diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index b870d118fa..689a1762a3 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -6,3 +6,6 @@ contact_links: - name: .NET platform and other product feedback url: https://developercommunity.visualstudio.com/spaces/61/index.html about: Log product issues here + - name: .NET Breaking Change + url: https://github.com/dotnet/docs/issues/new?assignees=&labels=&template=dotnet-breaking-change.md&title= + about: Breaking changes are documented in the .NET docs repo. diff --git a/.github/ISSUE_TEMPLATE/doc-issue.md b/.github/ISSUE_TEMPLATE/doc-issue.md index c338d9e80c..e6a7b6b38b 100644 --- a/.github/ISSUE_TEMPLATE/doc-issue.md +++ b/.github/ISSUE_TEMPLATE/doc-issue.md @@ -5,32 +5,40 @@ about: Report a problem in the .NET documentation **Before you open an issue** +(Delete this section before you submit your issue) + If the issue is: -- A simple typo or similar correction, consider submitting a PR to fix it instead of logging an issue. See [the contributor guide](https://docs.microsoft.com/contribute/#quick-edits-to-existing-documents) for instructions. -- A general support question, consider asking on a support forum site. -- A site design concern, create an issue at [MicrosoftDocs/feedback](https://github.com/MicrosoftDocs/feedback/issues/new/choose). +- A simple typo or similar correction, consider submitting a PR to fix it instead of logging an issue. See https://docs.microsoft.com/contribute/#quick-edits-to-existing-documents for instructions + +- A general support question, consider asking on a support forum site such as StackOverflow. + +- A site design concern, create an issue at https://github.com/MicrosoftDocs/feedback/issues/new/choose + - A problem completing a tutorial, compare your code with the completed sample. + - A duplicate of an open or closed issue, leave a comment on that issue. +(Delete the content above before you submit your issue) + **Issue description** -<include description here> +Include description here -**Target framework** +**.NET or .NET Framework** -Check the .NET target framework(s) being used, and include the version number(s). +Check the .NET target framework(s) being used, and include the version number(s). Put an `x` between the `[ ]` to check it. -- [ ] .NET Core +- [ ] .NET (5 or Core) - [ ] .NET Framework -- [ ] .NET Standard -If using the .NET Core SDK, include `dotnet --info` output. If using .NET Framework without the .NET Core SDK, include info from Visual Studio's **Help** > **About Microsoft Visual Studio** dialog. +**Technology** + +Check the .NET target framework(s) being used, and include the version number(s). Put an `x` between the `[ ]` to check it. + +- [ ] WPF +- [ ] Windows Forms -
-dotnet --info output or About VS info +**.NET information** -```console - -``` -
+If using the .NET SDK or .NET Core SDK, include `dotnet --info` output. If using .NET Framework without the .NET Core SDK, include info from Visual Studio's **Help** > **About Microsoft Visual Studio** dialog. diff --git a/.github/ISSUE_TEMPLATE/dotnet-breaking-change.md b/.github/ISSUE_TEMPLATE/dotnet-breaking-change.md deleted file mode 100644 index 0fbe711d67..0000000000 --- a/.github/ISSUE_TEMPLATE/dotnet-breaking-change.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -name: .NET Core breaking change -about: Report a change in .NET Core that breaks something that worked in a previous version (intended mostly for product-team use) ---- - - - -## [Change title] - -[Brief description of the change] - -### Version introduced - -[Version in which the breaking change first occurred (for example, 3.0 for .NET Core 3.0)] - -### Old behavior - -### New behavior - -### Reason for change - -### Recommended action - -[ Suggested steps if user is affected go here: -- Possible workarounds -- Example of code changes to handle change -] - -### Category - -[Choose a category from one of the following: - -- ASP.NET Core -- C# -- Core .NET libraries -- Cryptography -- Data -- Debugger -- Deployment -- Globalization -- Interop -- JIT -- LINQ -- Managed Extensibility Framework (MEF) -- MSBuild -- Networking -- Printing -- Security -- Serialization -- Visual Basic -- Windows Forms -- Windows Presentation Foundation (WPF) -- XML, XSLT -] - -### Affected APIs - -[ If no APIs are affected, this should read: - "Not detectable via API analysis" - - If affected APIs are identifiable, include a link for each. The link takes the form: - - `[friendly description of API](link to API on docs.microsoft.com)` - - For example, `[String.IndexOf(String)](https://docs.microsoft.com/dotnet/api/system.string.indexof#System_String_IndexOf_System_String_) - - For methods, if all overloads are affected, link to the general overloaded method page. For example: - - - - Otherwise, link to the individual method overload. For example: - - - -] - - - ---- -#### Issue metadata - -* Issue type: breaking-change diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 2ce82fbb8e..7cc95d61ba 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -5,8 +5,7 @@ "build_source_folder": "dotnet-desktop-guide", "build_output_subfolder": "dotnet-desktop-guide", "locale": "en-us", - "monikers": [], - "moniker_ranges": [], + "moniker_ranges": ["netframeworkdesktop-4.8", "netdesktop-5.0"], "filemap_share_depots": [ "VS.dotnet-api-docs" ], diff --git a/README.md b/README.md index 824a7c6d56..d7f27ae9b5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,22 @@ -## Microsoft Open Source Code of Conduct -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. \ No newline at end of file +# .NET Desktop Guide docs + +![Markdownlint](https://github.com/dotnet/docs-desktop/workflows/Markdownlint/badge.svg) + +This repository contains the conceptual documentation for .NET desktop technologies, such as Windows Presentation Foundation (WPF) and Windows Forms (WinForms). It's published at the [.NET Desktop Guide documentation site](https://docs.microsoft.com/dotnet/desktop). + +## Issues + +We have a large community using these resources. We make our best effort to respond to issues in a timely fashion. You can read more about our procedures for classifying and resolving issues in our [Issues policy](issues-policy.md) topic. + +We welcome contributions to help us improve and complete the .NET docs. This is a very large repo, covering a large area. If this is your first visit, see our [labels and projects roadmap](styleguide/labels-projects.md) for help navigating the issues and projects in this repository. + +## Migrate old examples + +If you're interested in helping migrate existing code that targets the .NET Framework (specifically WPF and WinForms) from the [retired Code Gallery](https://docs.microsoft.com/teamblog/msdn-code-gallery-retired) site to .NET Core applications stored in our [samples repository](https://github.com/dotnet/samples) and downloadable from the [Samples Browser](https://docs.microsoft.com/samples/browse), see the [Code Gallery migration](https://github.com/dotnet/docs/projects/88) project. The code gallery samples were moved to the [Microsoft Archive](https://github.com/microsoftarchive?q=msdn-code-gallery) organization. + +## Code of Conduct + +This project has adopted the code of conduct defined by the Contributor Covenant +to clarify expected behavior in our community. + +For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct). diff --git a/dotnet-desktop-guide/TOC.yml b/dotnet-desktop-guide/TOC.yml index b5ef71ac32..083f14ca85 100644 --- a/dotnet-desktop-guide/TOC.yml +++ b/dotnet-desktop-guide/TOC.yml @@ -1,2 +1,8 @@ -- name: Index - href: index.md \ No newline at end of file +items: +- name: Windows Forms + expanded: true + items: + - name: ".NET 5 (and .NET Core 3.1)" + href: https://docs.microsoft.com/dotnet/desktop/winforms/?view=netdesktop-5.0 + - name: .NET Framework + href: https://docs.microsoft.com/dotnet/desktop/winforms/?view=netframework-4-8 diff --git a/dotnet-desktop-guide/breadcrumb/toc.yml b/dotnet-desktop-guide/breadcrumb/toc.yml deleted file mode 100644 index 61d8fca61e..0000000000 --- a/dotnet-desktop-guide/breadcrumb/toc.yml +++ /dev/null @@ -1,3 +0,0 @@ -- name: Docs - tocHref: / - topicHref: / \ No newline at end of file diff --git a/dotnet-desktop-guide/docfx.json b/dotnet-desktop-guide/docfx.json index 80159a3983..14d3c3a668 100644 --- a/dotnet-desktop-guide/docfx.json +++ b/dotnet-desktop-guide/docfx.json @@ -16,7 +16,53 @@ "README.md", "LICENSE", "LICENSE-CODE", - "ThirdPartyNotices.md" + "ThirdPartyNotices.md", + "samples/**/*.*" + ], + "group": "framework", + "src": "framework" + }, + { + "files": [ + "**/*.md", + "**/*.yml" + ], + "exclude": [ + "**/obj/**", + "**/includes/**", + "_themes/**", + "_themes.pdf/**", + "**/docfx.json", + "_repo.en-us/**", + "README.md", + "LICENSE", + "LICENSE-CODE", + "ThirdPartyNotices.md", + "samples/**/*.*" + ], + "group": "net", + "src": "net" + }, + { + "files": [ + "**/*.md", + "**/*.yml" + ], + "exclude": [ + "framework", + "net", + + "**/obj/**", + "**/includes/**", + "_themes/**", + "_themes.pdf/**", + "**/docfx.json", + "_repo.en-us/**", + "README.md", + "LICENSE", + "LICENSE-CODE", + "ThirdPartyNotices.md", + "samples/**/*.*" ] } ], @@ -33,7 +79,47 @@ "_themes/**", "_themes.pdf/**", "**/docfx.json", - "_repo.en-us/**" + "_repo.en-us/**", + "samples/**/*.*" + ], + "group": "framework", + "src": "framework" + }, + { + "files": [ + "**/*.png", + "**/*.gif", + "**/*.jpg" + ], + "exclude": [ + "**/obj/**", + "**/includes/**", + "_themes/**", + "_themes.pdf/**", + "**/docfx.json", + "_repo.en-us/**", + "samples/**/*.*" + ], + "group": "net", + "src": "net" + }, + { + "files": [ + "**/*.png", + "**/*.gif", + "**/*.jpg" + ], + "exclude": [ + "framework", + "net", + + "**/obj/**", + "**/includes/**", + "_themes/**", + "_themes.pdf/**", + "**/docfx.json", + "_repo.en-us/**", + "samples/**/*.*" ] } ], @@ -41,10 +127,12 @@ "externalReference": [], "globalMetadata": { "breadcrumb_path": "/dotnet/desktop/breadcrumb/toc.json", - "extendBreadcrumb": true, + "extendBreadcrumb": false, "feedback_system": "GitHub", "feedback_github_repo": "dotnet/docs-desktop", - "feedback_product_url": "https://developercommunity.visualstudio.com/spaces/61/index.html" + "feedback_product_url": "https://developercommunity.visualstudio.com/spaces/61/index.html", + "author": "adegeo", + "ms.author": "adegeo" }, "fileMetadata": { "titleSuffix": { @@ -56,6 +144,16 @@ }, "template": [], "dest": "dotnet-desktop-guide", - "markdownEngineName": "markdig" + "markdownEngineName": "markdig", + "groups": { + "framework": { + "dest": "framework-dest", + "moniker_range": "netframeworkdesktop-4.8" + }, + "net": { + "dest": "net-dest", + "moniker_range": "netdesktop-5.0" + } + } } } \ No newline at end of file diff --git a/dotnet-desktop-guide/framework/breadcrumb/toc.yml b/dotnet-desktop-guide/framework/breadcrumb/toc.yml new file mode 100644 index 0000000000..1dac05392a --- /dev/null +++ b/dotnet-desktop-guide/framework/breadcrumb/toc.yml @@ -0,0 +1,25 @@ +items: +- name: Docs + tocHref: / + topicHref: / + items: + - name: .NET + tocHref: /dotnet/ + topicHref: /dotnet/index + items: + - name: Desktop Guide + tocHref: /dotnet/desktop + topicHref: /dotnet/desktop/index + items: + - name: .NET Framework + items: + - name: Windows Forms + tocHref: /dotnet/desktop/winforms + topicHref: /dotnet/desktop/winforms/index + items: + - name: Enhance Windows Forms applications + tocHref: /dotnet/desktop/winforms/advanced/ + topicHref: /dotnet/desktop/winforms/advanced/index + - name: Controls + tocHref: /dotnet/desktop/winforms/controls/ + topicHref: /dotnet/desktop/winforms/controls/index diff --git a/dotnet-desktop-guide/framework/winforms/additional-security-considerations-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/additional-security-considerations-in-windows-forms.md new file mode 100644 index 0000000000..c42cd8c2f9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/additional-security-considerations-in-windows-forms.md @@ -0,0 +1,91 @@ +--- +title: "Additional Security Considerations" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, secure calls to Windows API" + - "security [Windows Forms]" + - "security [Windows Forms], calling APIs" + - "Clipboard [Windows Forms], securing access" +ms.assetid: 15abda8b-0527-47c7-aedb-77ab595f2bf1 +--- +# Additional Security Considerations in Windows Forms +.NET Framework security settings might cause your application to run differently in a partial trust environment than on your local computer. The .NET Framework restricts access to such critical local resources as the file system, network, and unmanaged APIs, among other things. The security settings affect the ability to call the Microsoft Windows API or other APIs that cannot be verified by the security system. Security also affects other aspects of your application, including file and data access, and printing. For more information about file and data access in a partial trust environment, see [More Secure File and Data Access in Windows Forms](more-secure-file-and-data-access-in-windows-forms.md). For more information about printing in a partial trust environment, see [More Secure Printing in Windows Forms](more-secure-printing-in-windows-forms.md). + + The following sections discuss how to work with the Clipboard, perform window manipulation, and call the Windows API from applications that are running in a partial trust environment. + +## Clipboard Access + The class controls access to the Clipboard, and the associated enumeration value indicates the level of access. The following table shows the possible permission levels. + +|UIPermissionClipboard value|Description| +|---------------------------------|-----------------| +||The Clipboard can be used without restriction.| +||The Clipboard can be used with some restrictions. The ability to put data on the Clipboard (Copy or Cut command operations) is unrestricted. Intrinsic controls that accept paste, such as a text box, can accept Clipboard data, but user controls cannot programmatically read from the Clipboard.| +||The Clipboard cannot be used.| + + By default, the Local Intranet zone receives access and the Internet zone receives access. This means that the application can copy data to the Clipboard, but the application cannot programmatically paste to or read from the Clipboard. These restrictions prevent programs without full trust from reading content copied to the Clipboard by another application. If your application requires full Clipboard access but you do not have the permissions, you will have to elevate the permissions for your application. For more information about elevating permissions, see [General Security Policy Administration](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ed5htz45(v=vs.100)). + +## Window Manipulation + The class also controls permission to perform window manipulation and other UI-related actions, and the associated enumeration value indicates the level of access. The following table shows the possible permission levels. + + By default, the Local Intranet zone receives access and the Internet zone receives access. This means that in the Internet zone, the application can perform most windowing and UI actions, but the window's appearance will be modified. The modified window displays a balloon notification when first run, contains modified title bar text, and requires a close button on the title bar. The balloon notification and the title bar identify to the user of the application that the application is running under partial trust. + +|UIPermissionWindow value|Description| +|------------------------------|-----------------| +||Users can use all windows and user input events without restriction.| +||Users can use only safer top-level windows and safer subwindows for drawing, and can use only user input events for the user interface within those top-level windows and subwindows. These safer windows are clearly labeled and have minimum and maximum size restrictions. The restrictions prevent potentially harmful spoofing attacks, such as imitating system logon screens or the system desktop, and restricts programmatic access to parent windows, focus-related APIs, and use of the control,| +||Users can use only safer subwindows for drawing, and can use only user input events for the user interface within that subwindow. A control displayed within a browser is an example of a safer subwindow.| +||Users cannot use any windows or user interface events. No user interface can be used.| + + Each permission level identified by the enumeration allows fewer actions than the level above it. The following tables indicate the actions that are restricted by the and values. For exact permissions that are required for each member, see the reference for that member in the .NET Framework class library documentation. + + permission restricts the actions listed in the following table. + +|Component|Restricted actions| +|---------------|------------------------| +||- Setting the property.| +||- Getting the property.
- Setting the `Region` property.
- Calling the , , and , , , or method.
- Calling the method if the control returned is not a child of the calling control.
- Modify control focus inside a container control.| +||- Setting the property.
- Calling the method.| +||- Calling the method.| +||- Getting the or property.
- Setting the , , or property.
- Setting the property below 50%.
- Setting the property to programmatically.
- Calling the method.
- Using the , , and enumeration values.| +||- Using the component is completely restricted.| + + The value restricts the actions listed in the following table, in addition to the restrictions placed by the value. + +|Component|Restricted actions| +|---------------|------------------------| +||- Showing a dialog box derived from the class.| +||- Calling the method.
- Setting the property.| +||- Setting the property.| +||- Calling the method.| + +### Hosting Third-Party Controls + Another kind of window manipulation can occur if your forms host third-party controls. A third-party control is any custom that you have not developed and compiled yourself. Although the hosting scenario is hard to exploit, it is theoretically possible for a third-party control to expand its rendering surface to cover the entire area of your form. This control could then mimic a critical dialog box, and request information such as username/password combinations or bank account numbers from your users. + + To limit this potential risk, use third-party controls only from vendors you can trust. If you use third-party controls you have downloaded from an unverifiable source, we recommend that you review the source code for potential exploits. After you've verified that the source is non-malicious, you should compile the assembly yourself to ensure that the source matches the assembly. + +## Windows API Calls + If your application design requires calling a function from the Windows API, you are accessing unmanaged code. In this case the code's actions to the window or operating system cannot be determined when you are working with Windows API calls or values. The class and the value of the enumeration control access to unmanaged code. An application can access unmanaged code only when it is granted the permission. By default, only applications that are running locally can call unmanaged code. + + Some Windows Forms members provide unmanaged access that requires the permission. The following table lists the members in the namespace that require the permission. For more information about the permissions that are required for a member, see the .NET Framework class library documentation. + +|Component|Member| +|---------------|------------| +||- method
- property
- `Exit` method
- method
- event| +||- method
- \ method
- method
- method| +||- method
- method
- method
- method| +||- methods
- method| +||- class| +||- method| +||- method
- method| + + If your application does not have permission to call unmanaged code, your application must request permission, or you must consider alternative ways of implementing features; in many cases, Windows Forms provides a managed alternative to Windows API functions. If no alternative means exist and the application must access unmanaged code, you will have to elevate the permissions for the application. + + Permission to call unmanaged code allows an application to perform most anything. Therefore, permission to call unmanaged code should only be granted for applications that come from a trusted source. Alternatively, depending on the application, the piece of application functionality that makes the call to unmanaged code could be optional, or enabled in the full trust environment only. For more information about dangerous permissions, see [Dangerous Permissions and Policy Administration](https://docs.microsoft.com/dotnet/framework/misc/dangerous-permissions-and-policy-administration). For more information about elevating permissions, see [General Security Policy Administration](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ed5htz45(v=vs.100)). + +## See also + +- [More Secure File and Data Access in Windows Forms](more-secure-file-and-data-access-in-windows-forms.md) +- [More Secure Printing in Windows Forms](more-secure-printing-in-windows-forms.md) +- [Security in Windows Forms Overview](security-in-windows-forms-overview.md) +- [Windows Forms Security](windows-forms-security.md) +- [Securing ClickOnce Applications](/visualstudio/deployment/securing-clickonce-applications) diff --git a/dotnet-desktop-guide/framework/winforms/adjusting-the-size-and-scale-of-windows-forms.md b/dotnet-desktop-guide/framework/winforms/adjusting-the-size-and-scale-of-windows-forms.md new file mode 100644 index 0000000000..84cee13e28 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/adjusting-the-size-and-scale-of-windows-forms.md @@ -0,0 +1,35 @@ +--- +title: "Adjust the size and scale" +ms.date: "04/07/2017" +helpviewer_keywords: + - "Windows Forms, changing size" + - "Windows Forms, adjusting size" + - "Windows Forms, changing scale" +ms.assetid: a014d2b3-3273-4521-95e1-00171033bf58 +--- +# Adjusting the size and scale of Windows Forms +This topic provides links to information about resizing Windows Forms. + +## In This Section + [How to: Resize Windows Forms](how-to-resize-windows-forms.md) + Provides instructions for specifying the size of Windows Forms. + + [Automatic Scaling in Windows Forms](automatic-scaling-in-windows-forms.md) + Discusses how automatic scaling enables a form and its controls to be displayed appropriately between machines. + + [High DPI Support in Windows Forms](high-dpi-support-in-windows-forms.md) + Discusses Windows Forms' support for High DPI and dynamic scaling. + +## Reference + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + +## Related sections + [Changing the appearance of Windows Forms](changing-the-appearance-of-windows-forms.md) + Provides links to topics describing other ways to change the appearance of Windows Forms. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/about-gdi-managed-code.md b/dotnet-desktop-guide/framework/winforms/advanced/about-gdi-managed-code.md new file mode 100644 index 0000000000..8454c5fb06 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/about-gdi-managed-code.md @@ -0,0 +1,61 @@ +--- +title: "About GDI+ Managed Code" +ms.date: "03/30/2017" +helpviewer_keywords: + - "GDI+, about GDI+" + - "GDI+" + - "graphics [Windows Forms], GDI+" +ms.assetid: a98a76ab-e455-49c9-891c-0491ac932f2c +--- +# About GDI+ Managed Code + +GDI+ is the portion of the Windows operating system that provides two-dimensional vector graphics, imaging, and typography. GDI+ improves on GDI (the Graphics Device Interface included with earlier versions of Windows) by adding new features and by optimizing existing features. + +The GDI+ managed class interface (a set of wrappers) is part of the .NET Framework, an environment for building, deploying, and running XML Web services and other applications. + +This section provides information about the GDI+ API for programmers using managed code. + +## In this section + +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) + Discusses vector graphics. + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) + Discusses the type of images available and how to work with them. + +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) + Discusses how to transform graphics with GDI+. + +## Reference + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +- + Describes this class and has links to all its members. + +## Related sections + +[Using Managed Graphics Classes](using-managed-graphics-classes.md)\ +Contains links to topics that demonstrate how to use the `Graphics` programming interface. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/alpha-blending-lines-and-fills.md b/dotnet-desktop-guide/framework/winforms/advanced/alpha-blending-lines-and-fills.md new file mode 100644 index 0000000000..9c3a7696e4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/alpha-blending-lines-and-fills.md @@ -0,0 +1,37 @@ +--- +title: "Alpha Blending Lines and Fills" +ms.date: "03/30/2017" +helpviewer_keywords: + - "lines [Windows Forms], adding transparency" + - "examples [Windows Forms], alpha blending" + - "alpha blending [Windows Forms], using with lines" + - "alpha blending" + - "lines [Windows Forms], alpha blending" + - "fills [Windows Forms], alpha blending" + - "alpha blending [Windows Forms], using with fills" + - "shapes [Windows Forms], adding transparency" +ms.assetid: 5440f48c-3ac9-44c3-b170-c1c110bdbab8 +--- +# Alpha Blending Lines and Fills +In GDI+, a color is a 32-bit value with 8 bits each for alpha, red, green, and blue. The alpha value indicates the transparency of the color — the extent to which the color is blended with the background color. Alpha values range from 0 through 255, where 0 represents a fully transparent color, and 255 represents a fully opaque color. + + Alpha blending is a pixel-by-pixel blending of source and background color data. Each of the three components (red, green, blue) of a given source color is blended with the corresponding component of the background color according to the following formula: + + displayColor = sourceColor × alpha / 255 + backgroundColor × (255 – alpha) / 255 + + For example, suppose the red component of the source color is 150 and the red component of the background color is 100. If the alpha value is 200, the red component of the resultant color is calculated as follows: + + 150 × 200 / 255 + 100 × (255 – 200) / 255 = 139 + +## In This Section + [How to: Draw Opaque and Semitransparent Lines](how-to-draw-opaque-and-semitransparent-lines.md) + Shows how to draw alpha-blended lines. + + [How to: Draw with Opaque and Semitransparent Brushes](how-to-draw-with-opaque-and-semitransparent-brushes.md) + Explains how to alpha-blend with brushes. + + [How to: Use Compositing Mode to Control Alpha Blending](how-to-use-compositing-mode-to-control-alpha-blending.md) + Describes how to control alpha blending using . + + [How to: Use a Color Matrix to Set Alpha Values in Images](how-to-use-a-color-matrix-to-set-alpha-values-in-images.md) + Explains how to use a object to control alpha blending. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/antialiasing-with-lines-and-curves.md b/dotnet-desktop-guide/framework/winforms/advanced/antialiasing-with-lines-and-curves.md new file mode 100644 index 0000000000..36684a0007 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/antialiasing-with-lines-and-curves.md @@ -0,0 +1,45 @@ +--- +title: "Antialiasing with Lines and Curves" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "antialiasing" + - "antialiasing [Windows Forms], smoothing modes" + - "GDI+, antialiasing" +ms.assetid: 810da1a4-c136-4abf-88df-68e49efdd8d4 +--- +# Antialiasing with Lines and Curves +When you use GDI+ to draw a line, you provide the starting point and ending point of the line, but you do not have to provide any information about the individual pixels on the line. GDI+ works in conjunction with the display driver software to determine which pixels will be turned on to show the line on a particular display device. + +## Aliasing + Consider the straight red line that goes from the point (4, 2) to the point (16, 10). Assume the coordinate system has its origin in the upper-left corner and that the unit of measure is the pixel. Also assume that the x-axis points to the right and the y-axis points down. The following illustration shows an enlarged view of the red line drawn on a multicolored background. + + ![Line, no antialiasing](./media/aboutgdip02-art33.gif "AboutGdip02_Art33") + + The red pixels used to render the line are opaque. There are no partially transparent pixels in the line. This type of line rendering gives the line a jagged appearance, and the line looks somewhat like a staircase. This technique of representing a line with a staircase is called aliasing; the staircase is an alias for the theoretical line. + +## Antialiasing + A more sophisticated technique for rendering a line involves using partially transparent pixels along with opaque pixels. Pixels are set to pure red, or to some blend of red and the background color, depending on how close they are to the line. This type of rendering is called antialiasing and results in a line that the human eye perceives as more smooth. The following illustration shows how certain pixels are blended with the background to produce an antialiased line. + + ![Antialiasing a Line](./media/aboutgdip02-art34.gif "AboutGdip02_Art34") + + Antialiasing, also called smoothing, can also be applied to curves. The following illustration shows an enlarged view of a smoothed ellipse. + + ![Antialiasing Curves](./media/aboutgdip02-art35.gif "AboutGdip02_Art35") + + The following illustration shows the same ellipse in its actual size, once without antialiasing and once with antialiasing. + + ![Antialiasing example](./media/aboutgdip02-art36.gif "AboutGdip02_Art36") + + To draw lines and curves that use antialiasing, create an instance of the class and set its property to or . Then call one of the drawing methods of that same class. + + [!code-csharp[LinesCurvesAndShapes#81](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#81)] + [!code-vb[LinesCurvesAndShapes#81](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#81)] + +## See also + +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Use Antialiasing with Text](how-to-use-antialiasing-with-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/application-settings-architecture.md b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-architecture.md new file mode 100644 index 0000000000..19b2840185 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-architecture.md @@ -0,0 +1,151 @@ +--- +title: "Application Settings Architecture" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "application settings [Windows Forms], architecture" +ms.assetid: c8eb2ad0-fac6-4ea2-9140-675a4a44d562 +--- +# Application Settings Architecture +This topic describes how the Application Settings architecture works, and explores advanced features of the architecture, such as grouped settings and settings keys. + + The application settings architecture supports defining strongly typed settings with either application or user scope, and persisting the settings between application sessions. The architecture provides a default persistence engine for saving settings to and loading them from the local file system. The architecture also defines interfaces for supplying a custom persistence engine. + + Interfaces are provided that enable custom components to persist their own settings when they are hosted in an application. By using settings keys, components can keep settings for multiple instances of the component separate. + +## Defining Settings + The application settings architecture is used within both ASP.NET and Windows Forms, and it contains a number of base classes that are shared across both environments. The most important is , which provides access to settings through a collection, and provides low-level methods for loading and saving settings. Each environment implements its own class derived from to provide additional settings functionality for that environment. In a Windows Forms-based application, all application settings must be defined on a class derived from the class, which adds the following functionality to the base class: + +- Higher-level loading and saving operations + +- Support for user-scoped settings + +- Reverting a user's settings to the predefined defaults + +- Upgrading settings from a previous application version + +- Validating settings, either before they are changed or before they are saved + + The settings can be described using a number of attributes defined within the namespace; these are described in [Application Settings Attributes](application-settings-attributes.md). When you define a setting, you must apply it with either or , which describes whether the setting applies to the entire application or just to the current user. + + The following code example defines a custom settings class with a single setting, `BackgroundColor`. + + [!code-csharp[ApplicationSettings.Create#1](~/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/MyAppSettings.cs#1)] + [!code-vb[ApplicationSettings.Create#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/MyAppSettings.vb#1)] + +## Settings Persistence + The class does not itself persist or load settings; this job falls to the settings provider, a class that derives from . If a derived class of does not specify a settings provider through the , then the default provider, , is used. + + The configuration system that was originally released with the .NET Framework supports providing static application configuration data through either the local computer's machine.config file or within an `app.`exe.config file that you deploy with your application. The class expands this native support in the following ways: + +- Application-scoped settings can be stored in either the machine.config or `app.`exe.config files. Machine.config is always read-only, while `app`.exe.config is restricted by security considerations to read-only for most applications. + +- User-scoped settings can be stored in `app`.exe.config files, in which case they are treated as static defaults. + +- Non-default user-scoped settings are stored in a new file, *user*.config, where *user* is the user name of the person currently executing the application. You can specify a default for a user-scoped setting with . Because user-scoped settings often change during application execution, `user`.config is always read/write. + + All three configuration files store settings in XML format. The top-level XML element for application-scoped settings is ``, while `` is used for user-scoped settings. An `app`.exe.config file which contains both application-scoped settings and defaults for user-scoped settings would look like this: + +```xml + + + + +
+ + +
+ + + + + + Default + + + False + + + + + + + Form1 + + + 595, 536 + + + + +``` + + For a definition of the elements within the application settings section of a configuration file, see [Application Settings Schema](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/application-settings-schema). + +### Settings Bindings + Application settings uses the Windows Forms data binding architecture to provide two-way communication of settings updates between the settings object and components. If you use Visual Studio to create application settings and assign them to component properties, these bindings are generated automatically. + + You can only bind an application setting to a component that supports the interface. Also, the component must implement a change event for a specific bound property, or notify application settings that the property has changed through the interface. If the component does not implement and you are binding through Visual Studio, the bound properties will be set the first time, but will not update. If the component implements but does not support property change notifications, the binding will not update in the settings file when the property is changed. + + Some Windows Forms components, such as , do not support settings bindings. + +### Settings Serialization + When must save settings to disk, it performs the following actions: + +1. Uses reflection to examine all of the properties defined on your derived class, finding those that are applied with either or . + +2. Serializes the property to disk. It first attempts to call the or on the type's associated . If this does not succeed, it uses XML serialization instead. + +3. Determines which settings go in which files, based on the setting's attribute. + + If you implement your own settings class, you can use the to mark a setting for either binary or custom serialization using the enumeration. For more information on creating your own settings class in code, see [How to: Create Application Settings](how-to-create-application-settings.md). + +### Settings File Locations + The location of the `app`.exe.config and *user*.config files will differ based on how the application is installed. For a Windows Forms-based application copied onto the local computer, `app`.exe.config will reside in the same directory as the base directory of the application's main executable file, and *user*.config will reside in the location specified by the property. For an application installed by means of ClickOnce, both of these files will reside in the ClickOnce Data Directory underneath %InstallRoot%\Documents and Settings\\*username*\Local Settings. + + The storage location of these files is slightly different if a user has enabled roaming profiles, which enables a user to define different Windows and application settings when they are using other computers within a domain. In that case, both ClickOnce applications and non-ClickOnce applications will have their `app`.exe.config and *user*.config files stored under %InstallRoot%\Documents and Settings\\*username*\Application Data. + + For more information about how the Application Settings feature works with the new deployment technology, see [ClickOnce and Application Settings](/visualstudio/deployment/clickonce-and-application-settings). For more information about the ClickOnce Data Directory, see [Accessing Local and Remote Data in ClickOnce Applications](/visualstudio/deployment/accessing-local-and-remote-data-in-clickonce-applications). + +## Application Settings and Security + Application settings are designed to work in partial trust, a restricted environment that is the default for Windows Forms applications hosted over the Internet or an intranet. No special permissions beyond partial trust are needed to use application settings with the default settings provider. + + When application settings are used in a ClickOnce application, the `user`.config file is stored in the ClickOnce data directory. The size of the application's `user`.config file cannot exceed the data directory quota set by ClickOnce. For more information, see [ClickOnce and Application Settings](/visualstudio/deployment/clickonce-and-application-settings). + +## Custom Settings Providers + In the Application Settings architecture, there is a loose coupling between the applications settings wrapper class, derived from , and the associated settings provider or providers, derived from . This association is defined only by the applied to the wrapper class or its individual properties. If a settings provider is not explicitly specified, the default provider, , is used. As a result, this architecture supports creating and using custom settings providers. + + For example, suppose that you want to develop and use `SqlSettingsProvider`, a provider that will store all settings data in a Microsoft SQL Server database. Your -derived class would receive this information in its `Initialize` method as a parameter of type . You would then implement the method to retrieve your settings from the data store, and to save them. Your provider can use the supplied to to determine the property's name, type, and scope, as well as any other settings attributes defined for that property. + + Your provider will need to implement one property and one method whose implementations may not be obvious. The property is an abstract property of ; you should program it to return the following: + + [!code-csharp[ApplicationSettings.Architecture#2](~/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/DummyClass.cs#2)] + [!code-vb[ApplicationSettings.Architecture#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/DummyProviderClass.vb#2)] + + Your derived class must also implement an `Initialize` method that takes no arguments and returns no value. This method is not defined by . + + Finally, you implement on your provider to provide support for refreshing settings, reverting settings to their defaults, and upgrading settings from one application version to another. + + Once you have implemented and compiled your provider, you need to instruct your settings class to use this provider instead of the default. You accomplish this through the . If applied to an entire settings class, the provider is used for each setting that the class defines; if applied to individual settings, Application Settings architecture uses that provider for those settings only, and uses for the rest. The following code example shows how to instruct the settings class to use your custom provider. + + [!code-csharp[ApplicationSettings.Architecture#1](~/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/DummyClass.cs#1)] + [!code-vb[ApplicationSettings.Architecture#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/DummyProviderClass.vb#1)] + + A provider may be called from multiple threads simultaneously, but it will always write to the same storage location; therefore, the Application Settings architecture will only ever instantiate a single instance of your provider class. + +> [!IMPORTANT] +> You should ensure that your provider is thread-safe, and only allows one thread at a time to write to the configuration files. + + Your provider does not need to support all of the settings attributes defined in the namespace, though it must at a minimum support and , and should also support . For those attributes that it does not support, your provider should just fail without notification; it should not throw an exception. If the settings class uses an invalid combination of attributes, however — such as applying and to the same setting — your provider should throw an exception and cease operation. + +## See also + +- +- +- +- [Application Settings Overview](application-settings-overview.md) +- [Application Settings for Custom Controls](application-settings-for-custom-controls.md) +- [ClickOnce and Application Settings](/visualstudio/deployment/clickonce-and-application-settings) +- [Application Settings Schema](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/application-settings-schema) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/application-settings-attributes.md b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-attributes.md new file mode 100644 index 0000000000..94e134a0a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-attributes.md @@ -0,0 +1,39 @@ +--- +title: "Application Settings Attributes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], attributes" + - "attributes [Windows Forms], application settings" + - "wrapper classes [Windows Forms], application settings" +ms.assetid: 53caa66c-a9fb-43a5-953c-ad092590098d +--- +# Application Settings Attributes +The Application Settings architecture provides many attributes that can be applied either to the applications settings wrapper class or its individual properties. These attributes are examined at run time by the application settings infrastructure, often specifically the settings provider, in order to tailor its functioning to the stated needs of the custom wrapper. + + The following table lists the attributes that can be applied to the application settings wrapper class, this class's individual properties, or both. By definition, only a single scope attribute—**UserScopedSettingAttribute** or **ApplicationScopedSettingAttribute**—must be applied to each and every settings property. + +> [!NOTE] +> A custom settings provider, derived from the class, is only required to recognize the following three attributes: **ApplicationScopedSettingAttribute**, **UserScopedSettingAttribute**, and **DefaultSettingValueAttribute**. + +|Attribute|Target|Description| +|---------------|------------|-----------------| +||Both|Specifies the short name of the settings provider to use for persistence.

If this attribute is not supplied, the default provider, , is assumed.| +||Both|Defines a property as a user-scoped application setting.| +||Both|Defines a property as an application-scoped application setting.| +||Property|Specifies a string that can be deserialized by the provider into the hard-coded default value for this property.

The does not require this attribute, and will override any value provided by this attribute if there is a value already persisted.| +||Property|Provides the descriptive test for an individual setting, used primarily by run-time and design-time tools.| +||Class|Provides an explicit name for a settings group. If this attribute is missing, uses the wrapper class name.| +||Class|Provides the descriptive test for a settings group, used primarily by run-time and design-time tools.| +||Both|Specifies zero or more manageability services that should be provided to the settings group or property. The available services are described by the enumeration.| +||Property|Indicates that a setting belongs to a special, predefined category, such as a connection string, that suggests special processing by the settings provider. The predefined categories for this attribute are defined by the enumeration.| +||Both|Specifies a preferred serialization mechanism for a settings group or property. The available serialization mechanisms are defined by the enumeration.| +||Property|Specifies that a settings provider should disable all application upgrade functionality for the marked property.| + + *Class* indicates that the attribute can be applied only to an application settings wrapper class. *Property* indicates that the attribute can be applied only settings properties. *Both* indicates that the attribute can be applied at either level. + +## See also + +- +- +- [Application Settings Architecture](application-settings-architecture.md) +- [How to: Create Application Settings](how-to-create-application-settings.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/application-settings-for-custom-controls.md b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-for-custom-controls.md new file mode 100644 index 0000000000..381e92e6f4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-for-custom-controls.md @@ -0,0 +1,46 @@ +--- +title: "Application Settings for Custom Controls" +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], application settings" + - "application settings [Windows Forms], custom controls" +ms.assetid: f44afb74-76cc-44f2-890a-44b7cdc211a1 +--- +# Application Settings for Custom Controls +You must complete certain tasks to give your custom controls the ability to persist application settings when the controls are hosted in third-party applications. + + Most of the documentation about the Application Settings feature is written under the assumption that you are creating a standalone application. However, if you are creating a control that other developers will host in their applications, you need to take a few additional steps for your control to persist its settings properly. + +## Application Settings and Custom Controls + For your control to properly persist its settings, it must encapsulate the process by creating its own dedicated applications settings wrapper class, derived from . Additionally, the main control class must implement the . The interface contains several properties as well as two methods, and . If you add your control to a form using the **Windows Forms Designer** in Visual Studio, Windows Forms will call automatically when the control is initialized; you must call yourself in the `Dispose` method of your control. + + In addition, you should implement the following in order for application settings for custom controls to work properly in design-time environments such as Visual Studio: + +1. A custom application settings class with a constructor that takes an as a single parameter. Use this class to save and load all of your application settings. When you create a new instance of this class, pass your custom control using the constructor. + +2. Create this custom settings class after the control has been created and placed on a form, such as in the form's event handler. + + For instructions on creating a custom settings class, see [How to: Create Application Settings](how-to-create-application-settings.md). + +## Settings Keys and Shared Settings + Some controls can be used multiple times within the same form. Most of the time, you will want these controls to persist their own individual settings. With the property on , you can supply a unique string that acts to disambiguate multiple versions of a control on a form. + + The simplest way to implement is to use the property of the control for the . When you load or save the control's settings, you pass the value of on to the property of the class. Application Settings uses this unique key when it persists the user's settings to XML. The following code example shows how a `` section may look for an instance of a custom control named `CustomControl1` that saves a setting for its `Text` property. + +```xml + + + + Hello, World + + + +``` + + Any instances of a control that do not supply a value for will share the same settings. + +## See also + +- +- +- [Application Settings Architecture](application-settings-architecture.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/application-settings-for-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-for-windows-forms.md new file mode 100644 index 0000000000..a806db7b36 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-for-windows-forms.md @@ -0,0 +1,40 @@ +--- +title: "Application Settings" +ms.date: "04/07/2017" +f1_keywords: + - "ClientApplicationSettings" +helpviewer_keywords: + - "application settings [Windows Forms]" + - "Windows Forms, application settings" +ms.assetid: 64090a34-8556-4904-8ea0-20efe9f8c886 +--- +# Application Settings for Windows Forms +The Applications Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client. With Application Settings, you can store not only application data such as database connection strings, but also user-specific data, such as toolbar positions and most-recently used lists. + +## In This Section + [Application Settings Overview](application-settings-overview.md) + Discusses how to create and store settings data on behalf of your application and your users. + + [Application Settings Architecture](application-settings-architecture.md) + Describes how the Application Settings feature works, and explores advanced features of the architecture such as grouped settings and settings keys. + + [Application Settings Attributes](application-settings-attributes.md) + Lists and describes the attributes that can be applied to an application settings wrapper class or its settings properties. + + [Application Settings for Custom Controls](application-settings-for-custom-controls.md) + Discusses what must be done to give your custom controls the ability to persist application settings when hosted in third-party applications. + + [How to: Create Application Settings](how-to-create-application-settings.md) + Demonstrates creating new application settings that are persisted between application sessions. + + [How to: Validate Application Settings](how-to-validate-application-settings.md) + Demonstrates validating application settings before they are persisted. + +## Related topics + +[Windows Forms Configuration Section](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/winforms/index) +Documents the settings to enable High DPI support in Windows Forms Application starting with the .NET Framework 4.7. + +## See also + +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/application-settings-overview.md b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-overview.md new file mode 100644 index 0000000000..c1d2378801 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/application-settings-overview.md @@ -0,0 +1,57 @@ +--- +title: "Application Settings Overview" +description: Learn about the Application Settings feature of Windows Forms, for example how to create and store settings data on behalf of your application and your users. +ms.date: "03/30/2017" +f1_keywords: + - "ApplicationsSettingsOverview" +helpviewer_keywords: + - "application settings [Windows Forms], about application settings" + - "dynamic properties" + - "user preferences [Windows Forms], tracking" +ms.assetid: 0dd8bca5-a6bf-4ac4-8eec-5725d08b38dc +--- +# Application Settings Overview + +This article discusses how to create and store settings data on behalf of your application and your users. + + The Application Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client computer. With Windows Forms application settings, you can store not only application data such as database connection strings, but also user-specific data, such as user application preferences. Using Visual Studio or custom managed code, you can create new settings, read them from and write them to disk, bind them to properties on your forms, and validate settings data prior to loading and saving. + + Application settings enables developers to save state in their application using very little custom code, and is a replacement for dynamic properties in previous versions of the .NET Framework. Application settings contains many improvements over dynamic properties, which are read-only, late-bound, and require more custom programming. The dynamic property classes have been retained in .NET Framework 2.0, but they are just shell classes that thinly wrap the application settings classes. + +## What Are Application Settings? + Your Windows Forms applications will often require data that's critical to running the application, but which you don't want to include directly in the application's code. If your application uses a Web Service or a database server, you may want to store this information in a separate file, so that you can change it in the future without recompiling. Similarly, your applications may require storing data that is specific to the current user. Most applications, for example, have user preferences that customize the application's appearance and behavior. + + Application settings addresses both needs by providing an easy way to store both application-scoped and user-scoped settings on the client computer. Using Visual Studio or a code editor, you define a setting for a given property by specifying its name, data type, and scope (application or user). You can even place related settings into named groups for easier use and readability. Once defined, these settings are persisted and read back into memory automatically at run time. A pluggable architecture enables the persistence mechanism to be changed, but by default, the local file system is used. + + Application settings works by persisting data as XML to different configuration (.config) files, corresponding to whether the setting is application-scoped or user-scoped. In most cases, the application-scoped settings are read-only; because they are program information, you will typically not need to overwrite them. By contrast, user-scoped settings can be read and written safely at run time, even if your application runs under partial trust. For more information about partial trust, see [Security in Windows Forms Overview](../security-in-windows-forms-overview.md). + + Settings are stored as XML fragments in configuration files. Application-scoped settings are represented by the `` element, and generally are placed in *app*.exe.config, where *app* is the name of your main executable file. User-scoped settings are represented by the `` element and are placed in *user*.config, where *user* is the user name of the person currently running the application. You must deploy the *app*.exe.config file with your application; the settings architecture will create the *user*.config files on demand the first time the application saves settings for that user. You can also define a `` block within *app*.exe.config to provide default values for user-scoped settings. + + Custom controls can also save their own settings by implementing the interface, which exposes the method. The Windows Forms control implements this interface to save the position of toolbars and toolbar items between application sessions. For more information about custom controls and application settings, see [Application Settings for Custom Controls](application-settings-for-custom-controls.md). + +## Limitations of Application Settings + You cannot use application settings in an unmanaged application that hosts the .NET Framework. Settings will not work in such environments as Visual Studio add-ins, C++ for Microsoft Office, control hosting in Internet Explorer, or Microsoft Outlook add-ins and projects. + + You currently cannot bind to some properties in Windows Forms. The most notable example is the property, as binding to this property would cause unpredictable behavior at run time. You can usually work around these issues by saving and loading these settings programmatically. + + Application settings has no built-in facility for encrypting information automatically. You should never store security-related information, such as database passwords, in clear text. If you want to store such sensitive information, you as the application developer are responsible for making sure it is secure. If you want to store connection strings, we recommend that you use Windows Integrated Security and not resort to hard-coding passwords into the URL. For more information, see [Code Access Security and ADO.NET](https://docs.microsoft.com/dotnet/framework/data/adonet/code-access-security). + +## Getting Started with Application Settings + If you use Visual Studio, you can define settings within the Windows Forms Designer using the **(ApplicationSettings)** property in the **Properties** window. When you define settings this way, Visual Studio automatically creates a custom managed wrapper class that associates each setting with a class property. Visual Studio also takes care of binding the setting to a property on a form or control so that the control's settings are restored automatically when its form is displayed, and saved automatically when the form is closed. + + If you want more detailed control over your settings, you can define your own custom applications settings wrapper class. This is accomplished by deriving a class from , adding a property that corresponds to each setting, and applying special attributes to these properties. For details about creating wrapper classes, see [Application Settings Architecture](application-settings-architecture.md). + + You can also use the class to bind settings programmatically to properties on forms and controls. + +## See also + +- +- +- +- +- [How to: Validate Application Settings](how-to-validate-application-settings.md) +- [Managing Application Settings (.NET)](/visualstudio/ide/managing-application-settings-dotnet) +- [How To: Read Settings at Run Time With C#](how-to-read-settings-at-run-time-with-csharp.md) +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [Application Settings Architecture](application-settings-architecture.md) +- [Application Settings for Custom Controls](application-settings-for-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/bezier-splines-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/bezier-splines-in-gdi.md new file mode 100644 index 0000000000..2c4ff29e5f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/bezier-splines-in-gdi.md @@ -0,0 +1,41 @@ +--- +title: "Bézier Splines in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Bezier splines" + - "splines [Windows Forms], Bezier" + - "GDI+, Bezier splines" +ms.assetid: 5774ce1e-87d4-4bc7-88c4-4862052781b8 +--- +# Bézier Splines in GDI+ +A Bézier spline is a curve specified by four points: two end points (p1 and p2) and two control points (c1 and c2). The curve begins at p1 and ends at p2. The curve does not pass through the control points, but the control points act as magnets, pulling the curve in certain directions and influencing the way the curve bends. The following illustration shows a Bézier curve along with its endpoints and control points. + + ![Bezier Splines](./media/aboutgdip02-art11a.gif "Aboutgdip02_art11a") + + The curve starts at p1 and moves toward the control point c1. The tangent line to the curve at p1 is the line drawn from p1 to c1. The tangent line at the endpoint p2 is the line drawn from c2 to p2. + +## Drawing Bézier Splines + To draw a Bézier spline, you need an instance of the class and a . The instance of the class provides the method, and the stores attributes, such as width and color, of the line used to render the curve. The is passed as one of the arguments to the method. The remaining arguments passed to the method are the endpoints and the control points. The following example draws a Bézier spline with starting point (0, 0), control points (40, 20) and (80, 150), and ending point (100, 10): + + [!code-csharp[LinesCurvesAndShapes#71](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#71)] + [!code-vb[LinesCurvesAndShapes#71](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#71)] + + The following illustration shows the curve, the control points, and two tangent lines. + + ![Bezier Splines](./media/aboutgdip02-art12.gif "Aboutgdip02_art12") + + Bézier splines were originally developed by Pierre Bézier for design in the automotive industry. They have since proven to be useful in many types of computer-aided design and are also used to define the outlines of fonts. Bézier splines can yield a wide variety of shapes, some of which are shown in the following illustration. + + ![Paths](./media/aboutgdip02-art13.gif "Aboutgdip02_art13") + +## See also + +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [Constructing and Drawing Curves](constructing-and-drawing-curves.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) +- [How to: Create a Pen](how-to-create-a-pen.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/bi-directional-support-for-windows-forms-applications.md b/dotnet-desktop-guide/framework/winforms/advanced/bi-directional-support-for-windows-forms-applications.md new file mode 100644 index 0000000000..7f233250d5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/bi-directional-support-for-windows-forms-applications.md @@ -0,0 +1,114 @@ +--- +title: Bi-Directional Support +ms.date: "09/30/2017" +helpviewer_keywords: + - "globalization [Windows Forms], bi-directional support in Windows" + - "Windows Forms, international" + - "localization [Windows Forms], bi-directional support in Windows" + - "bi-directional language support [Windows Forms], Windows applications" + - "Windows Forms, bi-directional support" +--- +# Bi-Directional Support for Windows Forms Applications +You can use Visual Studio to create Windows-based applications that support bi-directional (right-to-left) languages such as Arabic and Hebrew. This includes standard forms, dialog boxes, MDI forms, and all the controls you can work with in these forms—that is, all the objects in the namespace. + +## Culture Support + Culture and UI culture settings determine how an application works with dates, times, currency, and other information. Support for culture and UI culture is the same for bi-directional languages as it is for any other languages. For more information, see [Culture-specific classes for global Windows forms and web forms](/visualstudio/ide/globalizing-and-localizing-applications). + +## RightToLeft and RightToLeftLayout Properties + The base class, from which forms derive, includes a property that you can set to change the reading order of a form and its controls. If you set the form's property, by default controls on the form inherit this setting. However, you can also set the property individually on most controls. Also see [How to: Display Right-to-Left Text in Windows Forms for Globalization](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/7d3337xw(v=vs.100)). + + The effect of the property can differ from one control to another. In some controls the property only sets the reading order, as in the , and controls. In other controls, the property changes both reading order and layout. This includes the , and controls. Other controls require that the property be applied to mirror its layout from right to left. The following table provides details on how the and properties affect individual Windows Forms controls. + +|Control/Component|Effect of RightToLeft property|Effect of RightToLeftLayout property|Requires mirroring?| +|------------------------|------------------------------------|------------------------------------------|-------------------------| +||Sets the RTL reading order. Reverses , , and |No effect|No| +||The check box is displayed on the right side of the text|No effect|No| +||All the check boxes are displayed on the right side of the text|No effect|No| +||Not affected; depends on the language of the operating system|No effect|No| +||Items in combo box control are right-aligned|No effect|No| +||Appears right-aligned with RTL reading order|No effect|No| +||Appears right-aligned with RTL reading order|No effect|No| +||Affects both RTL reading order and control layout|No effect|No| +||Not affected; depends on the language of the operating system|Mirrors the control|Yes| +||Left-aligns the up and down buttons|No effect|No| +||Not supported|No effect|No| +||Depends on the language of the operating system|No effect|No| +||Sets RTL reading order, and reverses scrollbars|Mirrors the form|Yes| +||The caption is displayed right aligned. Child controls may inherit this property.|Use a within the control for right-to-left mirroring support|No| +||Starts with the scroll box (thumb) right-aligned|No effect|No| +||Not required|No effect|No| +||Displayed right-aligned. Reverses and |No effect|No| +||Displayed right-aligned. Reverses and |No effect|No| +||Items are right-aligned|No effect|No| +||Sets the reading order to RTL; elements stay left-aligned|Mirrors the control|Yes| +||Displayed right-aligned with RTL reading order at run time (not at design time)|No effect|No| +||Displays text from right to left.|No effect|No| +||Not affected; depends on the language of the operating system|Mirrors the control|Yes| +||Not supported|Not supported|No| +||Up and down buttons are left-aligned|No effect|No| +||On right-to-left operating systems, setting the containing form's property to localizes the dialog |No effect|No| +||Not affected; depends on the language of the operating system|No effect|No| +||Child controls may inherit this property|Use within the control for right to left support|Yes| +||Not supported|No effect|No| +||Not affected; depends on the language of the operating system|No effect|No| +||The vertical scroll bar become left-aligned and the horizontal scroll bar starts from the left|No effect|No| +||Not supported|Not supported|No| +||Not affect by this property|Mirrors the control|Yes| +||The radio button is displayed on the right side of the text|No effect|No| +||Control elements that include text are displayed from right to left with RTL reading order|No effect|No| +||Not affected; depends on the language of the operating system|No effect|No| +||Panel layout is reversed; vertical scrollbar appears on the left; horizontal scrollbar starts from the right|Use a to mirror order of child controls|No| +||Not supported|No effect|No| +||Not supported; use instead|No effect; use instead|No| +||Not affected by this property|Mirrors the control|Yes| +||Displays text from right to left with RTL reading order|No effect|No| +||Not required|Not required|No| +||Not affected by this property; use instead|No effect; use instead|Yes| +||Sets the RTL reading order|No effect|No| +||The scroll or track starts from the right; when is vertical, ticks occur from the right|No effect|No| +||Sets the RTL reading order only|Mirrors the control|Yes| +||Vertical scrollbar appears on the left; horizontal scrollbar has thumb on the right|No direct support; use a |No| +||Displayed on the left side instead of right side of scrollable controls|No effect|No| + +## Encoding + Windows Forms support Unicode, so you can include any character set when you create your bi-directional applications. However, not all Windows Forms controls support Unicode on all platforms. + +## GDI+ + You can use GDI+ to draw text with right-to-left reading order. The method, which is used to draw text, supports a `StringFormat` parameter that you can set to the member of the enumeration in order to reverse the point of origin for the text. + +## Common Dialog Boxes + System tools such as the File Open dialog box are under the control of Windows. They inherit language elements from the operating system. If you are using a version of Windows with the correct language settings, these dialog boxes will work correctly with bi-directional languages. + + Similarly, message boxes go through the operating system and support bi-directional text. The captions on message box buttons are based on the current language setting. By default, message boxes do not use right-to-left reading order, but you can specify a parameter to change the reading order when the message boxes are displayed. + +## RightToLeft, Scrollbars, and ScrollableControl + There is currently a limitation in Windows Forms that prevents all classes derived from from acting properly when both is enabled and is set to . For example, let's say that you place a control such as —or a container class derived from (such as or )—on your form. If you set on the container to and then set the property on one or more of the controls inside of the container to , then no scrollbar ever appears. The class derived from acts as if were set to . + + Currently, the only workaround is to nest the inside another . For instance, if you need to work in this situation, you can place it inside of a control and set on the to . + +## Mirroring + *Mirroring* refers to reversing the layout of UI elements so that they flow from right to left. In a mirrored Windows Form, for example, the Minimize, Maximize, and Close buttons appear left-most on the title bar, not right-most. + + Setting a form or control's property to `true` reverses the reading order of elements on a form, but this setting does not reverse the layout to be right-to-left— that is, it does not cause mirroring. For example, setting this property does not move the **Minimize**, **Maximize**, and **Close** buttons in the form's title bar to the left side of the form. Similarly, some controls, such as the control, require mirroring in order to change their display to be appropriate for Arabic or Hebrew. You can mirror these controls by settings the property. + + You can create mirrored versions of the following controls: + +- + +- + +- + +- + +- + +- + +- + + Some controls are sealed. Therefore, you cannot derive a new control from them. These include the and controls. + +## See also + +- [Bidirectional Support for ASP.NET Web Applications](https://docs.microsoft.com/previous-versions/aspnet/6eedwbtt(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/brushes-and-filled-shapes-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/brushes-and-filled-shapes-in-gdi.md new file mode 100644 index 0000000000..2456d91dd2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/brushes-and-filled-shapes-in-gdi.md @@ -0,0 +1,81 @@ +--- +title: "Brushes and Filled Shapes in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "brushes [Windows Forms], GDI+" + - "filled shapes [Windows Forms], GDI+" + - "shapes [Windows Forms], GDI+" + - "GDI+, brushes" + - "GDI+, filled shapes" + - "gradient brushes" + - "brushes [Windows Forms], gradient" +ms.assetid: e863e2a7-0294-4130-99b6-f1ea3201e7cd +--- +# Brushes and Filled Shapes in GDI+ +A closed shape, such as a rectangle or an ellipse, consists of an outline and an interior. The outline is drawn with a pen and the interior is filled with a brush. GDI+ provides several brush classes for filling the interiors of closed shapes: , , , , and . All of these classes inherit from the class. The following illustration shows a rectangle filled with a solid brush and an ellipse filled with a hatch brush. + + ![Filled Shapes](./media/aboutgdip02-art17.gif "Aboutgdip02_art17") + +## Solid Brushes + To fill a closed shape, you need an instance of the class and a . The instance of the class provides methods, such as and , and the stores attributes of the fill, such as color and pattern. The is passed as one of the arguments to the fill method. The following code example shows how to fill an ellipse with a solid red color. + + [!code-csharp[LinesCurvesAndShapes#121](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#121)] + [!code-vb[LinesCurvesAndShapes#121](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#121)] + +> [!NOTE] +> In the preceding example, the brush is of type , which inherits from . + +## Hatch Brushes + When you fill a shape with a hatch brush, you specify a foreground color, a background color, and a hatch style. The foreground color is the color of the hatching. + + [!code-csharp[LinesCurvesAndShapes#122](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#122)] + [!code-vb[LinesCurvesAndShapes#122](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#122)] + + GDI+ provides more than 50 hatch styles; the three styles shown in the following illustration are , , and . + + ![Filled Shapes](./media/aboutgdip02-art18.gif "Aboutgdip02_art18") + +## Texture Brushes + With a texture brush, you can fill a shape with a pattern stored in a bitmap. For example, suppose the following picture is stored in a disk file named `MyTexture.bmp`. + + ![Filled Shape](./media/aboutgdip02-art19.gif "Aboutgdip02_Art19") + + The following code example shows how to fill an ellipse by repeating the picture stored in `MyTexture.bmp`. + + [!code-csharp[LinesCurvesAndShapes#123](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#123)] + [!code-vb[LinesCurvesAndShapes#123](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#123)] + + The following illustration shows the filled ellipse. + + ![Filled Shape](./media/aboutgdip02-art20.gif "AboutGdip02_Art20") + +## Gradient Brushes + GDI+ provides two kinds of gradient brushes: linear and path. You can use a linear gradient brush to fill a shape with color that changes gradually as you move across the shape horizontally, vertically, or diagonally. The following code example shows how to fill an ellipse with a horizontal gradient brush that changes from blue to green as you move from the left edge of the ellipse to the right edge. + + [!code-csharp[LinesCurvesAndShapes#124](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#124)] + [!code-vb[LinesCurvesAndShapes#124](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#124)] + + The following illustration shows the filled ellipse. + + ![Filled Shape](./media/aboutgdip02-art21.gif "AboutGdip02_Art21") + + A path gradient brush can be configured to change color as you move from the center of a shape toward the edge. + + ![Filled Shape](./media/aboutgdip02-art22.gif "AboutGdip02_Art22") + + Path gradient brushes are quite flexible. The gradient brush used to fill the triangle in the following illustration changes gradually from red at the center to each of three different colors at the vertices. + + ![Filled Shape](./media/aboutgdip02-art23.gif "AboutGdip02_Art23") + +## See also + +- +- +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Draw a Filled Rectangle on a Windows Form](how-to-draw-a-filled-rectangle-on-a-windows-form.md) +- [How to: Draw a Filled Ellipse on a Windows Form](how-to-draw-a-filled-ellipse-on-a-windows-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/cardinal-splines-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/cardinal-splines-in-gdi.md new file mode 100644 index 0000000000..708a83a98f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/cardinal-splines-in-gdi.md @@ -0,0 +1,35 @@ +--- +title: "Cardinal Splines in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "splines [Windows Forms], cardinal" + - "GDI+, cardinal splines" + - "cardinal splines" +ms.assetid: 09b3797a-6294-422d-9adf-a5a0a7695c0c +--- +# Cardinal Splines in GDI+ +A cardinal spline is a sequence of individual curves joined to form a larger curve. The spline is specified by an array of points and a tension parameter. A cardinal spline passes smoothly through each point in the array; there are no sharp corners and no abrupt changes in the tightness of the curve. The following illustration shows a set of points and a cardinal spline that passes through each point in the set. + + ![Cardinal Spline](./media/aboutgdip02-art09.gif "Aboutgdip02_art09") + +## Physical and Mathematical Splines + A physical spline is a thin piece of wood or other flexible material. Before the advent of mathematical splines, designers used physical splines to draw curves. A designer would place the spline on a piece of paper and anchor it to a given set of points. The designer could then create a curve by drawing along the spline with a pen or pencil. A given set of points could yield a variety of curves, depending on the properties of the physical spline. For example, a spline with a high resistance to bending would produce a different curve than an extremely flexible spline. + + The formulas for mathematical splines are based on the properties of flexible rods, so the curves produced by mathematical splines are similar to the curves that were once produced by physical splines. Just as physical splines of different tension will produce different curves through a given set of points, mathematical splines with different values for the tension parameter will produce different curves through a given set of points. The following illustration shows four cardinal splines passing through the same set of points. The tension is shown for each spline. A tension of 0 corresponds to infinite physical tension, forcing the curve to take the shortest way (straight lines) between points. A tension of 1 corresponds to no physical tension, allowing the spline to take the path of least total bend. With tension values greater than 1, the curve behaves like a compressed spring, pushed to take a longer path. + + ![Cardinal Splines](./media/aboutgdip02-art10.gif "Aboutgdip02_art10") + + The four splines in the preceding illustration share the same tangent line at the starting point. The tangent is the line drawn from the starting point to the next point along the curve. Likewise, the shared tangent at the ending point is the line drawn from the ending point to the previous point on the curve. + + To draw a cardinal spline, you need an instance of the class, a , and an array of objects The instance of the class provides the method, which draws the spline, and the stores attributes of the spline, such as line width and color. The array of objects stores the points that the curve will pass through. The following code example shows how to draw a cardinal spline that passes through the points in `myPointArray`. The third parameter is the tension. + + [!code-csharp[LinesCurvesAndShapes#31](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#31)] + [!code-vb[LinesCurvesAndShapes#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#31)] + +## See also + +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [Constructing and Drawing Curves](constructing-and-drawing-curves.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/com-interop-by-displaying-a-windows-form-shadow.md b/dotnet-desktop-guide/framework/winforms/advanced/com-interop-by-displaying-a-windows-form-shadow.md new file mode 100644 index 0000000000..527c995b1b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/com-interop-by-displaying-a-windows-form-shadow.md @@ -0,0 +1,38 @@ +--- +title: "How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method" +ms.date: "03/30/2017" +helpviewer_keywords: + - "COM [Windows Forms]" + - "Windows Forms, unmanaged" + - "COM interop [Windows Forms], calling methods" + - "ActiveX controls [Windows Forms], COM interop" + - "Windows Forms, interop" +ms.assetid: 87aac8ad-3c04-43b3-9b0c-d0b00df9ee74 +--- +# How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method +You can resolve Component Object Model (COM) interoperability problems by displaying your Windows Form on a .NET Framework message loop, which is created by using the method. + + To make a form work correctly from a COM client application, you must run it on a Windows Forms message loop. To do this, use one of the following approaches: + +- Use the method to display the Windows Form; + +- Display each Windows Form on a separate thread. For more information, see [How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread](how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md). + +## Procedure + Using the method can be the easiest way to display a form on a .NET Framework message loop because, of all the approaches, it requires the least code to implement. + + The method suspends the unmanaged application's message loop and displays the form as a dialog box. Because the host application's message loop has been suspended, the method creates a new .NET Framework message loop to process the form's messages. + + The disadvantage of using the method is that the form will be opened as a modal dialog box. This behavior blocks any user interface (UI) in the calling application while the Windows Form is open. When the user exits the form, the .NET Framework message loop closes and the earlier application's message loop starts running again. + + You can create a class library in Windows Forms which has a method to show the form, and then build the class library for COM interop. You can use this DLL file from Visual Basic 6.0 or Microsoft Foundation Classes (MFC), and from either of these environments you can call the method to display the form. + +#### To support COM interop by displaying a windows form with the ShowDialog method + +- Replace all calls to the method with calls to the method in your .NET Framework component. + +## See also + +- [Exposing .NET Framework Components to COM](https://docs.microsoft.com/dotnet/framework/interop/exposing-dotnet-components-to-co) +- [How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread](how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md) +- [Windows Forms and Unmanaged Applications](windows-forms-and-unmanaged-applications.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/constructing-and-drawing-curves.md b/dotnet-desktop-guide/framework/winforms/advanced/constructing-and-drawing-curves.md new file mode 100644 index 0000000000..4708a7b37e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/constructing-and-drawing-curves.md @@ -0,0 +1,21 @@ +--- +title: "Constructing and Drawing Curves" +ms.date: "03/30/2017" +helpviewer_keywords: + - "drawing [Windows Forms], curves" + - "examples [Windows Forms], drawing curves" + - "curves [Windows Forms], drawing" +ms.assetid: 76e92623-4130-4644-b867-faca58bdb3a2 +--- +# Constructing and Drawing Curves +GDI+ supports several types of curves: ellipses, arcs, cardinal splines, and Bézier splines. An ellipse is defined by its bounding rectangle; an arc is a portion of an ellipse defined by a starting angle and a sweep angle. A cardinal spline is defined by an array of points and a tension parameter — the curve passes smoothly through each point in the array, and the tension parameter influences the way the curve bends. A Bézier spline is defined by two endpoints and two control points the curve does not pass through the control points, but the control points influence the direction and bend as the curve goes from one endpoint to the other. + +## In This Section + [How to: Draw Cardinal Splines](how-to-draw-cardinal-splines.md) + Describes cardinal splines and how to draw them. + + [How to: Draw a Single Bézier Spline](how-to-draw-a-single-bezier-spline.md) + Describes a Bézier spline and how to draw one. + + [How to: Draw a Sequence of Bézier Splines](how-to-draw-a-sequence-of-bezier-splines.md) + Explains how to draw several Bézier splines in sequence. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/constructing-and-drawing-paths.md b/dotnet-desktop-guide/framework/winforms/advanced/constructing-and-drawing-paths.md new file mode 100644 index 0000000000..b21dacb87c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/constructing-and-drawing-paths.md @@ -0,0 +1,29 @@ +--- +title: "Constructing and Drawing Paths" +ms.date: "03/30/2017" +helpviewer_keywords: + - "paths [Windows Forms], drawing" + - "drawing paths [Windows Forms]" + - "graphics paths [Windows Forms], creating" + - "graphics paths [Windows Forms], drawing" + - "examples [Windows Forms], drawing paths" +ms.assetid: f16ec921-56cf-46d1-9741-d7316ad06b23 +--- +# Constructing and Drawing Paths +A path is a sequence of graphics primitives (lines, rectangles, curves, text, and the like) that can be manipulated and drawn as a single unit. A path can be divided into *figures* that are either open or closed. A figure can contain several primitives. + + You can draw a path by calling the method of the class, and you can fill a path by calling the method of the class. + +## In This Section + [How to: Create Figures from Lines, Curves, and Shapes](how-to-create-figures-from-lines-curves-and-shapes.md) + Shows how to use a to create figures. + + [How to: Fill Open Figures](how-to-fill-open-figures.md) + Explains how to fill a . + + [How to: Flatten a Curved Path into a Line](how-to-flatten-a-curved-path-into-a-line.md) + Shows how to flatten a . + +## Reference + + Describes this class and contains links to all of its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/control-help-using-tooltips.md b/dotnet-desktop-guide/framework/winforms/advanced/control-help-using-tooltips.md new file mode 100644 index 0000000000..504145fc0f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/control-help-using-tooltips.md @@ -0,0 +1,19 @@ +--- +title: "Control Help Using ToolTips" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Help [Windows Forms], tooltips for controls" + - "controls [Windows Forms], tooltips" + - "tooltips [Windows Forms], for controls" + - "Help [Windows Forms], adding to dialog boxes" +ms.assetid: 03263f94-e539-440b-a67c-8b9110c96dcd +--- +# Control Help Using ToolTips +You can use the component to display a brief, specialized Help message for individual controls on Windows Forms. The component provides a property that specifies the text displayed for each control on the form. For more information about working with the component in this way, see [How to: Set ToolTips for Controls on a Windows Form at Design Time](../controls/how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md). Additionally, you can configure the component so that there is a delay before it is shown. For more information, see [How to: Change the Delay of the Windows Forms ToolTip Component](../controls/how-to-change-the-delay-of-the-windows-forms-tooltip-component.md). + +## See also + +- [How to: Display Pop-up Help](how-to-display-pop-up-help.md) +- [ToolTip Component](../controls/tooltip-component-windows-forms.md) +- [Integrating User Help in Windows Forms](integrating-user-help-in-windows-forms.md) +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/coordinate-systems-and-transformations.md b/dotnet-desktop-guide/framework/winforms/advanced/coordinate-systems-and-transformations.md new file mode 100644 index 0000000000..70e12ff9e0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/coordinate-systems-and-transformations.md @@ -0,0 +1,32 @@ +--- +title: "Coordinate Systems and Transformations" +ms.date: "03/30/2017" +helpviewer_keywords: + - "transformations" + - "graphics [Windows Forms], transformations" + - "matrix transformations" +ms.assetid: 9fef7451-bddf-4c68-9350-400d1f1f25a3 +--- +# Coordinate Systems and Transformations +GDI+ provides a world transformation and a page transformation so that you can transform (rotate, scale, translate, and so on) the items you draw. The two transformations also allow you to work in a variety of coordinate systems. + +## In This Section + [Types of Coordinate Systems](types-of-coordinate-systems.md) + Introduces coordinates systems and transformations. + + [Matrix Representation of Transformations](matrix-representation-of-transformations.md) + Discusses using matrices for coordinate transformations. + + [Global and Local Transformations](global-and-local-transformations.md) + Discusses global and local transformations. + +## Reference + + Encapsulates a 3-by-3 affine matrix that represents a geometric transform. + +## Related Sections + [Using Transformations in Managed GDI+](using-transformations-in-managed-gdi.md) + Provides a list of topics that provide more information about how to use matrix transformations. + + [About GDI+ Managed Code](about-gdi-managed-code.md) + Contains a list of topics describing the graphics constructs you can use in the .NET Framework. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/cropping-and-scaling-images-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/cropping-and-scaling-images-in-gdi.md new file mode 100644 index 0000000000..a043e361d6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/cropping-and-scaling-images-in-gdi.md @@ -0,0 +1,46 @@ +--- +title: "Cropping and Scaling Images in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "GDI+, scaling images" + - "GDI+, cropping images" + - "images [Windows Forms], cropping" + - "compressing data [Windows Forms], images" + - "images [Windows Forms], expansion" + - "images [Windows Forms], scaling" + - "rectangles [Windows Forms], source" + - "rectangles [Windows Forms], destination" + - "images [Windows Forms], compression" +ms.assetid: ad5daf26-005f-45bc-a2af-e0e97777a21a +--- +# Cropping and Scaling Images in GDI+ +You can use the method of the class to draw and position vector images and raster images. is an overloaded method, so there are several ways you can supply it with arguments. + +## DrawImage Variations + One variation of the method receives a and a . The rectangle specifies the destination for the drawing operation; that is, it specifies the rectangle in which to draw the image. If the size of the destination rectangle is different from the size of the original image, the image is scaled to fit the destination rectangle. The following code example shows how to draw the same image three times: once with no scaling, once with an expansion, and once with a compression: + + [!code-csharp[System.Drawing.ImagesBitmapsMetafiles#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs#31)] + [!code-vb[System.Drawing.ImagesBitmapsMetafiles#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb#31)] + + The following illustration shows the three pictures. + + ![Scaling](./media/aboutgdip03-art06.gif "AboutGdip03_Art06") + + Some variations of the method have a source-rectangle parameter as well as a destination-rectangle parameter. The source-rectangle parameter specifies the portion of the original image to draw. The destination rectangle specifies the rectangle in which to draw that portion of the image. If the size of the destination rectangle is different from the size of the source rectangle, the picture is scaled to fit the destination rectangle. + + The following code example shows how to construct a from the file Runner.jpg. The entire image is drawn with no scaling at (0, 0). Then a small portion of the image is drawn twice: once with a compression and once with an expansion. + + [!code-csharp[System.Drawing.ImagesBitmapsMetafiles#32](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs#32)] + [!code-vb[System.Drawing.ImagesBitmapsMetafiles#32](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb#32)] + + The following illustration shows the unscaled image, and the compressed and expanded image portions. + + ![Cropping and Scaling](./media/aboutgdip03-art07.gif "AboutGdip03_Art07") + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/display-of-asian-characters-with-the-imemode-property.md b/dotnet-desktop-guide/framework/winforms/advanced/display-of-asian-characters-with-the-imemode-property.md new file mode 100644 index 0000000000..a24eaf9404 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/display-of-asian-characters-with-the-imemode-property.md @@ -0,0 +1,24 @@ +--- +title: "Display of Asian Characters with the ImeMode Property" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Asian languages [Windows Forms], displaying with ImeMode" + - "Chinese characters [Windows Forms], displaying with ImeMode" + - "IME mode" + - "Japanese characters [Windows Forms], displaying with ImeMode" + - "international applications [Windows Forms], character display" + - "international characters" + - "Korean characters" + - "Asian languages" + - "Input Method Editor (IME), mode" + - "localization [Windows Forms], character sets" + - "globalization [Windows Forms], character sets" +ms.assetid: c60ae399-0dab-4f07-9dea-6dbfb15ec0ae +--- +# Display of Asian Characters with the ImeMode Property +The property is used by forms and controls to force a specific mode for an input method editor (IME). The IME is an essential component for writing Chinese, Japanese, and Korean scripts, since these writing systems have more characters than can be encoded for a regular keyboard. For example, you may want to allow only ASCII characters in a particular text box. In such a case you can set the property to and users will only be able to enter ASCII characters for that particular text box. The default value of the property is , so if you set the property for a form, all controls on the form will inherit that setting. For more information, see +) and . + +## See also + +- [Globalizing Windows Forms applications](globalizing-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/double-buffered-graphics.md b/dotnet-desktop-guide/framework/winforms/advanced/double-buffered-graphics.md new file mode 100644 index 0000000000..ba3275b53d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/double-buffered-graphics.md @@ -0,0 +1,37 @@ +--- +title: "Double Buffered Graphics" +ms.date: "03/30/2017" +helpviewer_keywords: + - "double buffering" + - "graphics [Windows Forms], double-buffered" + - "flicker [Windows Forms], reducing with double buffering" + - "examples [Windows Forms], double-buffered graphics" +ms.assetid: 4f6fef99-0972-436e-9d73-0167e4033f71 +--- +# Double Buffered Graphics +Flicker is a common problem when programming graphics. Graphics operations that require multiple complex painting operations can cause the rendered images to appear to flicker or have an otherwise unacceptable appearance. To address these problems, the .NET Framework provides access to double buffering. + + Double buffering uses a memory buffer to address the flicker problems associated with multiple paint operations. When double buffering is enabled, all paint operations are first rendered to a memory buffer instead of the drawing surface on the screen. After all paint operations are completed, the memory buffer is copied directly to the drawing surface associated with it. Because only one graphics operation is performed on the screen, the image flickering associated with complex painting operations is eliminated. + +## Default Double Buffering + The easiest way to use double buffering in your applications is to use the default double buffering for forms and controls that is provided by the .NET Framework. You can enable default double buffering for your Windows Forms and authored Windows controls by setting the property to `true` or by using the method. For more information, see [How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls](how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md). + +## Manually Managing Buffered Graphics + For more advanced double buffering scenarios, such as animation or advanced memory management, you can use the .NET Framework classes to implement your own double-buffering logic. The class responsible for allocating and managing individual graphics buffers is the class. Every application domain has its own default instance that manages all of the default double buffering for that application. In most cases there will be only one application domain per application, so there is generally one default per application. Default instances are managed by the class. You can retrieve a reference to the default instance by calling the . You can also create a dedicated instance, which can improve performance for graphically intensive applications. For information on how to create a instance, see [How to: Manually Manage Buffered Graphics](how-to-manually-manage-buffered-graphics.md). + +## Manually Displaying Buffered Graphics + You can use an instance of the class to create graphics buffers by calling the , which returns an instance of the class. A object manages a memory buffer that is associated with a rendering surface, such as a form or control. + + After it is instantiated, the class manages rendering to an in-memory graphics buffer. You can render graphics to the memory buffer through the , which exposes a object that directly represents the memory buffer. You can paint to this object just as you would to a object that represents a drawing surface. After all the graphics have been drawn to the buffer, you can use the to copy the contents of the buffer to the drawing surface on the screen. + + For more information on using the class, see [Manually Rendering Buffered Graphics](how-to-manually-render-buffered-graphics.md). For more information on rendering graphics, see [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) + +## See also + +- +- +- +- [How to: Manually Render Buffered Graphics](how-to-manually-render-buffered-graphics.md) +- [How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls](how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md) +- [How to: Manually Manage Buffered Graphics](how-to-manually-manage-buffered-graphics.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/drag-and-drop-operations-and-clipboard-support.md b/dotnet-desktop-guide/framework/winforms/advanced/drag-and-drop-operations-and-clipboard-support.md new file mode 100644 index 0000000000..f88522b348 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/drag-and-drop-operations-and-clipboard-support.md @@ -0,0 +1,39 @@ +--- +title: "Drag-and-Drop Operations and Clipboard Support" +ms.date: "03/30/2017" +helpviewer_keywords: + - "drag and drop [Windows Forms]" + - "drag and drop [Windows Forms], Windows Forms" + - "Clipboard [Windows Forms], Windows Forms" +ms.assetid: 7cce79b6-5835-46fd-b690-73f12ad368b2 +--- +# Drag-and-Drop Operations and Clipboard Support +You can enable user drag-and-drop operations within a Windows-based application by handling a series of events, most notably the , , and events. + + You can also implement user cut/copy/paste support and user data transfer to the Clipboard within your Windows-based applications by using simple method calls. + +## In This Section + [Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms](walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md) + Explains how to start a drag-and-drop operation. + + [How to: Perform Drag-and-Drop Operations Between Applications](how-to-perform-drag-and-drop-operations-between-applications.md) + Illustrates how to accomplish drag-and-drop operations across applications. + + [How to: Add Data to the Clipboard](how-to-add-data-to-the-clipboard.md) + Describes a way to programmatically insert information on the Clipboard. + + [How to: Retrieve Data from the Clipboard](how-to-retrieve-data-from-the-clipboard.md) + Describes how to access the data stored on the Clipboard. + +## Related Sections + [Drag-and-Drop Functionality in Windows Forms](../drag-and-drop-functionality-in-windows-forms.md) + Describes the methods, events, and classes used to implement drag-and-drop behavior. + + + Describes the intricacies of the event that asks permission to continue the drag operation. + + + Describes the intricacies of the method that is central to beginning a drag operation. + + + Also see [How to: Send Data to the Active MDI Child](how-to-send-data-to-the-active-mdi-child.md). diff --git a/dotnet-desktop-guide/framework/winforms/advanced/drawing-positioning-and-cloning-images-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/drawing-positioning-and-cloning-images-in-gdi.md new file mode 100644 index 0000000000..8a4c3a67cc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/drawing-positioning-and-cloning-images-in-gdi.md @@ -0,0 +1,52 @@ +--- +title: "Drawing, Positioning, and Cloning Images in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "raster images [Windows Forms]" + - "images [Windows Forms], positioning" + - "drawing [Windows Forms], images" + - "drawing [Windows Forms], raster images" + - "images [Windows Forms], cloning" + - "images [Windows Forms], drawing" + - "GDI+, drawing images" + - "GDI+, cloning images" + - "GDI+, positioning images" +ms.assetid: 09f0c07a-19c0-43b4-90a2-862a10545ce8 +--- +# Drawing, Positioning, and Cloning Images in GDI+ +You can use the class to load and display raster images, and you can use the class to load and display vector images. The and classes inherit from the class. To display a vector image, you need an instance of the class and a . To display a raster image, you need an instance of the class and a . The instance of the class provides the method, which receives the or as an argument. + +## File Types and Cloning + The following code example shows how to construct a from the file Climber.jpg and displays the bitmap. The destination point for the upper-left corner of the image, (10, 10), is specified in the second and third parameters. + + [!code-csharp[System.Drawing.ImagesBitmapsMetafiles#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs#11)] + [!code-vb[System.Drawing.ImagesBitmapsMetafiles#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb#11)] + + The following illustration shows the image. + + ![Image Sample](./media/aboutgdip03-art04.gif "AboutGdip03_Art04") + + You can construct objects from a variety of graphics file formats: BMP, GIF, JPEG, EXIF, PNG, TIFF, and ICON. + + The following code example shows how to construct objects from a variety of file types and then displays the bitmaps. + + [!code-csharp[System.Drawing.ImagesBitmapsMetafiles#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs#12)] + [!code-vb[System.Drawing.ImagesBitmapsMetafiles#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb#12)] + + The class provides a method that you can use to make a copy of an existing . The method has a source rectangle parameter that you can use to specify the portion of the original bitmap that you want to copy. The following code example shows how to create a by cloning the top half of an existing . Then both images are drawn. + + [!code-csharp[System.Drawing.ImagesBitmapsMetafiles#13](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs#13)] + [!code-vb[System.Drawing.ImagesBitmapsMetafiles#13](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb#13)] + + The following illustration shows the two images. + + ![Cropping](./media/aboutgdip03-art05.gif "AboutGdip03_Art05") + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/effects-of-modifying-base-form-appearance.md b/dotnet-desktop-guide/framework/winforms/advanced/effects-of-modifying-base-form-appearance.md new file mode 100644 index 0000000000..227655bb3d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/effects-of-modifying-base-form-appearance.md @@ -0,0 +1,24 @@ +--- +title: "Effects of Modifying a Base Form's Appearance" +ms.date: "03/30/2017" +helpviewer_keywords: + - "parent forms [Windows Forms]" + - "inherited forms [Windows Forms], modifications to base form" + - "Windows Forms, base form appearance" + - "base forms" + - "inheritance [Windows Forms], forms" +ms.assetid: 1c3f2b29-a05c-4c6f-aa1a-4e66b94f343a +--- +# Effects of modifying a base form's appearance + +During application development, you may often need to change the appearance of the base form from which other forms in the project (or in other projects) are inheriting. + +At design time, changes to the base form's appearance (be it the setting of properties or the addition and subtraction of controls) are reflected on inherited forms when the project containing the base form is built. It is not sufficient for you to simply save the changes to the base form. To build a project, choose **Build** from the **Build** menu. + +Modifications made to the base form at run time have no affect on inherited forms that are already instantiated. + +## See also + +- [base](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/base) +- [How to: Inherit Windows Forms](how-to-inherit-windows-forms.md) +- [Windows Forms Visual Inheritance](windows-forms-visual-inheritance.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/ellipses-and-arcs-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/ellipses-and-arcs-in-gdi.md new file mode 100644 index 0000000000..28a8b8d307 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/ellipses-and-arcs-in-gdi.md @@ -0,0 +1,51 @@ +--- +title: "Ellipses and Arcs in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "arcs" + - "GDI+, arcs" + - "drawing [Windows Forms], ellipses" + - "GDI+, ellipses" + - "ellipses" + - "drawing [Windows Forms], arcs" +ms.assetid: 34f35133-a835-4ca4-81f6-0dfedee8b683 +--- +# Ellipses and Arcs in GDI+ +You can easily draw ellipses and arcs using the and methods of the class. + +## Drawing an Ellipse + To draw an ellipse, you need a object and a object. The object provides the method, and the object stores attributes, such as width and color, of the line used to render the ellipse. The object is passed as one of the arguments to the method. The remaining arguments passed to the method specify the bounding rectangle for the ellipse. The following illustration shows an ellipse along with its bounding rectangle. + + ![Ellipses and arcs](./media/aboutgdip02-art05.gif "Aboutgdip02_art05") + + The following example draws an ellipse; the bounding rectangle has a width of 80, a height of 40, and an upper-left corner of (100, 50): + + [!code-csharp[LinesCurvesAndShapes#51](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#51)] + [!code-vb[LinesCurvesAndShapes#51](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#51)] + + is an overloaded method of the class, so there are several ways you can supply it with arguments. For example, you can construct a and pass the to the method as an argument: + + [!code-csharp[LinesCurvesAndShapes#52](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#52)] + [!code-vb[LinesCurvesAndShapes#52](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#52)] + +## Drawing an Arc + An arc is a portion of an ellipse. To draw an arc, you call the method of the class. The parameters of the method are the same as the parameters of the method, except that requires a starting angle and sweep angle. The following example draws an arc with a starting angle of 30 degrees and a sweep angle of 180 degrees: + + [!code-csharp[LinesCurvesAndShapes#53](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#53)] + [!code-vb[LinesCurvesAndShapes#53](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#53)] + + The following illustration shows the arc, the ellipse, and the bounding rectangle. + + ![Ellipses and arcs](./media/aboutgdip02-art06.gif "Aboutgdip02_art06") + +## See also + +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) +- [How to: Create a Pen](how-to-create-a-pen.md) +- [How to: Draw an Outlined Shape](how-to-draw-an-outlined-shape.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/getting-started-with-graphics-programming.md b/dotnet-desktop-guide/framework/winforms/advanced/getting-started-with-graphics-programming.md new file mode 100644 index 0000000000..16974c02de --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/getting-started-with-graphics-programming.md @@ -0,0 +1,60 @@ +--- +title: "Getting Started with Graphics Programming" +description: Get started using GDI+ in a Windows Forms application. Learn how to complete several GDI+ tasks, such as drawing and filling shapes and text. +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [Windows Forms], getting started" + - "getting started [Windows Forms], graphics programming" + - "examples [Windows Forms], graphics" + - "drawing" +ms.assetid: eb0f6d6f-9e52-4167-9592-ff4b82fb5869 +--- +# Getting Started with Graphics Programming +This section shows how to get started using GDI+ in a Windows Forms application. The following topics show how to complete several GDI+ tasks such as drawing and filling shapes and text. + +## In This Section + [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) + Shows how to create a object for drawing. + + [How to: Create a Pen](how-to-create-a-pen.md) + Shows how to create a pen. + + [How to: Set the Color of a Pen](how-to-set-the-color-of-a-pen.md) + Demonstrates how to set the color of a pen. + + [How to: Create a Solid Brush](how-to-create-a-solid-brush.md) + Describes how to create a solid brush. + + [How to: Draw a Line on a Windows Form](how-to-draw-a-line-on-a-windows-form.md) + Demonstrates how to draw a line. + + [How to: Draw an Outlined Shape](how-to-draw-an-outlined-shape.md) + Describes how to draw a shape. + + [How to: Draw a Filled Rectangle on a Windows Form](how-to-draw-a-filled-rectangle-on-a-windows-form.md) + Explains how to draw a rectangle. + + [How to: Draw a Filled Ellipse on a Windows Form](how-to-draw-a-filled-ellipse-on-a-windows-form.md) + Shows how to draw a filled ellipse. + + [How to: Draw Text on a Windows Form](how-to-draw-text-on-a-windows-form.md) + Describes how to draw text. + + [How to: Draw Vertical Text on a Windows Form](how-to-draw-vertical-text-on-a-windows-form.md) + Shows how to draw vertical text. + + [How to: Render Images with GDI+](how-to-render-images-with-gdi.md) + Demonstrates how to draw images. + + [How to: Create a Shaped Windows Form](how-to-create-a-shaped-windows-form.md) + Explains how to change the shape of a form. + + [How to: Copy Pixels for Reducing Flicker in Windows Forms](how-to-copy-pixels-for-reducing-flicker-in-windows-forms.md) + Explains how to copy pixels from one area to another. + +## Reference + + Describes this namespace and has links to all its members. + + + Describes this namespace and has links to all of its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/global-and-local-transformations.md b/dotnet-desktop-guide/framework/winforms/advanced/global-and-local-transformations.md new file mode 100644 index 0000000000..43961b733d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/global-and-local-transformations.md @@ -0,0 +1,60 @@ +--- +title: "Global and Local Transformations" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "matrices [Windows Forms], using transformations" + - "transformations [Windows Forms], global" + - "transformations [Windows Forms], local" +ms.assetid: b601d66d-d572-4f11-9d2e-92f0dc8893f3 +--- +# Global and Local Transformations +A global transformation is a transformation that applies to every item drawn by a given object. In contrast, a local transformation is a transformation that applies to a specific item to be drawn. + +## Global Transformations + To create a global transformation, construct a object, and then manipulate its property. The property is a object, so it can hold any sequence of affine transformations. The transformation stored in the property is called the world transformation. The class provides several methods for building up a composite world transformation: , , , and . The following example draws an ellipse twice: once before creating a world transformation and once after. The transformation first scales by a factor of 0.5 in the y direction, then translates 50 units in the x direction, and then rotates 30 degrees. + + [!code-csharp[System.Drawing.CoordinateSystems#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#21)] + [!code-vb[System.Drawing.CoordinateSystems#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#21)] + + The following illustration shows the matrices involved in the transformation. + + ![Transformations](./media/aboutgdip05-art14.gif "AboutGdip05_art14") + +> [!NOTE] +> In the preceding example, the ellipse is rotated about the origin of the coordinate system, which is at the upper-left corner of the client area. This produces a different result than rotating the ellipse about its own center. + +## Local Transformations + A local transformation applies to a specific item to be drawn. For example, a object has a method that allows you to transform the data points of that path. The following example draws a rectangle with no transformation and a path with a rotation transformation. (Assume that there is no world transformation.) + + [!code-csharp[System.Drawing.CoordinateSystems#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#22)] + [!code-vb[System.Drawing.CoordinateSystems#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#22)] + + You can combine the world transformation with local transformations to achieve a variety of results. For example, you can use the world transformation to revise the coordinate system and use local transformations to rotate and scale objects drawn on the new coordinate system. + + Suppose you want a coordinate system that has its origin 200 pixels from the left edge of the client area and 150 pixels from the top of the client area. Furthermore, assume that you want the unit of measure to be the pixel, with the x-axis pointing to the right and the y-axis pointing up. The default coordinate system has the y-axis pointing down, so you need to perform a reflection across the horizontal axis. The following illustration shows the matrix of such a reflection. + + ![Transformations](./media/aboutgdip05-art15.gif "AboutGdip05_art15") + + Next, assume you need to perform a translation 200 units to the right and 150 units down. + + The following example establishes the coordinate system just described by setting the world transformation of a object. + + [!code-csharp[System.Drawing.CoordinateSystems#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#23)] + [!code-vb[System.Drawing.CoordinateSystems#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#23)] + + The following code (placed at the end of the preceding example) creates a path that consists of a single rectangle with its lower-left corner at the origin of the new coordinate system. The rectangle is filled once with no local transformation and once with a local transformation. The local transformation consists of a horizontal scaling by a factor of 2 followed by a 30-degree rotation. + + [!code-csharp[System.Drawing.CoordinateSystems#24](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#24)] + [!code-vb[System.Drawing.CoordinateSystems#24](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#24)] + + The following illustration shows the new coordinate system and the two rectangles. + + ![Transformations](./media/aboutgdip05-art16.gif "AboutGdip05_art16") + +## See also + +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) +- [Using Transformations in Managed GDI+](using-transformations-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/globalizing-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/globalizing-windows-forms.md new file mode 100644 index 0000000000..95edbcb6a1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/globalizing-windows-forms.md @@ -0,0 +1,46 @@ +--- +title: Globalize apps +description: This topic presents a list of topics related to globalizing Windows Forms applications. +ms.date: "06/08/2018" +helpviewer_keywords: + - "Windows Forms, globalization" + - "localization [Windows Forms]" + - "globalization [Windows Forms]" + - "world-ready applications" + - "global applications [Windows Forms], creating Windows Forms" +ms.assetid: 72f6cd92-83be-45ec-aa37-9cb8e3ebc3c5 +--- +# Globalizing Windows Forms applications + +*Globalization* is the process of designing and developing a software product that functions for multiple cultures. + +## In this section + +[International Fonts in Windows Forms and Controls](international-fonts-in-windows-forms-and-controls.md) +Explains when and how to select fonts for display of international characters on Windows Forms. + +[Bi-Directional Support for Windows Forms Applications](bi-directional-support-for-windows-forms-applications.md) +Explains how to create Windows-based applications that support bi-directional (right-to-left) languages. + +[Display of Asian Characters with the ImeMode Property](display-of-asian-characters-with-the-imemode-property.md) +Introduces the `ImeMode` property, which is used to control the type of input a Windows Form or control accepts. + +## Related sections + +- [Globalizing and localizing .NET applications](https://docs.microsoft.com/dotnet/standard/globalization-localization/index) + +- [Walkthrough: Downloading Satellite Assemblies on Demand with the ClickOnce Deployment API Using the Designer](/visualstudio/deployment/walkthrough-downloading-satellite-assemblies-on-demand-with-the-clickonce-deployment-api-using-the-designer) + +- [Localizing ClickOnce Applications](/visualstudio/deployment/localizing-clickonce-applications) + +- [Walkthrough: Downloading Satellite Assemblies on Demand with the ClickOnce Deployment API](/visualstudio/deployment/walkthrough-downloading-satellite-assemblies-on-demand-with-the-clickonce-deployment-api) + +- [How to: Set the Culture and UI Culture for Windows Forms Globalization](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/b28bx3bh(v=vs.100)) + +- [How to: Create Mirrored Windows Forms and Controls](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/xwbz5ws0(v=vs.100)) + +- [How to: Support Localization on Windows Forms Using AutoSize and the TableLayoutPanel Control](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/1zkt8b33(v=vs.100)) + +- [Walkthrough: Localizing Windows Forms](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/y99d1cd3(v=vs.100)) + +- [Walkthrough: Creating a Layout That Adjusts Proportion for Localization](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/7k9fa71y(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/graphics-and-drawing-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/graphics-and-drawing-in-windows-forms.md new file mode 100644 index 0000000000..e77a1217f9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/graphics-and-drawing-in-windows-forms.md @@ -0,0 +1,47 @@ +--- +title: "Graphics and Drawing" +description: Learn about the Graphics, Pen, Brush, and Color objects, and how to perform such tasks as drawing shapes, drawing text, or displaying images in Windows Forms. +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [Windows Forms]" + - "graphics [Windows Forms], using in Windows Forms" + - "GDI+, using in managed code" + - "drawing [Windows Forms]" +ms.assetid: 362532c5-1a06-4257-bdc8-723461009ede +--- +# Graphics and Drawing in Windows Forms +The common language runtime uses an advanced implementation of the Windows Graphics Device Interface (GDI) called GDI+. With GDI+ you can create graphics, draw text, and manipulate graphical images as objects. GDI+ is designed to offer performance and ease of use. You can use GDI+ to render graphical images on Windows Forms and controls. Although you cannot use GDI+ directly on Web Forms, you can display graphical images through the Image Web Server control. + + In this section, you will find topics that introduce the fundamentals of GDI+ programming. Although not intended to be a comprehensive reference, this section includes information about the , , , and objects, and explains how to perform such tasks as drawing shapes, drawing text, or displaying images. For more information, see [GDI+ Reference](/windows/desktop/gdiplus/-gdiplus-class-gdi-reference). + + If you'd like to jump in and get started right away, see [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md). It has topics on how to use code to draw lines, shapes, text, and more on Windows forms. + +## In This Section + [Graphics Overview](graphics-overview-windows-forms.md) + Provides an introduction to the graphics-related managed classes. + + [About GDI+ Managed Code](about-gdi-managed-code.md) + Provides information about the managed GDI+ classes. + + [Using Managed Graphics Classes](using-managed-graphics-classes.md) + Demonstrates how to complete a variety of tasks using the GDI+ managed classes. + +## Reference + + Provides access to GDI+ basic graphics functionality. + + + Provides advanced two-dimensional and vector graphics functionality. + + + Provides advanced GDI+ imaging functionality. + + + Provides advanced GDI+ typography functionality. The classes in this namespace can be used to create and use collections of fonts. + + + Provides printing functionality. + +## Related Sections + [Custom Control Painting and Rendering](../controls/custom-control-painting-and-rendering.md) + Details how to provide code for painting controls. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/graphics-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/graphics-overview-windows-forms.md new file mode 100644 index 0000000000..88cafc64e9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/graphics-overview-windows-forms.md @@ -0,0 +1,42 @@ +--- +title: "Graphics Overview" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, graphics" + - "Windows Forms, GDI+" + - "graphics [Windows Forms], Windows Forms" + - "GDI+, Windows Forms" + - "graphics" +ms.assetid: 94084509-2c6f-477d-923b-d25d37a36b1c +--- +# Graphics Overview (Windows Forms) +GDI+ is a Graphics Device Interface that enables programmers to write device-independent applications. The services of GDI+ are exposed through a set of managed classes. + +## In This Section + [Overview of Graphics](overview-of-graphics.md) + Provides a general introduction to GDI+. + + [Three Categories of Graphics Services](three-categories-of-graphics-services.md) + Describes the three categories that make up programming with GDI+. + + [Structure of the Graphics Interface](structure-of-the-graphics-interface.md) + Describes the managed class interface of GDI+. + +## Reference + + Provides access to GDI+ basic graphics functionality. + + + Provides advanced two-dimensional and vector graphics functionality. + + + Provides advanced GDI+ imaging functionality. + + + Provides advanced GDI+ typography functionality. + + + Provides print-related services. + + + Provides GDI text drawing and measuring functionality. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/graphics-paths-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/graphics-paths-in-gdi.md new file mode 100644 index 0000000000..a34e45c7b7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/graphics-paths-in-gdi.md @@ -0,0 +1,69 @@ +--- +title: "Graphics Paths in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "graphics [Windows Forms], paths" + - "GDI+, drawing paths" + - "paths [Windows Forms], drawing" + - "drawing [Windows Forms], paths" +ms.assetid: a5500dec-666c-41fd-9da3-2169dd89c5eb +--- +# Graphics Paths in GDI+ +Paths are formed by combining lines, rectangles, and simple curves. Recall from the [Vector Graphics Overview](vector-graphics-overview.md) that the following basic building blocks have proven to be the most useful for drawing pictures: + +- Lines + +- Rectangles + +- Ellipses + +- Arcs + +- Polygons + +- Cardinal splines + +- Bézier splines + + In GDI+, the object allows you to collect a sequence of these building blocks into a single unit. The entire sequence of lines, rectangles, polygons, and curves can then be drawn with one call to the method of the class. The following illustration shows a path created by combining a line, an arc, a Bézier spline, and a cardinal spline. + + ![Path](./media/aboutgdip02-art14.gif "Aboutgdip02_art14") + +## Using a Path + The class provides the following methods for creating a sequence of items to be drawn: , , , , , (for cardinal splines), and . Each of these methods is overloaded; that is, each method supports several different parameter lists. For example, one variation of the method receives four integers, and another variation of the method receives two objects. + + The methods for adding lines, rectangles, and Bézier splines to a path have plural companion methods that add several items to the path in a single call: , , and . Also, the and methods have companion methods, and , that add a closed curve or pie to the path. + + To draw a path, you need a object, a object, and a object. The object provides the method, and the object stores attributes, such as width and color, of the line used to render the path. The object stores the sequence of lines and curves that make up the path. The object and the object are passed as arguments to the method. The following example draws a path that consists of a line, an ellipse, and a Bézier spline: + + [!code-csharp[LinesCurvesAndShapes#101](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#101)] + [!code-vb[LinesCurvesAndShapes#101](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#101)] + + The following illustration shows the path. + + ![Path](./media/aboutgdip02-art15.gif "Aboutgdip02_art15") + + In addition to adding lines, rectangles, and curves to a path, you can add paths to a path. This allows you to combine existing paths to form large, complex paths. + + [!code-csharp[LinesCurvesAndShapes#102](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#102)] + [!code-vb[LinesCurvesAndShapes#102](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#102)] + + There are two other items you can add to a path: strings and pies. A pie is a portion of the interior of an ellipse. The following example creates a path from an arc, a cardinal spline, a string, and a pie: + + [!code-csharp[LinesCurvesAndShapes#103](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#103)] + [!code-vb[LinesCurvesAndShapes#103](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#103)] + + The following illustration shows the path. Note that a path does not have to be connected; the arc, cardinal spline, string, and pie are separated. + + ![Paths](./media/aboutgdip02-art16.gif "Aboutgdip02_Art16") + +## See also + +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) +- [Constructing and Drawing Paths](constructing-and-drawing-paths.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/help-systems-in-windows-forms-applications.md b/dotnet-desktop-guide/framework/winforms/advanced/help-systems-in-windows-forms-applications.md new file mode 100644 index 0000000000..5dd648fd56 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/help-systems-in-windows-forms-applications.md @@ -0,0 +1,26 @@ +--- +title: Help Systems +ms.date: "03/30/2017" +helpviewer_keywords: + - "Help [Windows Forms], adding to Windows applications" + - "Windows applications [Windows Forms], providing Help systems" + - "What's This? Help" + - "Help [Windows Forms], Windows Forms" + - "HelpProvider component [Windows Forms], providing Help in Windows applications" +ms.assetid: 2a96a278-432c-41fc-9e3c-5bfedf5e1267 +--- +# Help Systems in Windows Forms Applications +One of the most important courtesies you, as a developer of applications, can furnish your users with is a competent Help system. This is where they will turn when they become confused or disoriented. Providing a Help system in a Windows-based application is easily done by using the [HelpProvider Component](../controls/helpprovider-component-windows-forms.md). + +## Different Types of Help + The Windows Forms component is used to associate an HTML Help 1.x Help file (either a .chm file, produced with the HTML Help Workshop, or an .htm file) with your Windows-based application. The component can be used to provide context-sensitive Help for controls on Windows Forms or specific controls. Additionally, the component can open a Help file to specific areas, such as the main page of a table of contents, an index, or a search function. For general information about the component, see [HelpProvider Component Overview](../controls/helpprovider-component-overview-windows-forms.md). For information on how to use the component to show pop-up Help on Windows Forms, see [How to: Display Pop-up Help](how-to-display-pop-up-help.md). For information on using the component to show control-specific Help, see [Control Help Using ToolTips](control-help-using-tooltips.md). + + You can generate HTML Help 1.x files with the HTML Help Workshop. For more information on HTML Help, see the "HTML Help Workshop" or the other "HTML Help" topics in MSDN. + +## See also + +- [Integrating User Help in Windows Forms](integrating-user-help-in-windows-forms.md) +- [HelpProvider Component](../controls/helpprovider-component-windows-forms.md) +- [ToolTip Component](../controls/tooltip-component-windows-forms.md) +- [Windows Forms Overview](../windows-forms-overview.md) +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-add-data-to-the-clipboard.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-add-data-to-the-clipboard.md new file mode 100644 index 0000000000..e83eb26c20 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-add-data-to-the-clipboard.md @@ -0,0 +1,61 @@ +--- +title: "How to: Add Data to the Clipboard" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Clipboard [Windows Forms], copying data to" + - "data [Windows Forms], copying to Clipboard" +ms.assetid: 25152454-0e78-40a9-8a9e-a2a5a274e517 +--- +# How to: Add Data to the Clipboard + +The class provides methods that you can use to interact with the Windows operating system Clipboard feature. Many applications use the Clipboard as a temporary repository for data. For example, word processors use the Clipboard during cut-and-paste operations. The Clipboard is also useful for transferring data from one application to another. + +When you add data to the Clipboard, you can indicate the data format so that other applications can recognize the data if they can use that format. You can also add data to the Clipboard in multiple different formats to increase the number of other applications that can potentially use the data. + +A Clipboard format is a string that identifies the format so that an application that uses that format can retrieve the associated data. The class provides predefined format names for your use. You can also use your own format names or use the type of an object as its format. + +To add data to the Clipboard in one or multiple formats, use the method. You can pass any object to this method, but to add data in multiple formats, you must first add the data to a separate object designed to work with multiple formats. Typically, you will add your data to a , but you can use any type that implements the interface. + +In .NET Framework 2.0, you can add data directly to the Clipboard by using new methods designed to make basic Clipboard tasks easier. Use these methods when you work with data in a single, common format such as text. + +> [!NOTE] +> All Windows-based applications share the Clipboard. Therefore, the contents are subject to change when you switch to another application. +> +> The class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your `Main` method is marked with the attribute. +> +> An object must be serializable for it to be put on the Clipboard. To make a type serializable, mark it with the attribute. If you pass a non-serializable object to a Clipboard method, the method will fail without throwing an exception. For more information about serialization, see . + +### To add data to the Clipboard in a single, common format + +1. Use the , , , or method. These methods are available only in .NET Framework 2.0. + + [!code-csharp[System.Windows.Forms.Clipboard#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#2)] + [!code-vb[System.Windows.Forms.Clipboard#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#2)] + +### To add data to the Clipboard in a custom format + +1. Use the method with a custom format name. This method is available only in .NET Framework 2.0. + + You can also use predefined format names with the method. For more information, see . + + [!code-csharp[System.Windows.Forms.Clipboard#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#3)] + [!code-vb[System.Windows.Forms.Clipboard#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#3)] + [!code-csharp[System.Windows.Forms.Clipboard#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#100)] + [!code-vb[System.Windows.Forms.Clipboard#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#100)] + +### To add data to the Clipboard in multiple formats + +1. Use the method and pass in a that contains your data. You must use this method to add data to the Clipboard on versions earlier than .NET Framework 2.0. + + [!code-csharp[System.Windows.Forms.Clipboard#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#4)] + [!code-vb[System.Windows.Forms.Clipboard#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#4)] + [!code-csharp[System.Windows.Forms.Clipboard#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#100)] + [!code-vb[System.Windows.Forms.Clipboard#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#100)] + +## See also + +- [Drag-and-Drop Operations and Clipboard Support](drag-and-drop-operations-and-clipboard-support.md) +- [How to: Retrieve Data from the Clipboard](how-to-retrieve-data-from-the-clipboard.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-add-multiple-sets-of-settings-to-your-application-in-csharp.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-add-multiple-sets-of-settings-to-your-application-in-csharp.md new file mode 100644 index 0000000000..8ebc9ccec4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-add-multiple-sets-of-settings-to-your-application-in-csharp.md @@ -0,0 +1,29 @@ +--- +title: "How To: Add Multiple Sets of Settings To Your Application in C#" +description: Learn how to add multiple sets of Windows Forms settings to your application in C# by using Visual Studio. +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], multiple sets" + - "application settings [Windows Forms], C#" +ms.assetid: 45007ac6-cf07-4be7-bc38-3f0ef962faf9 +--- +# How To: Add Multiple Sets of Settings To Your Application in C\# + +In some cases, you might want to have multiple sets of settings in an application. For example, if you are developing an application where a particular group of settings is expected to change frequently, it might be wise to separate them all into a single file so that the file can be replaced wholesale, leaving other settings unaffected. Visual Studio allows you to add multiple sets of settings to your project. Additional sets of settings can be accessed via the `Properties.Settings` object. + +## Add an Additional Set of Settings + +1. In Visual Studio, from the **Project** menu, choose **Add New Item**. + + The **Add New Item** dialog box opens. + +2. In the **Add New Item** dialog box, select **Settings File**, enter a name for the file, and click **Add** to add a new settings file to your solution. + +3. In **Solution Explorer**, drag the new Settings file into the **Properties** folder. This allows your new settings to be available in code. + +4. Add and use settings in this file as you would any other settings file. You can access this group of settings via the `Properties.Settings` object. + +## See also + +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [Application Settings Overview](application-settings-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-align-drawn-text.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-align-drawn-text.md new file mode 100644 index 0000000000..81d84508c8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-align-drawn-text.md @@ -0,0 +1,36 @@ +--- +title: "How to: Align Drawn Text" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "text [Windows Forms], aligning" + - "Windows Forms, aligning drawn text" +ms.assetid: 83c10a81-1a90-4b5c-98aa-2c6c4b280079 +--- +# How to: Align Drawn Text +When you perform custom drawing, you may often want to center drawn text on a form or control. You can easily align text drawn with the or methods by creating the correct formatting object and setting the appropriate format flags. + +### To draw centered text with GDI+ (DrawString) + +1. Use a with the appropriate method to specify centered text. + + [!code-csharp[System.Drawing.AlignDrawnText#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs#10)] + [!code-vb[System.Drawing.AlignDrawnText#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb#10)] + +### To draw centered text with GDI (DrawText) + +1. Use the enumeration for wrapping as well as vertically and horizontally centering text with the appropriate method. + + [!code-csharp[System.Drawing.AlignDrawnText#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs#20)] + [!code-vb[System.Drawing.AlignDrawnText#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb#20)] + +## Compiling the Code + The preceding code examples are designed for use with Windows Forms, and they require `e`, which is a parameter of . + +## See also + +- [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) +- [Using Fonts and Text](using-fonts-and-text.md) +- [How to: Construct Font Families and Fonts](how-to-construct-font-families-and-fonts.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-apply-gamma-correction-to-a-gradient.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-apply-gamma-correction-to-a-gradient.md new file mode 100644 index 0000000000..c706cbcf5e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-apply-gamma-correction-to-a-gradient.md @@ -0,0 +1,32 @@ +--- +title: "How to: Apply Gamma Correction to a Gradient" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "gradient brushes [Windows Forms], gamma correction" + - "gradients [Windows Forms], gamma correction" +ms.assetid: da4690e7-5fac-4fd2-b3f0-5cb35c165b92 +--- +# How to: Apply Gamma Correction to a Gradient +You can enable gamma correction for a linear gradient brush by setting the brush's property to `true`. You can disable gamma correction by setting the property to `false`. Gamma correction is disabled by default. + +## Example + +The following example is a method that is called from a control's event handler. The example creates a linear gradient brush and uses that brush to fill two rectangles. The first rectangle is filled without gamma correction, and the second rectangle is filled with gamma correction. + + The following illustration shows the two filled rectangles. The top rectangle, which does not have gamma correction, appears dark in the middle. The bottom rectangle, which has gamma correction, appears to have more uniform intensity. + + ![Two gradient-filled rectangles, with and without gamma correction.](./media/how-to-apply-gamma-correction-to-a-gradient/two-rectangles-gamma-gradient.png) + + [!code-csharp[System.Drawing.UsingaGradientBrush#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#31)] + [!code-vb[System.Drawing.UsingaGradientBrush#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#31)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- +- [Using a Gradient Brush to Fill Shapes](using-a-gradient-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-arrange-mdi-child-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-arrange-mdi-child-forms.md new file mode 100644 index 0000000000..965eb44d25 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-arrange-mdi-child-forms.md @@ -0,0 +1,50 @@ +--- +title: "How to: Arrange MDI Child Forms" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "child forms [Windows Forms], arranging" + - "MDI [Windows Forms], arranging child forms" +ms.assetid: a0786378-3206-4ccc-898e-7d3b38cc5089 +--- +# How to: Arrange MDI Child Forms +Often, applications will have menu commands for actions such as Tile, Cascade, and Arrange, which control the layout of the open MDI child forms. You can use the method with one of the enumeration values to rearrange the child forms in an MDI parent form. + + The enumeration values display child forms as cascading, as horizontally or vertically tiled, or as child form icons arranged along the lower portion of the MDI form. These values have the same effect as the Windows commands **Cascade windows**, **Show windows side by side**, **Show windows stacked**, and **Show the desktop**, respectively. + + Often, these methods are used as the event handlers called by a menu item's event. In this way, a menu item with the text "Cascade Windows" can have the desired effect on the MDI child windows. + +### To arrange child forms + +1. In a method, use the method to set the enumeration for the MDI parent form. The following example uses the enumeration value for the child windows of the MDI parent form (`Form1`). The enumeration is used in code during the event handler for the event of the **Cascade Windows** menu item. + + ```vb + Protected Sub CascadeWindows_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) + Me.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade) + End Sub + ``` + + ```csharp + protected void CascadeWindows_Click(object sender, System.EventArgs e){ + this.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade); + } + ``` + + > [!NOTE] + > You can also tile windows and arranging windows as icons by changing the enumeration value used. + +2. If you’re using Visual C#, place the following code in the form's constructor to register the event handler. + + ```csharp + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + +## See also + +- [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md) +- [How to: Create MDI Parent Forms](how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](how-to-create-mdi-child-forms.md) +- [How to: Determine the Active MDI Child](how-to-determine-the-active-mdi-child.md) +- [How to: Send Data to the Active MDI Child](how-to-send-data-to-the-active-mdi-child.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-capture-user-input-from-a-printdialog-at-run-time.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-capture-user-input-from-a-printdialog-at-run-time.md new file mode 100644 index 0000000000..bab349b8dc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-capture-user-input-from-a-printdialog-at-run-time.md @@ -0,0 +1,55 @@ +--- +title: "How to: Capture User Input from a PrintDialog at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "print options [Windows Forms], changing at run time" + - "printing [Windows Forms], options" + - "print options" + - "run time [Windows Forms], changing print options" +ms.assetid: 438501d8-9a70-4fb3-aae6-e46579aba0c6 +--- +# How to: Capture User Input from a PrintDialog at Run Time +While you can set options related to printing at design time, you will sometimes want to change these options at run time, most likely because of choices made by the user. You can capture user input for printing a document using the and the components. + +### To change print options programmatically + +1. Add a and a component to your form. + +2. Set the property of the to the added to the form. + + ```vb + PrintDialog1.Document = PrintDocument1 + ``` + + ```csharp + printDialog1.Document = PrintDocument1; + ``` + + ```cpp + printDialog1->Document = PrintDocument1; + ``` + +3. Display the component by using the method. + + ```vb + PrintDialog1.ShowDialog() + ``` + + ```csharp + printDialog1.ShowDialog(); + ``` + + ```cpp + printDialog1->ShowDialog(); + ``` + +4. The user's printing choices from the dialog will be copied to the property of the component. + +## See also + +- [How to: Print a Multi-Page Text File in Windows Forms](how-to-print-a-multi-page-text-file-in-windows-forms.md) +- [Windows Forms Print Support](windows-forms-print-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-change-the-value-of-a-setting-between-application-sessions.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-change-the-value-of-a-setting-between-application-sessions.md new file mode 100644 index 0000000000..16da24c9a4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-change-the-value-of-a-setting-between-application-sessions.md @@ -0,0 +1,29 @@ +--- +title: "How To: Change the Value of a Setting Between Application Sessions" +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], changing" + - "application settings [Windows Forms], between application sessions" +ms.assetid: 1a85911f-97b2-476c-930b-83379edd890c +--- +# How To: Change the Value of a Setting Between Application Sessions +At times, you might want to change the value of a setting between application sessions after the application has been compiled and deployed. For example, you might want to change a connection string to point to the correct database location. Since design-time tools are not available after the application has been compiled and deployed, you must change the setting value manually in the file. + +### To Change the Value of a Setting Between Application Sessions + +1. Using Microsoft Notepad or some other text or XML editor, open the .config file associated with your application. + +2. Locate the entry for the setting you want to change. It should look similar to the example presented below. + + ```xml + + My Setting Value + + ``` + +3. Type a new value for your setting and save the file. + +## See also + +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [Application Settings Overview](application-settings-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-change-the-value-of-an-existing-setting-at-design-time.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-change-the-value-of-an-existing-setting-at-design-time.md new file mode 100644 index 0000000000..cbc2279ba8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-change-the-value-of-an-existing-setting-at-design-time.md @@ -0,0 +1,32 @@ +--- +title: "How To: Change the Value of an Existing Setting at Design Time" +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], design time" + - "application settings [Windows Forms], changing" +ms.assetid: 5da91272-ad7e-49e7-9d1f-eb64439a1e4d +--- +# How To: Change the Value of an Existing Setting at Design Time +You can use Visual Studio to edit the values of existing settings in your project. + +### To Change the Value of an Existing Setting at Design Time in C\# + +1. In **Solution Explorer**, expand the **Properties** node of your project. + +2. Double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings. + +3. In the Settings designer, find the setting for which you want to change the value and type the new value in the Value column. + +### To Change the Value of an Existing Setting at Design Time in Visual Basic + +1. In **Solution Explorer**, right-click your project node and choose **Properties**. + +2. In the **Properties** page, select the **Settings** tab. + +3. In the Settings designer, find the setting for which you want to change the value and type the new value in the Value column. + +## See also + +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [How To: Create a New Setting at Design Time](how-to-create-a-new-setting-at-design-time.md) +- [Application Settings Overview](application-settings-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-choose-the-printers-attached-to-user-computer-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-choose-the-printers-attached-to-user-computer-in-windows-forms.md new file mode 100644 index 0000000000..09b79c3d20 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-choose-the-printers-attached-to-user-computer-in-windows-forms.md @@ -0,0 +1,105 @@ +--- +title: "How to: Choose the Printers Attached to a User's Computer" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "printing [Windows Forms], choosing printers" + - "printers [Windows Forms], choosing" +ms.assetid: 63c1172b-2931-4ac0-953f-37f629494bbf +--- +# How to: Choose the Printers Attached to a User's Computer in Windows Forms +Often, users want to choose a printer other than the default printer to print to. You can enable users to choose a printer from among those currently installed by using the component. Through the component, the of the component is captured and used to select the printer. + + In the following procedure, a text file is selected to be printed to the default printer. The class is then instantiated. + +### To choose a printer and then print a file + +1. Select the printer to be used using the component. + + In the following code example, there are two events being handled. In the first, a control's event, the class is instantiated and the printer selected by the user is captured in the property. + + In the second event, the event of the component, a sample document is printed to the printer specified. + + ```vb + Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click + Dim PrintDialog1 As New PrintDialog() + PrintDialog1.Document = PrintDocument1 + Dim result As DialogResult = PrintDialog1.ShowDialog() + + If (result = DialogResult.OK) Then + PrintDocument1.Print() + End If + + End Sub + + Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage + e.Graphics.FillRectangle(Brushes.Red, New Rectangle(500, 500, 500, 500)) + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + PrintDialog printDialog1 = new PrintDialog(); + printDialog1.Document = printDocument1; + DialogResult result = printDialog1.ShowDialog(); + if (result == DialogResult.OK) + { + printDocument1.Print(); + } + } + + private void printDocument1_PrintPage(object sender, + System.Drawing.Printing.PrintPageEventArgs e) + { + e.Graphics.FillRectangle(Brushes.Red, + new Rectangle(500, 500, 500, 500)); + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + PrintDialog ^ printDialog1 = gcnew PrintDialog(); + printDialog1->Document = printDocument1; + System::Windows::Forms::DialogResult result = + printDialog1->ShowDialog(); + if (result == DialogResult::OK) + { + printDocument1->Print(); + } + } + private: + void printDocument1_PrintPage(System::Object ^ sender, + System::Drawing::Printing::PrintPageEventArgs ^ e) + { + e->Graphics->FillRectangle(Brushes::Red, + Rectangle(500, 500, 500, 500)); + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.printDocument1.PrintPage += new + System.Drawing.Printing.PrintPageEventHandler + (this.printDocument1_PrintPage); + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + + ```cpp + this->printDocument1->PrintPage += gcnew + System::Drawing::Printing::PrintPageEventHandler + (this, &Form1::printDocument1_PrintPage); + this->button1->Click += gcnew + System::EventHandler(this, &Form1::button1_Click); + ``` + +## See also + +- [Windows Forms Print Support](windows-forms-print-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-complete-windows-forms-print-jobs.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-complete-windows-forms-print-jobs.md new file mode 100644 index 0000000000..5dc076e663 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-complete-windows-forms-print-jobs.md @@ -0,0 +1,80 @@ +--- +title: Complete Print Jobs +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "print jobs [Windows Forms], completing in Windows Forms" + - "printing [Windows Forms], print jobs" +ms.assetid: 23ec74f7-34c5-4710-82a0-ee2914518548 +--- +# How to: Complete Windows Forms Print Jobs +Frequently, word processors and other applications that involve printing will provide the option to display a message to users that a print job is complete. You can provide this functionality in your Windows Forms by handling the event of the component. + + The following procedure requires that you have created a Windows-based application with a component on it, which is the standard way of enabling printing from a Windows-based application. For more information about printing from Windows Forms using the component, see [How to: Create Standard Windows Forms Print Jobs](how-to-create-standard-windows-forms-print-jobs.md). + +### To complete a print job + +1. Set the property of the component. + + ```vb + PrintDocument1.DocumentName = "MyTextFile" + ``` + + ```csharp + printDocument1.DocumentName = "MyTextFile"; + ``` + + ```cpp + printDocument1->DocumentName = "MyTextFile"; + ``` + +2. Write code to handle the event. + + In the following code example, a message box is displayed, indicating that the document has finished printing. + + ```vb + Private Sub PrintDocument1_EndPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.EndPrint + MessageBox.Show(PrintDocument1.DocumentName + " has finished printing.") + End Sub + ``` + + ```csharp + private void printDocument1_EndPrint(object sender, + System.Drawing.Printing.PrintEventArgs e) + { + MessageBox.Show(printDocument1.DocumentName + + " has finished printing."); + } + ``` + + ```cpp + private: + void printDocument1_EndPrint(System::Object ^ sender, + System::Drawing::Printing::PrintEventArgs ^ e) + { + MessageBox::Show(String::Concat(printDocument1->DocumentName, + " has finished printing.")); + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.printDocument1.EndPrint += new + System.Drawing.Printing.PrintEventHandler + (this.printDocument1_EndPrint); + ``` + + ```cpp + this->printDocument1->EndPrint += gcnew + System::Drawing::Printing::PrintEventHandler + (this, &Form1::printDocument1_EndPrint); + ``` + +## See also + +- +- [Windows Forms Print Support](windows-forms-print-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-construct-font-families-and-fonts.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-construct-font-families-and-fonts.md new file mode 100644 index 0000000000..2ecf6b0279 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-construct-font-families-and-fonts.md @@ -0,0 +1,49 @@ +--- +title: "How to: Construct Font Families and Fonts" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "font families [Windows Forms], constructing" + - "fonts [Windows Forms], constructing" +ms.assetid: d3a4a223-9492-4b54-9afd-db1c31c3cefd +--- +# How to: Construct Font Families and Fonts +GDI+ groups fonts with the same typeface but different styles into font families. For example, the Arial font family contains the following fonts: + +- Arial Regular + +- Arial Bold + +- Arial Italic + +- Arial Bold Italic + + GDI+ uses four styles to form families: regular, bold, italic, and bold italic. Adjectives such as *narrow* and *rounded* are not considered styles; rather they are part of the family name. For example, Arial Narrow is a font family with the following members: + +- Arial Narrow Regular + +- Arial Narrow Bold + +- Arial Narrow Italic + +- Arial Narrow Bold Italic + + Before you can draw text with GDI+, you need to construct a object and a object. The object specifies the typeface (for example, Arial), and the object specifies the size, style, and units. + +## Example + The following example constructs a regular style Arial font with a size of 16 pixels. In the following code, the first argument passed to the constructor is the object. The second argument specifies the size of the font measured in units identified by the fourth argument. The third argument identifies the style. + + is a member of the enumeration, and is a member of the enumeration. + + [!code-csharp[System.Drawing.FontsAndText#61](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#61)] + [!code-vb[System.Drawing.FontsAndText#61](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#61)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Using Fonts and Text](using-fonts-and-text.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-convert-a-bmp-image-to-a-png-image.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-convert-a-bmp-image-to-a-png-image.md new file mode 100644 index 0000000000..00efd040b6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-convert-a-bmp-image-to-a-png-image.md @@ -0,0 +1,32 @@ +--- +title: "How to: Convert a BMP image to a PNG image" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "BMP images [Windows Forms], converting to PNG" + - "image formats [Windows Forms], converting between" +ms.assetid: 9d4a692d-73ac-4ce3-9e05-9ec321e8fbd6 +--- +# How to: Convert a BMP image to a PNG image +Oftentimes, you will want to convert from one image file format to another. You can do this conversion easily by calling the method of the class and specifying the for the desired image file format. + +## Example + The following example loads a BMP image from a type, and saves the image in the PNG format. + + [!code-csharp[UsingImageEncodersDecoders#4](~/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs#4)] + [!code-vb[UsingImageEncodersDecoders#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb#4)] + +## Compiling the Code + This example requires: + +- A Windows Forms application. + +- A reference to the `System.Drawing.Imaging` namespace. + +## See also + +- [How to: List Installed Encoders](how-to-list-installed-encoders.md) +- [Using Image Encoders and Decoders in Managed GDI+](using-image-encoders-and-decoders-in-managed-gdi.md) +- [Types of Bitmaps](types-of-bitmaps.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-copy-and-paste-an-elementhost-control-at-design-time.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-copy-and-paste-an-elementhost-control-at-design-time.md new file mode 100644 index 0000000000..69e34d46d0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-copy-and-paste-an-elementhost-control-at-design-time.md @@ -0,0 +1,44 @@ +--- +title: "How to: Copy and Paste an ElementHost Control at Design Time" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, content copying and pasting" + - "interoperability [WPF]" + - "ElementHost control [Windows Forms], copying and pasting at design time" + - "WPF user control [Windows Forms], hosting in Windows Forms" +ms.assetid: e570375d-2a68-44ba-b4f7-c781af2d20e8 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Copy and paste an ElementHost control + +This procedure shows you how to copy a Windows Presentation Foundation (WPF) control on a Windows Form in Visual Studio. + +1. In Visual Studio, add a new WPF to a Windows Forms project. Use the default name for the control type, `UserControl1.xaml`. For more information, see [Walkthrough: Creating New WPF Content on Windows Forms at Design Time](walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md). + +2. In the **Properties** window, set the value of the and properties of `UserControl1` to **200**. + +3. Set the value of the property to **Blue**. + +4. Build the project. + +5. Open `Form1` in the Windows Forms Designer. + +6. From the **Toolbox**, drag an instance of `UserControl1` onto the form. + + An instance of `UserControl1` is hosted in a new control named `elementHost1`. + +7. With `elementHost1` selected, press **Ctrl**+**C** to copy it to the clipboard. + +8. Press **Ctrl**+**V** to paste the copied control onto the form. + + A new control named `elementHost2` is created on the form. + +## See also + +- +- +- [Migration and Interoperability](https://docs.microsoft.com/dotnet/framework/wpf/advanced/migration-and-interoperability) +- [Using WPF Controls](using-wpf-controls.md) +- [Design XAML in Visual Studio](/visualstudio/xaml-tools/designing-xaml-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-copy-pixels-for-reducing-flicker-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-copy-pixels-for-reducing-flicker-in-windows-forms.md new file mode 100644 index 0000000000..6c6cfd6a03 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-copy-pixels-for-reducing-flicker-in-windows-forms.md @@ -0,0 +1,65 @@ +--- +title: "How to: Copy Pixels for Reducing Flicker" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "bitblt" + - "graphics [Windows Forms], copying" + - "flicker [Windows Forms], reducing in Windows Forms" + - "graphics [Windows Forms], reducing flicker" + - "pixels [Windows Forms], copying" + - "flicker" + - "bit-block transfer" +ms.assetid: 33b76910-13a3-4521-be98-5c097341ae3b +--- +# How to: Copy Pixels for Reducing Flicker in Windows Forms +When you animate a simple graphic, users can sometimes encounter flicker or other undesirable visual effects. One way to limit this problem is to use a "bitblt" process on the graphic. Bitblt is the "bit-block transfer" of the color data from an origin rectangle of pixels to a destination rectangle of pixels. + + With Windows Forms, bitblt is accomplished using the method of the class. In the parameters of the method, you specify the source and destination (as points), the size of the area to be copied, and the graphics object used to draw the new shape. + + In the example below, a shape is drawn on the form in its event handler. Then, the method is used to duplicate the shape. + +> [!NOTE] +> Setting the form's property to `true` will make graphics-based code in the event be double-buffered. While this will not have any discernible performance gains when using the code below, it is something to keep in mind when working with more complex graphics-manipulation code. + +## Example + +```vb +Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _ + System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint + ' Draw a circle with a bar on top. + e.Graphics.FillEllipse(Brushes.DarkBlue, New Rectangle _ + (10, 10, 60, 60)) + e.Graphics.FillRectangle(Brushes.Khaki, New Rectangle _ + (20, 30, 60, 10)) + ' Copy the graphic to a new location. + e.Graphics.CopyFromScreen(New Point(10, 10), New Point _ + (100, 100), New Size(70, 70)) +End Sub +``` + +```csharp +private void Form1_Paint(System.Object sender, + System.Windows.Forms.PaintEventArgs e) + { + e.Graphics.FillEllipse(Brushes.DarkBlue, new + Rectangle(10,10,60,60)); + e.Graphics.FillRectangle(Brushes.Khaki, new + Rectangle(20,30,60,10)); + e.Graphics.CopyFromScreen(new Point(10, 10), new Point(100, 100), + new Size(70, 70)); +} +``` + +## Compiling the Code + The code above is run in the form's event handler so that the graphics persist when the form is redrawn. As such, do not call graphics-related methods in the event handler, because the drawn content will not be redrawn if the form is resized or obscured by another form. + +## See also + +- +- +- +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-bitmap-at-run-time.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-bitmap-at-run-time.md new file mode 100644 index 0000000000..cf85cf280c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-bitmap-at-run-time.md @@ -0,0 +1,28 @@ +--- +title: "How to: Create a Bitmap at Run Time" +description: Learn how to create a bitmap object and display it in an existing Windows Forms PictureBox control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "bitmaps [Windows Forms], creating" + - "bitmaps [Windows Forms], examples [Visual Basic]" +ms.assetid: 737bae30-e599-4e1d-bf30-bab8280b32be +--- +# How to: Create a Bitmap at Run Time +This example creates and draws in a object and displays it in an existing Windows Forms control. + +## Example + [!code-csharp[System.Drawing.CreateBitmapAtRuntime#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/CS/Form1.cs#1)] + [!code-vb[System.Drawing.CreateBitmapAtRuntime#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- A Windows Form that imports the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-linear-gradient.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-linear-gradient.md new file mode 100644 index 0000000000..1e04e51c3a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-linear-gradient.md @@ -0,0 +1,80 @@ +--- +title: "How to: Create a Linear Gradient" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "linear gradients [Windows Forms], creating" + - "gradients [Windows Forms], creating linear" + - "colors [Windows Forms], creating linear gradients" + - "gradients" +ms.assetid: 6c88e1cc-1217-4399-ac12-cb37592b9f01 +--- +# How to: Create a Linear Gradient +GDI+ provides horizontal, vertical, and diagonal linear gradients. By default, the color in a linear gradient changes uniformly. However, you can customize a linear gradient so that the color changes in a non-uniform fashion. + +> [!NOTE] +> The examples in this article are methods that are called from a control's event handler. + +The following example fills a line, an ellipse, and a rectangle with a horizontal linear gradient brush. + +The constructor receives four arguments: two points and two colors. The first point (0, 10) is associated with the first color (red), and the second point (200, 10) is associated with the second color (blue). As you would expect, the line drawn from (0, 10) to (200, 10) changes gradually from red to blue. + + The 10s in the points (0, 10) and (200, 10) are not important. What is important is that the two points have the same second coordinate — the line connecting them is horizontal. The ellipse and the rectangle also change gradually from red to blue as the horizontal coordinate goes from 0 to 200. + + The following illustration shows the line, the ellipse, and the rectangle. Note that the color gradient repeats itself as the horizontal coordinate increases beyond 200. + + ![A line, an ellipse, and a rectangle filled with a color gradient.](./media/how-to-create-a-linear-gradient/gradient-line-ellipse-rectangle.png) + +## To use horizontal linear gradients + +- Pass in the opaque red and opaque blue as the third and fourth argument, respectively. + + [!code-csharp[System.Drawing.UsingaGradientBrush#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#21)] + [!code-vb[System.Drawing.UsingaGradientBrush#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#21)] + + In the preceding example, the color components change linearly as you move from a horizontal coordinate of 0 to a horizontal coordinate of 200. For example, a point whose first coordinate is halfway between 0 and 200 will have a blue component that is halfway between 0 and 255. + + GDI+ allows you to adjust the way a color varies from one edge of a gradient to the other. Suppose you want to create a gradient brush that changes from black to red according to the following table. + +|Horizontal coordinate|RGB components| +|---------------------------|--------------------| +|0|(0, 0, 0)| +|40|(128, 0, 0)| +|200|(255, 0, 0)| + + Note that the red component is at half intensity when the horizontal coordinate is only 20 percent of the way from 0 to 200. + + The following example sets the property to associate three relative intensities with three relative positions. As in the preceding table, a relative intensity of 0.5 is associated with a relative position of 0.2. The code fills an ellipse and a rectangle with the gradient brush. + + The following illustration shows the resulting ellipse and rectangle. + + ![An ellipse and a rectangle filled with a horizontal color gradient.](./media/how-to-create-a-linear-gradient/gradient-ellipse-rectangle.png) + +## To customize linear gradients + +- Pass in the opaque black and opaque red as the third and fourth argument, respectively. + + [!code-csharp[System.Drawing.UsingaGradientBrush#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#22)] + [!code-vb[System.Drawing.UsingaGradientBrush#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#22)] + + The gradients in the preceding examples have been horizontal; that is, the color changes gradually as you move along any horizontal line. You can also define vertical gradients and diagonal gradients. + + The following example passes the points (0, 0) and (200, 100) to a constructor. The color blue is associated with (0, 0), and the color green is associated with (200, 100). A line (with pen width 10) and an ellipse are filled with the linear gradient brush. + + The following illustration shows the line and the ellipse. Note that the color in the ellipse changes gradually as you move along any line that is parallel to the line passing through (0, 0) and (200, 100). + + ![A line and an ellipse filled with a diagonal color gradient.](./media/how-to-create-a-linear-gradient/gradient-line-ellipse.png) + +## To create diagonal linear gradients + +- Pass in the opaque blue and opaque green as the third and fourth argument, respectively. + + [!code-csharp[System.Drawing.UsingaGradientBrush#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#23)] + [!code-vb[System.Drawing.UsingaGradientBrush#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#23)] + +## See also + +- [Using a Gradient Brush to Fill Shapes](using-a-gradient-brush-to-fill-shapes.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-new-setting-at-design-time.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-new-setting-at-design-time.md new file mode 100644 index 0000000000..81f0d568bd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-new-setting-at-design-time.md @@ -0,0 +1,38 @@ +--- +title: "How To: Create a New Setting at Design Time" +description: Learn how to create a new Windows Forms setting at design time by using the Settings designer in Visual Studio. +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], design time" + - "application settings [Windows Forms], creating" +ms.assetid: c5d60a66-6507-462f-a81f-e3bc0a804e16 +--- +# How To: Create a new setting at design time + +You can create a new setting at design time by using the Settings designer in Visual Studio. The Settings designer is a grid-style interface that allows you to create new settings and specify properties for those settings. You must specify Name, Value, Type and Scope for your new settings. Once a setting is created, it is accessible in code. + +## Create a new setting at design time in C\# + +1. Open Visual Studio. + +2. In **Solution Explorer**, expand the **Properties** node of your project. + +3. Double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings. + +4. In the Settings designer, set the **Name**, **Value**, **Type**, and **Scope** for your setting. Each row represents a single setting. + +## Create a new setting at design time in Visual Basic + +1. Open Visual Studio. + +2. In **Solution Explorer**, right-click your project node and choose **Properties**. + +3. In the **Properties** page, select the **Settings** tab. + +4. In the Settings designer, set the **Name**, **Value**, **Type**, and **Scope** for your setting. Each row represents a single setting. + +## See also + +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [Application Settings Overview](application-settings-overview.md) +- [How To: Change the Value of an Existing Setting at Design Time](how-to-change-the-value-of-an-existing-setting-at-design-time.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-path-gradient.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-path-gradient.md new file mode 100644 index 0000000000..7ed35b7ebc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-path-gradient.md @@ -0,0 +1,111 @@ +--- +title: "How to: Create a Path Gradient" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "path gradients [Windows Forms], creating" + - "gradients [Windows Forms], creating path" + - "graphics paths [Windows Forms], creating gradient" +ms.assetid: 1948e834-e104-481c-b71d-d8aa9e4d106e +--- +# How to: Create a Path Gradient +The class allows you to customize the way you fill a shape with gradually changing colors. For example, you can specify one color for the center of a path and another color for the boundary of a path. You can also specify separate colors for each of several points along the boundary of a path. + +> [!NOTE] +> In GDI+, a path is a sequence of lines and curves maintained by a object. For more information about GDI+ paths, see [Graphics Paths in GDI+](graphics-paths-in-gdi.md) and [Constructing and Drawing Paths](constructing-and-drawing-paths.md). + +The examples in this article are methods that are called from a control's event handler. + +### To fill an ellipse with a path gradient + +- The following example fills an ellipse with a path gradient brush. The center color is set to blue and the boundary color is set to aqua. The following illustration shows the filled ellipse. + + ![Gradient Path fills an ellipse.](./media/how-to-create-a-path-gradient/gradient-path-filled-ellipse.png) + + By default, a path gradient brush does not extend outside the boundary of the path. If you use the path gradient brush to fill a figure that extends beyond the boundary of the path, the area of the screen outside the path will not be filled. + + The following illustration shows what happens if you change the call in the following code to `e.Graphics.FillRectangle(pthGrBrush, 0, 10, 200, 40)`: + + ![Gradient Path extended beyond boundary of the path.](./media/how-to-create-a-path-gradient/gradient-path-extended-beyond-boundary.png) + + [!code-csharp[System.Drawing.UsingaGradientBrush#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#11)] + [!code-vb[System.Drawing.UsingaGradientBrush#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#11)] + + The preceding code example is designed for use with Windows Forms, and it requires the e, which is a parameter of . + +### To specify points on the boundary + +- The following example constructs a path gradient brush from a star-shaped path. The code sets the property, which sets the color at the centroid of the star to red. Then the code sets the property to specify various colors (stored in the `colors` array) at the individual points in the `points` array. The final code statement fills the star-shaped path with the path gradient brush. + + [!code-csharp[System.Drawing.UsingaGradientBrush#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#12)] + [!code-vb[System.Drawing.UsingaGradientBrush#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#12)] + +- The following example draws a path gradient without a object in the code. The particular constructor in the example receives an array of points but does not require a object. Also, note that the is used to fill a rectangle, not a path. The rectangle is larger than the closed path used to define the brush, so some of the rectangle is not painted by the brush. The following illustration shows the rectangle (dotted line) and the portion of the rectangle painted by the path gradient brush: + + ![Gradient portion painted by the path gradient brush.](./media/how-to-create-a-path-gradient/gradient-painted-path-gradient-brush.png) + + [!code-csharp[System.Drawing.UsingaGradientBrush#13](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#13)] + [!code-vb[System.Drawing.UsingaGradientBrush#13](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#13)] + +### To customize a path gradient + +- One way to customize a path gradient brush is to set its property. The focus scales specify an inner path that lies inside the main path. The center color is displayed everywhere inside that inner path rather than only at the center point. + + The following example creates a path gradient brush based on an elliptical path. The code sets the boundary color to blue, sets the center color to aqua, and then uses the path gradient brush to fill the elliptical path. + + Next, the code sets the focus scales of the path gradient brush. The x focus scale is set to 0.3, and the y focus scale is set to 0.8. The code calls the method of a object so that the subsequent call to fills an ellipse that sits to the right of the first ellipse. + + To see the effect of the focus scales, imagine a small ellipse that shares its center with the main ellipse. The small (inner) ellipse is the main ellipse scaled (about its center) horizontally by a factor of 0.3 and vertically by a factor of 0.8. As you move from the boundary of the outer ellipse to the boundary of the inner ellipse, the color changes gradually from blue to aqua. As you move from the boundary of the inner ellipse to the shared center, the color remains aqua. + + The following illustration shows the output of the following code. The ellipse on the left is aqua only at the center point. The ellipse on the right is aqua everywhere inside the inner path. + + ![Gradient effect of focus scales](./media/how-to-create-a-path-gradient/focus-scales-aqua-inner-outer-ellipse.png) + + [!code-csharp[System.Drawing.UsingaGradientBrush#14](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#14)] + [!code-vb[System.Drawing.UsingaGradientBrush#14](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#14)] + +### To customize with interpolation + +- Another way to customize a path gradient brush is to specify an array of interpolation colors and an array of interpolation positions. + + The following example creates a path gradient brush based on a triangle. The code sets the property of the path gradient brush to specify an array of interpolation colors (dark green, aqua, blue) and an array of interpolation positions (0, 0.25, 1). As you move from the boundary of the triangle to the center point, the color changes gradually from dark green to aqua and then from aqua to blue. The change from dark green to aqua happens in 25 percent of the distance from dark green to blue. + + The following illustration shows the triangle filled with the custom path gradient brush. + + ![Triangle filled with custom path gradient brush.](./media/how-to-create-a-path-gradient/gradient-brush-filled-triangle.png) + + [!code-csharp[System.Drawing.UsingaGradientBrush#15](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#15)] + [!code-vb[System.Drawing.UsingaGradientBrush#15](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#15)] + +### To set the center point + +- By default, the center point of a path gradient brush is at the centroid of the path used to construct the brush. You can change the location of the center point by setting the property of the class. + + The following example creates a path gradient brush based on an ellipse. The center of the ellipse is at (70, 35), but the center point of the path gradient brush is set to (120, 40). + + [!code-csharp[System.Drawing.UsingaGradientBrush#16](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#16)] + [!code-vb[System.Drawing.UsingaGradientBrush#16](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#16)] + + The following illustration shows the filled ellipse and the center point of the path gradient brush: + + ![Gradient Path with filled ellipse and center point.](./media/how-to-create-a-path-gradient/gradient-path-filled-ellipse-center-point.png) + +- You can set the center point of a path gradient brush to a location outside the path that was used to construct the brush. The following example replaces the call to set the property in the preceding code. + + [!code-csharp[System.Drawing.UsingaGradientBrush#17](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs#17)] + [!code-vb[System.Drawing.UsingaGradientBrush#17](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb#17)] + + The following illustration shows the output with this change: + + ![Gradient Path with center point outside the path.](./media/how-to-create-a-path-gradient/gradient-path-center-point-outside.png) + + In the preceding illustration, the points at the far right of the ellipse are not pure blue (although they are very close). The colors in the gradient are positioned as if the fill reached the point (145, 35) where the color would be pure blue (0, 0, 255). But the fill never reaches (145, 35) because a path gradient brush paints only inside its path. + +## Compiling the Code + The preceding examples are designed for use with Windows Forms, and they require `e`, which is a parameter of the event handler. + +## See also + +- [Using a Gradient Brush to Fill Shapes](using-a-gradient-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-pen.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-pen.md new file mode 100644 index 0000000000..7fc10a615e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-pen.md @@ -0,0 +1,29 @@ +--- +title: "How to: Create a Pen" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "graphics [Windows Forms], creating pens" + - "pens [Windows Forms], creating" + - "Pen object" +ms.assetid: 7fbea8b7-7ac1-4413-9c17-733a850381e3 +--- +# How to: Create a Pen +This example creates a object. + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#3](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#3)] + [!code-csharp[System.Drawing.ConceptualHowTos#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#3)] + [!code-vb[System.Drawing.ConceptualHowTos#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#3)] + +## Robust Programming + After you have finished using objects that consume system resources, such as objects, you should call on them. + +## See also + +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Pens, Lines, and Rectangles in GDI+](pens-lines-and-rectangles-in-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-private-font-collection.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-private-font-collection.md new file mode 100644 index 0000000000..706d3dbae5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-private-font-collection.md @@ -0,0 +1,51 @@ +--- +title: "How to: Create a Private Font Collection" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "private font collections [Windows Forms], creating" + - "fonts [Windows Forms], creating private collections" +ms.assetid: 6533d5e5-a8dc-4b76-9fc4-3bf75c8b9212 +--- +# How to: Create a Private Font Collection +The class inherits from the abstract base class. You can use a object to maintain a set of fonts specifically for your application. A private font collection can include installed system fonts as well as fonts that have not been installed on the computer. To add a font file to a private font collection, call the method of a object. + + The property of a object contains an array of objects. + + The number of font families in a private font collection is not necessarily the same as the number of font files that have been added to the collection. For example, suppose you add the files ArialBd.tff, Times.tff, and TimesBd.tff to a collection. There will be three files but only two families in the collection because Times.tff and TimesBd.tff belong to the same family. + +## Example + The following example adds the following three font files to a object: + +- C:\\*systemroot*\Fonts\Arial.tff (Arial, regular) + +- C:\\*systemroot*\Fonts\CourBI.tff (Courier New, bold italic) + +- C:\\*systemroot*\Fonts\TimesBd.tff (Times New Roman, bold) + + The code retrieves an array of objects from the property of the object. + + For each object in the collection, the code calls the method to determine whether various styles (regular, bold, italic, bold italic, underline, and strikeout) are available. The arguments passed to the method are members of the enumeration. + + If a given family/style combination is available, a object is constructed using that family and style. The first argument passed to the constructor is the font family name (not a object as is the case for other variations of the constructor). After the object is constructed, it is passed to the method of the class to display the family name along with the name of the style. + + The output of the following code is similar to the output shown in the following illustration: + + ![Screenshot that shows text in various fonts.](./media/how-to-create-a-private-font-collection/various-fonts-text-output.png) + + Arial.tff (which was added to the private font collection in the following code example) is the font file for the Arial regular style. Note, however, that the program output shows several available styles other than regular for the Arial font family. That is because GDI+ can simulate the bold, italic, and bold italic styles from the regular style. GDI+ can also produce underlines and strikeouts from the regular style. + + Similarly, GDI+ can simulate the bold italic style from either the bold style or the italic style. The program output shows that the bold italic style is available for the Times family even though TimesBd.tff (Times New Roman, bold) is the only Times file in the collection. + + [!code-csharp[System.Drawing.FontsAndText#51](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#51)] + [!code-vb[System.Drawing.FontsAndText#51](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#51)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-shaped-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-shaped-windows-form.md new file mode 100644 index 0000000000..fe6beb45d3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-shaped-windows-form.md @@ -0,0 +1,44 @@ +--- +title: "How to: Create a Shaped Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "forms [Windows Forms], rounded" + - "Windows Forms, custom shapes" + - "Windows Forms, shaped" + - "shaped forms" + - "forms [Windows Forms], changing the shape of" + - "forms [Windows Forms], circular" + - "forms [Windows Forms], nonrectangular" + - "Windows Forms, nonrectangular shape" + - "Windows Forms, rounded" + - "Windows Forms, circular" + - "forms [Windows Forms], custom shapes" +ms.assetid: 6e6041e0-8e67-4487-b1e9-e410dbd1ef6c +--- +# How to: Create a Shaped Windows Form +This example gives a form an elliptical shape that resizes with the form. + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#10](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#10)] + [!code-csharp[System.Drawing.ConceptualHowTos#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#10)] + [!code-vb[System.Drawing.ConceptualHowTos#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#10)] + +## Compiling the Code + This example requires: + +- References to the and namespaces. + + This example overrides the method to change the shape of the form. To use this code, copy the method declaration as well as the drawing code inside the method. + +## See also + +- +- +- +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-solid-brush.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-solid-brush.md new file mode 100644 index 0000000000..5c11edfca5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-a-solid-brush.md @@ -0,0 +1,31 @@ +--- +title: "How to: Create a Solid Brush" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "solid color brushes" + - "brushes [Windows Forms], examples" + - "brushes [Windows Forms], creating solid" +ms.assetid: 85c3fe7d-fb1d-4591-8a9f-d75b556b90af +--- +# How to: Create a Solid Brush +This example creates a object that can be used by a object for filling shapes. + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#1)] + [!code-csharp[System.Drawing.ConceptualHowTos#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#1)] + [!code-vb[System.Drawing.ConceptualHowTos#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#1)] + +## Robust Programming + After you have finished using them, you should call on objects that consume system resources, such as brush objects. + +## See also + +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Brushes and Filled Shapes in GDI+](brushes-and-filled-shapes-in-gdi.md) +- [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-application-settings.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-application-settings.md new file mode 100644 index 0000000000..0797febb44 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-application-settings.md @@ -0,0 +1,48 @@ +--- +title: "How to: Create Application Settings" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "application settings [Windows Forms], Windows Forms" + - "application settings [Windows Forms], creating" +ms.assetid: 1e7aa347-af75-41e5-89ca-f53cab704f72 +--- +# How to: Create Application Settings +Using managed code, you can create new application settings and bind them to properties on your form or your form's controls, so that these settings are loaded and saved automatically at run time. + + In the following procedure, you manually create a wrapper class that derives from . To this class you add a publicly accessible property for each application setting that you want to expose. + + You can also perform this procedure using minimal code in the Visual Studio designer. Also see [How to: Create Application Settings Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/wabtadw6(v=vs.100)). + +### To create new Application Settings programmatically + +1. Add a new class to your project, and rename it. For this procedure, we will call this class `MyUserSettings`. Change the class definition so that the class derives from . + +2. Define a property on this wrapper class for each application setting you require, and apply that property with either the or , depending on the scope of the setting. For more information about settings scope, see [Application Settings Overview](application-settings-overview.md). By now, your code should look like this: + + [!code-csharp[ApplicationSettings.Create#1](~/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/MyAppSettings.cs#1)] + [!code-vb[ApplicationSettings.Create#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/MyAppSettings.vb#1)] + +3. Create an instance of this wrapper class in your application. It will commonly be a private member of the main form. Now that you have defined your class, you need to bind it to a property; in this case, the property of your form. You can accomplish this in your form's `Load` event handler. + + [!code-csharp[ApplicationSettings.Create#2](~/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.cs#2)] + [!code-vb[ApplicationSettings.Create#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.vb#2)] + +4. If you provide a way to change settings at run time, you will need to save the user's current settings to disk when your form closes, or else these changes will be lost. + + [!code-csharp[ApplicationSettings.Create#3](~/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.cs#3)] + [!code-vb[ApplicationSettings.Create#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.vb#3)] + + You have now successfully created a new application setting and bound it to the specified property. + +## .NET Framework Security + The default settings provider, , persists information to configuration files as plain text. This limits security to the file access security provided by the operating system for the current user. Because of this, care must be taken with the information stored in configuration files. For example, one common use for application settings is to store connection strings that point to the application's data store. However, because of security concerns, such strings should not include passwords. For more information about connection strings, see . + +## See also + +- +- +- [Application Settings Overview](application-settings-overview.md) +- [How to: Validate Application Settings](how-to-validate-application-settings.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-figures-from-lines-curves-and-shapes.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-figures-from-lines-curves-and-shapes.md new file mode 100644 index 0000000000..64ae8d19da --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-figures-from-lines-curves-and-shapes.md @@ -0,0 +1,35 @@ +--- +title: "How to: Create Figures from Lines, Curves, and Shapes" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "figures [Windows Forms], creating from shapes" + - "figures [Windows Forms], creating from lines" +ms.assetid: 82fd56c7-b443-4765-9b7c-62ce030656ec +--- +# How to: Create Figures from Lines, Curves, and Shapes +To create a figure, construct a , and then call methods, such as and , to add primitives to the path. + +## Example + The following code examples create paths that have figures: + +- The first example creates a path that has a single figure. The figure consists of a single arc. The arc has a sweep angle of –180 degrees, which is counterclockwise in the default coordinate system. + +- The second example creates a path that has two figures. The first figure is an arc followed by a line. The second figure is a line followed by a curve followed by a line. The first figure is left open, and the second figure is closed. + + [!code-csharp[System.Drawing.ConstructingDrawingPaths#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/CS/Class1.cs#21)] + [!code-vb[System.Drawing.ConstructingDrawingPaths#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/VB/Class1.vb#21)] + + [!code-csharp[System.Drawing.ConstructingDrawingPaths#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/CS/Class1.cs#22)] + [!code-vb[System.Drawing.ConstructingDrawingPaths#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/VB/Class1.vb#22)] + +## Compiling the Code + The previous examples are designed for use with Windows Forms, and they require `e`, which is a parameter of the event handler. + +## See also + +- +- [Constructing and Drawing Paths](constructing-and-drawing-paths.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-graphics-objects-for-drawing.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-graphics-objects-for-drawing.md new file mode 100644 index 0000000000..81046ef6ce --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-graphics-objects-for-drawing.md @@ -0,0 +1,173 @@ +--- +title: "How to: Create Graphics Objects for Drawing" +description: Learn now to create a Graphic object that you need to draw lines and shapes, render text, or display and manipulate images with GDI+. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "graphics [Windows Forms], creating" + - "images [Windows Forms], creating" + - "GDI+, creating images" +ms.assetid: 162861f9-f050-445e-8abb-b2c43a918b8b +--- +# How to: Create Graphics Objects for Drawing +Before you can draw lines and shapes, render text, or display and manipulate images with GDI+, you need to create a object. The object represents a GDI+ drawing surface, and is the object that is used to create graphical images. + + There are two steps in working with graphics: + +1. Creating a object. + +2. Using the object to draw lines and shapes, render text, or display and manipulate images. + +## Creating a Graphics Object + A graphics object can be created in a variety of ways. + +#### To create a graphics object + +- Receive a reference to a graphics object as part of the in the event of a form or control. This is usually how you obtain a reference to a graphics object when creating painting code for a control. Similarly, you can also obtain a graphics object as a property of the when handling the event for a . + + -or- + +- Call the method of a control or form to obtain a reference to a object that represents the drawing surface of that control or form. Use this method if you want to draw on a form or control that already exists. + + -or- + +- Create a object from any object that inherits from . This approach is useful when you want to alter an already existing image. + + The following sections give details about each of these processes. + +## PaintEventArgs in the Paint Event Handler + When programming the for controls or the for a , a graphics object is provided as one of the properties of or . + +#### To obtain a reference to a Graphics object from the PaintEventArgs in the Paint event + +1. Declare the object. + +2. Assign the variable to refer to the object passed as part of the . + +3. Insert code to paint the form or control. + + The following example shows how to reference a object from the in the event: + + ```vb + Private Sub Form1_Paint(sender As Object, pe As PaintEventArgs) Handles _ + MyBase.Paint + ' Declares the Graphics object and sets it to the Graphics object + ' supplied in the PaintEventArgs. + Dim g As Graphics = pe.Graphics + ' Insert code to paint the form here. + End Sub + ``` + + ```csharp + private void Form1_Paint(object sender, + System.Windows.Forms.PaintEventArgs pe) + { + // Declares the Graphics object and sets it to the Graphics object + // supplied in the PaintEventArgs. + Graphics g = pe.Graphics; + // Insert code to paint the form here. + } + ``` + + ```cpp + private: + void Form1_Paint(System::Object ^ sender, + System::Windows::Forms::PaintEventArgs ^ pe) + { + // Declares the Graphics object and sets it to the Graphics object + // supplied in the PaintEventArgs. + Graphics ^ g = pe->Graphics; + // Insert code to paint the form here. + } + ``` + +## CreateGraphics Method + You can also use the method of a control or form to obtain a reference to a object that represents the drawing surface of that control or form. + +#### To create a Graphics object with the CreateGraphics method + +- Call the method of the form or control upon which you want to render graphics. + + ```vb + Dim g as Graphics + ' Sets g to a Graphics object representing the drawing surface of the + ' control or form g is a member of. + g = Me.CreateGraphics + ``` + + ```csharp + Graphics g; + // Sets g to a graphics object representing the drawing surface of the + // control or form g is a member of. + g = this.CreateGraphics(); + ``` + + ```cpp + Graphics ^ g; + // Sets g to a graphics object representing the drawing surface of the + // control or form g is a member of. + g = this->CreateGraphics(); + ``` + +## Create from an Image Object + Additionally, you can create a graphics object from any object that derives from the class. + +#### To create a Graphics object from an Image + +- Call the method, supplying the name of the Image variable from which you want to create a object. + + The following example shows how to use a object: + + ```vb + Dim myBitmap as New Bitmap("C:\Documents and Settings\Joe\Pics\myPic.bmp") + Dim g as Graphics = Graphics.FromImage(myBitmap) + ``` + + ```csharp + Bitmap myBitmap = new Bitmap(@"C:\Documents and + Settings\Joe\Pics\myPic.bmp"); + Graphics g = Graphics.FromImage(myBitmap); + ``` + + ```cpp + Bitmap ^ myBitmap = gcnew + Bitmap("D:\\Documents and Settings\\Joe\\Pics\\myPic.bmp"); + Graphics ^ g = Graphics::FromImage(myBitmap); + ``` + +> [!NOTE] +> You can only create objects from nonindexed .bmp files, such as 16-bit, 24-bit, and 32-bit .bmp files. Each pixel of nonindexed .bmp files holds a color, in contrast to pixels of indexed .bmp files, which hold an index to a color table. + +## Drawing and Manipulating Shapes and Images + After it is created, a object may be used to draw lines and shapes, render text, or display and manipulate images. The principal objects that are used with the object are: + +- The class—Used for drawing lines, outlining shapes, or rendering other geometric representations. + +- The class—Used for filling areas of graphics, such as filled shapes, images, or text. + +- The class—Provides a description of what shapes to use when rendering text. + +- The structure—Represents the different colors to display. + +#### To use the Graphics object you have created + +- Work with the appropriate object listed above to draw what you need. + + For more information, see the following topics: + + |To render|See| + |---------------|---------| + |Lines|[How to: Draw a Line on a Windows Form](how-to-draw-a-line-on-a-windows-form.md)| + |Shapes|[How to: Draw an Outlined Shape](how-to-draw-an-outlined-shape.md)| + |Text|[How to: Draw Text on a Windows Form](how-to-draw-text-on-a-windows-form.md)| + |Images|[How to: Render Images with GDI+](how-to-render-images-with-gdi.md)| + +## See also + +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Render Images with GDI+](how-to-render-images-with-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-mdi-child-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-mdi-child-forms.md new file mode 100644 index 0000000000..959174dd07 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-mdi-child-forms.md @@ -0,0 +1,108 @@ +--- +title: "How to: Create MDI Child Forms" +description: Learn how to use Visual Studio to create a Multiple-Document Interface (MDI) child form that displays a RichTextBox control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "MDI [Windows Forms], creating forms" + - "child forms" +ms.assetid: 164b69bb-2eca-4339-ada3-0679eb2c6dda +--- +# How to: Create MDI child forms + +MDI child forms are an essential element of [Multiple-Document Interface (MDI) applications](multiple-document-interface-mdi-applications.md), as these forms are the center of user interaction. + +In the following procedure, you'll use Visual Studio to create an MDI child form that displays a control, similar to most word-processing applications. By substituting the control with other controls, such as the control, or a mixture of controls, you can create MDI child windows (and, by extension, MDI applications) with diverse possibilities. + +## Create MDI child forms + +1. Create a new Windows Forms application project in Visual Studio. In the **Properties** window for the form, set its property to `true` and its `WindowsState` property to `Maximized`. + + This designates the form as an MDI container for child windows. + +2. From the `Toolbox`, drag a control to the form. Set its `Text` property to **File**. + +3. Click the ellipsis (…) next to the **Items** property, and click **Add** to add two child tool strip menu items. Set the `Text` property for these items to **New** and **Window**. + +4. In **Solution Explorer**, right-click the project, and then select **Add** > **New Item**. + +5. In the **Add New Item** dialog box, select **Windows Form** (in Visual Basic or in Visual C#) or **Windows Forms Application (.NET)** (in Visual C++) from the **Templates** pane. In the **Name** box, name the form **Form2**. Select **Open** to add the form to the project. + + > [!NOTE] + > The MDI child form you created in this step is a standard Windows Form. As such, it has an property, which enables you to control the transparency of the form. However, the property was designed for top-level windows. Do not use it with MDI child forms, as painting problems can occur. + + This form will be the template for your MDI child forms. + + The **Windows Forms Designer** opens, displaying **Form2**. + +6. From the **Toolbox**, drag a **RichTextBox** control to the form. + +7. In the **Properties** window, set the `Anchor` property to **Top, Left** and the `Dock` property to **Fill**. + + This causes the control to completely fill the area of the MDI child form, even when the form is resized. + +8. Double click the **New** menu item to create a event handler for it. + +9. Insert code similar to the following to create a new MDI child form when the user clicks the **New** menu item. + + > [!NOTE] + > In the following example, the event handler handles the event for `MenuItem2`. Be aware that, depending on the specifics of your application architecture, your **New** menu item may not be `MenuItem2`. + + ```vb + Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click + Dim NewMDIChild As New Form2() + 'Set the Parent Form of the Child window. + NewMDIChild.MdiParent = Me + 'Display the new form. + NewMDIChild.Show() + End Sub + ``` + + ```csharp + protected void MDIChildNew_Click(object sender, System.EventArgs e){ + Form2 newMDIChild = new Form2(); + // Set the Parent Form of the Child window. + newMDIChild.MdiParent = this; + // Display the new form. + newMDIChild.Show(); + } + ``` + + ```cpp + private: + void menuItem2_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + Form2^ newMDIChild = gcnew Form2(); + // Set the Parent Form of the Child window. + newMDIChild->MdiParent = this; + // Display the new form. + newMDIChild->Show(); + } + ``` + + In C++, add the following `#include` directive at the top of Form1.h: + + ```cpp + #include "Form2.h" + ``` + +10. In the drop-down list at the top of the **Properties** window, select the menu strip that corresponds to the **File** menu strip and set the property to the Window . + + This enables the **Window** menu to maintain a list of open MDI child windows with a check mark next to the active child window. + +11. Press **F5** to run the application. By selecting **New** from the **File** menu, you can create new MDI child forms, which are kept track of in the **Window** menu item. + + > [!NOTE] + > When an MDI child form has a component (with, usually, a menu structure of menu items) and it is opened within an MDI parent form that has a component (with, usually, a menu structure of menu items), the menu items will merge automatically if you have set the property (and optionally, the property). Set the property of both components and all of the menu items of the child form to . Additionally, set the property so that the menu items from both menus appear in the desired order. Moreover, keep in mind that when you close an MDI parent form, each of the MDI child forms raises a event before the event for the MDI parent is raised. Canceling an MDI child's event will not prevent the MDI parent's event from being raised; however, the argument for the MDI parent's event will now be set to `true`. You can force the MDI parent and all MDI child forms to close by setting the argument to `false`. + +## See also + +- [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md) +- [How to: Create MDI Parent Forms](how-to-create-mdi-parent-forms.md) +- [How to: Determine the Active MDI Child](how-to-determine-the-active-mdi-child.md) +- [How to: Send Data to the Active MDI Child](how-to-send-data-to-the-active-mdi-child.md) +- [How to: Arrange MDI Child Forms](how-to-arrange-mdi-child-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-mdi-parent-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-mdi-parent-forms.md new file mode 100644 index 0000000000..c8f85c6a6b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-mdi-parent-forms.md @@ -0,0 +1,40 @@ +--- +title: "How to: Create MDI Parent Forms" +description: Learn how to create an MDI parent form programmatically and by using the Windows Forms Designer. +ms.date: "03/30/2017" +helpviewer_keywords: + - "parent forms" + - "MDI [Windows Forms], creating forms" +ms.assetid: 12c71221-2377-4bb6-b10b-7b4b300fd462 +--- +# How to: Create MDI Parent Forms + +> [!IMPORTANT] +> This topic uses the control, which has been replaced by the control. The control is retained for both backward compatibility and future use, if you choose. For information about creating a MDI parent Form by using a , see [How to: Create an MDI Window List with MenuStrip](../controls/how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md). + +The foundation of a Multiple-Document Interface (MDI) application is the MDI parent form. This is the form that contains the MDI child windows, which are the sub-windows wherein the user interacts with the MDI application. Creating an MDI parent form is easy, both in the Windows Forms Designer and programmatically. + +## Create an MDI parent form at design time + +1. Create a Windows Application project in Visual Studio. + +2. In the **Properties** window, set the property to **true**. + + This designates the form as an MDI container for child windows. + + > [!NOTE] + > While setting properties in the **Properties** window, you can also set the `WindowState` property to **Maximized**, if you like, as it is easiest to manipulate MDI child windows when the parent form is maximized. Additionally, be aware that the edge of the MDI parent form will pick up the system color (set in the Windows System Control Panel), rather than the back color you set using the property. + +3. From the **Toolbox**, drag a **MenuStrip** control to the form. Create a top-level menu item with the **Text** property set to **&File** with submenu items called **&New** and **&Close**. Also create a top-level menu item called **&Window**. + + The first menu will create and hide menu items at run time, and the second menu will keep track of the open MDI child windows. At this point, you have created an MDI parent window. + +4. Press **F5** to run the application. For information about creating MDI child windows that operate within the MDI parent form, see [How to: Create MDI Child Forms](how-to-create-mdi-child-forms.md). + +## See also + +- [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md) +- [How to: Create MDI Child Forms](how-to-create-mdi-child-forms.md) +- [How to: Determine the Active MDI Child](how-to-determine-the-active-mdi-child.md) +- [How to: Send Data to the Active MDI Child](how-to-send-data-to-the-active-mdi-child.md) +- [How to: Arrange MDI Child Forms](how-to-arrange-mdi-child-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-standard-windows-forms-print-jobs.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-standard-windows-forms-print-jobs.md new file mode 100644 index 0000000000..1acc46bce6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-standard-windows-forms-print-jobs.md @@ -0,0 +1,76 @@ +--- +title: Create Standard Print Jobs +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "printing [Windows Forms]" + - "printing [Windows Forms], creating print jobs" + - "printing [Visual Basic], in Windows applications" +ms.assetid: 03342b90-9cfe-40b2-838b-b479a13c5dea +--- +# How to: Create Standard Windows Forms Print Jobs +The foundation of printing in Windows Forms is the component—more specifically, the event. By writing code to handle the event, you can specify what to print and how to print it. + +### To create a print job + +1. Add a component to your form. + +2. Write code to handle the event. + + You will have to code your own printing logic. Additionally, you will have to specify the material to be printed. + + In the following code example, a sample graphic in the shape of a red rectangle is created in the event handler to act as material to be printed. + + ```vb + Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage + e.Graphics.FillRectangle(Brushes.Red, New Rectangle(500, 500, 500, 500)) + End Sub + ``` + + ```csharp + private void printDocument1_PrintPage(object sender, + System.Drawing.Printing.PrintPageEventArgs e) + { + e.Graphics.FillRectangle(Brushes.Red, + new Rectangle(500, 500, 500, 500)); + } + ``` + + ```cpp + private: + void printDocument1_PrintPage(System::Object ^ sender, + System::Drawing::Printing::PrintPageEventArgs ^ e) + { + e->Graphics->FillRectangle(Brushes::Red, + Rectangle(500, 500, 500, 500)); + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.printDocument1.PrintPage += new + System.Drawing.Printing.PrintPageEventHandler + (this.printDocument1_PrintPage); + ``` + + ```cpp + printDocument1->PrintPage += gcnew + System::Drawing::Printing::PrintPageEventHandler + (this, &Form1::printDocument1_PrintPage); + ``` + + You may also want to write code for the and events, perhaps including an integer representing the total number of pages to print that is decremented as each page prints. + + > [!NOTE] + > You can add a component to your form to provide a clean and efficient user interface (UI) to your users. Setting the property of the component enables you to set properties related to the print document you are working with on your form. For more information about the component, see [PrintDialog Component](../controls/printdialog-component-windows-forms.md). + + For more information about the specifics of Windows Forms print jobs, including how to create a print job programmatically, see . + +## See also + +- +- [Windows Forms Print Support](windows-forms-print-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-thumbnail-images.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-thumbnail-images.md new file mode 100644 index 0000000000..4ea20e7ed7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-thumbnail-images.md @@ -0,0 +1,50 @@ +--- +title: "How to: Create Thumbnail Images" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "thumbnail images [Windows Forms], creating" + - "images [Windows Forms], creating thumbnails" +ms.assetid: e956242a-1e5b-4217-a3cf-5f3fb45d00ba +--- +# How to: Create Thumbnail Images +A thumbnail image is a small version of an image. You can create a thumbnail image by calling the method of an object. + +## Example + The following example constructs an object from a JPG file. The original image has a width of 640 pixels and a height of 479 pixels. The code creates a thumbnail image that has a width of 100 pixels and a height of 100 pixels. + + The following illustration shows the thumbnail image: + + ![Screenshot that shows the output thumbnail.](./media/how-to-create-thumbnail-images/construct-thumbnail-image.png) + +> [!NOTE] +> In this example, a callback method is declared, but never used. This supports all versions of GDI+. + + [!code-csharp[System.Drawing.WorkingWithImages#71](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#71)] + [!code-vb[System.Drawing.WorkingWithImages#71](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#71)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. To run the example, follow these steps: + +1. Create a new Windows Forms application. + +2. Add the example code to the form. + +3. Create a handler for the form's event + +4. In the handler, call the `GetThumbnail` method and pass `e` for . + +5. Find an image file that you want to make a thumbnail of. + +6. In the `GetThumbnail` method, specify the path and file name to your image. + +7. Press F5 to run the example. + + A 100 by 100 thumbnail image appears on the form. + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-vertical-text.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-vertical-text.md new file mode 100644 index 0000000000..45b6022d8e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-create-vertical-text.md @@ -0,0 +1,33 @@ +--- +title: "How to: Create Vertical Text" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "text [Windows Forms], drawing vertical" + - "Windows Forms, drawing vertical text" + - "strings [Windows Forms], drawing vertical" + - "vertical text [Windows Forms], drawing" +ms.assetid: 50c69046-4188-47d9-b949-cc2610ffd337 +--- +# How to: Create Vertical Text +You can use a object to specify that text be drawn vertically rather than horizontally. + +## Example + The following example assigns the value to the property of a object. That object is passed to the method of the class. The value is a member of the enumeration. + + The following illustration shows the vertical text: + + ![Graphic that shows vertical font text.](./media/how-to-create-vertical-text/vertical-font-text-graphic.png) + + [!code-csharp[System.Drawing.FontsAndText#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#31)] + [!code-vb[System.Drawing.FontsAndText#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#31)] + +## Compiling the Code + +- The preceding example is designed for use with Windows Forms, and it requires `e` , which is a parameter of . + +## See also + +- [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-crop-and-scale-images.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-crop-and-scale-images.md new file mode 100644 index 0000000000..d2447a93f0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-crop-and-scale-images.md @@ -0,0 +1,35 @@ +--- +title: "How to: Crop and Scale Images" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "images [Windows Forms], cropping" + - "images [Windows Forms], scaling" +ms.assetid: 053e3360-bca0-4b25-9afa-0e77a6f17b03 +--- +# How to: Crop and Scale Images +The class provides several methods, some of which have source and destination rectangle parameters that you can use to crop and scale images. + +## Example + The following example constructs an object from the disk file Apple.gif. The code draws the entire apple image in its original size. The code then calls the method of a object to draw a portion of the apple image in a destination rectangle that is larger than the original apple image. + + The method determines which portion of the apple to draw by looking at the source rectangle, which is specified by the third, fourth, fifth, and sixth arguments. In this case, the apple is cropped to 75 percent of its width and 75 percent of its height. + + The method determines where to draw the cropped apple and how big to make the cropped apple by looking at the destination rectangle, which is specified by the second argument. In this case, the destination rectangle is 30 percent wider and 30 percent taller than the original image. + + The following illustration shows the original apple and the scaled, cropped apple. + + ![Screenshot of an original image and the same image cropped.](./media/how-to-crop-and-scale-images/original-image-cropped-image.png) + + [!code-csharp[System.Drawing.WorkingWithImages#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#11)] + [!code-vb[System.Drawing.WorkingWithImages#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Make sure to replace `Apple.gif` with an image file name and path that are valid on your system. + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-determine-the-active-mdi-child.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-determine-the-active-mdi-child.md new file mode 100644 index 0000000000..6298f38f31 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-determine-the-active-mdi-child.md @@ -0,0 +1,86 @@ +--- +title: "How to: Determine the Active MDI Child" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Clipboard [Windows Forms], copying data to" + - "MDI [Windows Forms], child windows" + - "child forms" + - "MDI [Windows Forms], activating forms" + - "MDI [Windows Forms], locating focus" +ms.assetid: 33880ec3-0207-4c2b-a616-ff140443cc0f +--- +# How to: Determine the Active MDI Child +On occasion, you will want to provide a command that operates on the control that has focus on the currently active child form. For example, suppose you want to copy selected text from the child form's text box to the Clipboard. You would create a procedure that copies selected text to the Clipboard using the event of the Copy menu item on the standard Edit menu. + + Because an MDI application can have many instances of the same child form, the procedure needs to know which form to use. To specify the correct form, use the property, which returns the child form that has the focus or that was most recently active. + + When you have several controls on a form, you also need to specify which control is active. Like the property, the property returns the control with the focus on the active child form. The procedure below illustrates a copy procedure that can be called from a child form menu, a menu on the MDI form, or a toolbar button. + +### To determine the active MDI child (to copy its text to the Clipboard) + +1. Within a method, copy the text of the active control of the active child form to the Clipboard. + + > [!NOTE] + > This example assumes there is an MDI parent form (`Form1`) that has one or more MDI child windows containing a control. For more information, see [Creating MDI Parent Forms](how-to-create-mdi-parent-forms.md). + + ```vb + Public Sub mniCopy_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles mniCopy.Click + + ' Determine the active child form. + Dim activeChild As Form = Me.ActiveMDIChild + + ' If there is an active child form, find the active control, which + ' in this example should be a RichTextBox. + If (Not activeChild Is Nothing) Then + Dim theBox As RichTextBox = _ + TryCast(activeChild.ActiveControl, RichTextBox) + + If (Not theBox Is Nothing) Then + 'Put selected text on Clipboard. + Clipboard.SetDataObject(theBox.SelectedText) + Else + MessageBox.Show("You need to select a RichTextBox.") + End If + End If + End Sub + ``` + + ```csharp + protected void mniCopy_Click (object sender, System.EventArgs e) + { + // Determine the active child form. + Form activeChild = this.ActiveMdiChild; + + // If there is an active child form, find the active control, which + // in this example should be a RichTextBox. + if (activeChild != null) + { + try + { + RichTextBox theBox = (RichTextBox)activeChild.ActiveControl; + if (theBox != null) + { + // Put the selected text on the Clipboard. + Clipboard.SetDataObject(theBox.SelectedText); + + } + } + catch + { + MessageBox.Show("You need to select a RichTextBox."); + } + } + } + ``` + +## See also + +- [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md) +- [How to: Create MDI Parent Forms](how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](how-to-create-mdi-child-forms.md) +- [How to: Send Data to the Active MDI Child](how-to-send-data-to-the-active-mdi-child.md) +- [How to: Arrange MDI Child Forms](how-to-arrange-mdi-child-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-determine-the-parameters-supported-by-an-encoder.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-determine-the-parameters-supported-by-an-encoder.md new file mode 100644 index 0000000000..9e2b1e4837 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-determine-the-parameters-supported-by-an-encoder.md @@ -0,0 +1,31 @@ +--- +title: "How to: Determine the Parameters Supported by an Encoder" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "encoder parameters [Windows Forms], determining supported" +ms.assetid: f47ae459-e3ce-4d41-a140-2f6c6aea3f44 +--- +# How to: Determine the Parameters Supported by an Encoder +You can adjust image parameters, such as quality and compression level, but you must know which parameters are supported by a given image encoder. The class provides the method so that you can determine which image parameters are supported for a particular encoder. You specify the encoder with a GUID. The method returns an array of objects. + +## Example + The following example code outputs the supported parameters for the JPEG encoder. Use the list of parameter categories and associated GUIDs in the class overview to determine the category for each parameter. + + [!code-csharp[UsingImageEncodersDecoders#3](~/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs#3)] + [!code-vb[UsingImageEncodersDecoders#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb#3)] + +## Compiling the Code + This example requires: + +- A Windows Forms application. + +- A , which is a parameter of . + +## See also + +- [How to: List Installed Encoders](how-to-list-installed-encoders.md) +- [Types of Bitmaps](types-of-bitmaps.md) +- [Using Image Encoders and Decoders in Managed GDI+](using-image-encoders-and-decoders-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-display-pop-up-help.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-display-pop-up-help.md new file mode 100644 index 0000000000..41ddfb165d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-display-pop-up-help.md @@ -0,0 +1,41 @@ +--- +title: "How to: Display Pop-up Help" +ms.date: "03/30/2017" +helpviewer_keywords: + - "pop-up Help" + - "Help [Windows Forms], pop-up Help" + - "Windows Forms, displaying Help" + - "forms [Windows Forms], displaying Help" + - "modal dialog boxes [Windows Forms], pop-up Help" + - "F1 Help [Windows Forms], in dialog boxes" + - "HelpProvider component [Windows Forms]" + - "Help [Windows Forms], adding to dialog boxes" +ms.assetid: 218aa81e-e87e-4d67-af05-11627bbdce3b +--- +# How to: Display pop-up Help + +One way to display Help on Windows Forms is through the **Help** button, located on the right side of the title bar, accessible through the property. This type of Help display is well-suited for use with dialog boxes. Dialog boxes shown modally (with the method) have trouble bringing up external Help systems, because modal dialog boxes need to be closed before focus can shift to another window. Additionally, using the **Help** button requires that there is no **Minimize** button or **Maximize** button shown in the title bar. This is a standard dialog-box convention, whereas forms usually have **Minimize** and **Maximize** buttons. + +You can also use the component to link controls to files in a Help system, even if you have implemented pop-up Help. For more information, see [Providing Help in a Windows Application](how-to-provide-help-in-a-windows-application.md). + +## Display pop-up Help + +1. In Visual Studio, drag a [HelpProvider](../controls/helpprovider-component-windows-forms.md) component from the Toolbox to your form. + + It will sit in the tray at the bottom of the Windows Forms Designer. + +2. In the Properties window, set the property to `true`. This will display a button with a question mark in it on the right side of the title bar of the form. + +3. In order for the to display, the form's and properties must be set to `false`, the property set to `true`, and the property to one of the following values: , , or . + +4. Select the control for which you want to show help on your form and set the Help string in the Properties window. This is the string of text that will be displayed in a window similar to a [ToolTip](../controls/tooltip-component-windows-forms.md). + +5. Press **F5**. + +6. Press the **Help** button on the title bar and click the control on which you set the Help string. + +## See also + +- [Control Help Using ToolTips](control-help-using-tooltips.md) +- [Integrating User Help in Windows Forms](integrating-user-help-in-windows-forms.md) +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-custom-dashed-line.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-custom-dashed-line.md new file mode 100644 index 0000000000..bb59b5bce9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-custom-dashed-line.md @@ -0,0 +1,31 @@ +--- +title: "How to: Draw a Custom Dashed Line" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "lines [Windows Forms], custom" + - "lines [Windows Forms], drawing" + - "lines [Windows Forms], dashed" +ms.assetid: cd0ed96a-cce4-47b9-b58a-3bae2e3d1bee +--- +# How to: Draw a Custom Dashed Line +GDI+ provides several dash styles that are listed in the enumeration. If those standard dash styles do not suit your needs, you can create a custom dash pattern. + +## Example + To draw a custom dashed line, put the lengths of the dashes and spaces in an array and assign the array as the value of the property of a object. The following example draws a custom dashed line based on the array `{5, 2, 15, 4}`. If you multiply the elements of the array by the pen width of 5, you get `{25, 10, 75, 20}`. The displayed dashes alternate in length between 25 and 75, and the spaces alternate in length between 10 and 20. + + The following illustration shows the resulting dashed line. Note that the final dash has to be shorter than 25 units so that the line can end at (405, 5). + + ![Illustration that shows a dashed line.](./media/how-to-draw-a-custom-dashed-line/dashed-line-illustration.gif "pens6") + + [!code-csharp[System.Drawing.UsingAPen#51](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#51)] + [!code-vb[System.Drawing.UsingAPen#51](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#51)] + +## Compiling the Code + Create a Windows Form and handle the form's event. Paste the preceding code into the event handler. + +## See also + +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-filled-ellipse-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-filled-ellipse-on-a-windows-form.md new file mode 100644 index 0000000000..087cc574e2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-filled-ellipse-on-a-windows-form.md @@ -0,0 +1,38 @@ +--- +title: "How to: Draw a Filled Ellipse on a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "Graphics.FillEllipse" +helpviewer_keywords: + - "ellipses [Windows Forms], drawing" + - "circles [Windows Forms], drawing" + - "circular shapes" + - "drawing [Windows Forms], ellipses" + - "shapes [Windows Forms], drawing" + - "forms [Windows Forms], drawing ellipses" +ms.assetid: 781db806-950d-4c5b-b022-493f7fd0c4a8 +--- +# How to: Draw a Filled Ellipse on a Windows Form +This example draws a filled ellipse on a form. + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#1)] + [!code-csharp[System.Drawing.ConceptualHowTos#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#1)] + [!code-vb[System.Drawing.ConceptualHowTos#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#1)] + +## Compiling the Code + You cannot call this method in the event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the method. + +## Robust Programming + You should always call on any objects that consume system resources, such as and objects. + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Alpha Blending Lines and Fills](alpha-blending-lines-and-fills.md) +- [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-filled-rectangle-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-filled-rectangle-on-a-windows-form.md new file mode 100644 index 0000000000..fddf5dd9c4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-filled-rectangle-on-a-windows-form.md @@ -0,0 +1,38 @@ +--- +title: "How to: Draw a Filled Rectangle on a Windows Form" +description: Learn how to programmatically draw a filled rectangle on a Windows Form. Also learn about compiling your code. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "Graphics.FillRectangle" +helpviewer_keywords: + - "drawing [Windows Forms], rectangles" + - "rectangles [Windows Forms], drawing" + - "drawing rectangles" +ms.assetid: d656a93c-987d-4809-aafd-493fe17450f0 +--- +# How to: Draw a Filled Rectangle on a Windows Form +This example draws a filled rectangle on a form. + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#2](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#2)] + [!code-csharp[System.Drawing.ConceptualHowTos#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#2)] + [!code-vb[System.Drawing.ConceptualHowTos#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#2)] + +## Compiling the Code + You cannot call this method in the event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the method. + +## Robust Programming + You should always call on any objects that consume system resources, such as and objects. + +## See also + +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Brushes and Filled Shapes in GDI+](brushes-and-filled-shapes-in-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-filled-with-a-texture.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-filled-with-a-texture.md new file mode 100644 index 0000000000..d25dadd49d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-filled-with-a-texture.md @@ -0,0 +1,32 @@ +--- +title: "How to: Draw a Line Filled with a Texture" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "drawing [Windows Forms], lines" + - "lines [Windows Forms], texture" + - "drawing lines [Windows Forms], texture" +ms.assetid: dc9118cc-f3c2-42e5-8173-f46d41d18fd5 +--- +# How to: Draw a Line Filled with a Texture +Instead of drawing a line with a solid color, you can draw a line with a texture. To draw lines and curves with a texture, create a object, and pass that object to a constructor. The bitmap associated with the texture brush is used to tile the plane (invisibly), and when the pen draws a line or curve, the stroke of the pen uncovers certain pixels of the tiled texture. + +## Example + The following example creates a object from the file `Texture1.jpg`. That bitmap is used to construct a object, and the object is used to construct a object. The call to draws the bitmap with its upper-left corner at (0, 0). The call to uses the object to draw a textured ellipse. + + The following illustration shows the bitmap and the textured ellipse: + + ![Screenshot that shows the bitmap and the textured ellipse.](./media/how-to-draw-a-line-filled-with-a-texture/bitmap-textured-ellipse.png) + + [!code-csharp[System.Drawing.UsingAPen#61](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#61)] + [!code-vb[System.Drawing.UsingAPen#61](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#61)] + +## Compiling the Code + Create a Windows Form and handle the form's event. Paste the preceding code into the event handler. Replace `Texture.jpg` with an image valid on your system. + +## See also + +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-on-a-windows-form.md new file mode 100644 index 0000000000..2b341ff82b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-on-a-windows-form.md @@ -0,0 +1,36 @@ +--- +title: "How to: Draw a Line on a Windows Form" +description: Learn how to draws a line on a form by handling the Paint event, and then perform the drawing using the Graphics property of the PaintEventArgs. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "Graphics.DrawLine" +helpviewer_keywords: + - "examples [Windows Forms], drawing lines on forms" + - "drawing [Windows Forms], lines" + - "lines [Windows Forms], drawing" + - "drawing lines" +ms.assetid: 55c1dbeb-75d0-430c-9814-a24b8971ad8c +--- +# How to: Draw a Line on a Windows Form +This example draws a line on a form. Typically, when you draw on a form, you handle the form’s event and perform the drawing using the property of the , as shown in this example + +## Example + [!code-csharp[System.Drawing.UsingAPen#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#11)] + [!code-vb[System.Drawing.UsingAPen#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## Robust Programming + You should always call on any objects that consume system resources, such as objects. + +## See also + +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-with-line-caps.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-with-line-caps.md new file mode 100644 index 0000000000..f689904edb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-line-with-line-caps.md @@ -0,0 +1,36 @@ +--- +title: "How to: Draw a Line with Line Caps" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "drawing [Windows Forms], lines" + - "lines [Windows Forms], drawing" + - "pens [Windows Forms], drawing lines" + - "drawing lines [Windows Forms], line caps" +ms.assetid: eb68c3e1-c400-4886-8a04-76978a429cb6 +--- +# How to: Draw a Line with Line Caps +You can draw the start or end of a line in one of several shapes called line caps. GDI+ supports several line caps, such as round, square, diamond, and arrowhead. + +## Example + You can specify line caps for the start of a line (start cap), the end of a line (end cap), or the dashes of a dashed line (dash cap). + + The following example draws a line with an arrowhead at one end and a round cap at the other end. The illustration shows the resulting line: + + ![Illustration that shows a line with a round cap.](./media/how-to-draw-a-line-with-line-caps/line-cap-arrowhead-example.gif) + + [!code-csharp[System.Drawing.UsingAPen#71](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#71)] + [!code-vb[System.Drawing.UsingAPen#71](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#71)] + +## Compiling the Code + +- Create a Windows Form and handle the form's event. Paste the example code into the event handler passing `e` as . + +## See also + +- +- +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-sequence-of-bezier-splines.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-sequence-of-bezier-splines.md new file mode 100644 index 0000000000..a68ea17ee4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-sequence-of-bezier-splines.md @@ -0,0 +1,32 @@ +--- +title: "How to: Draw a Sequence of Bézier Splines" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "splines [Windows Forms], drawing Bezier" + - "Bezier splines [Windows Forms], drawing sequence of" +ms.assetid: 37a0bedb-20c2-4cf0-91fa-a5509e826b30 +--- +# How to: Draw a Sequence of Bézier Splines +You can use the method of the class to draw a sequence of connected Bézier splines. + +## Example + The following example draws a curve that consists of two connected Bézier splines. The endpoint of the first Bézier spline is the start point of the second Bézier spline. + + The following illustration shows the connected splines along with the seven points: + + ![Graphic that shows the connected splines along with seven points.](./media/how-to-draw-a-sequence-of-bezier-splines/bezier-spline-seven-points.png) + + [!code-csharp[System.Drawing.ConstructingDrawingCurves#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs#11)] + [!code-vb[System.Drawing.ConstructingDrawingCurves#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Bézier Splines in GDI+](bezier-splines-in-gdi.md) +- [Constructing and Drawing Curves](constructing-and-drawing-curves.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-single-bezier-spline.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-single-bezier-spline.md new file mode 100644 index 0000000000..78eb44196e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-a-single-bezier-spline.md @@ -0,0 +1,32 @@ +--- +title: "How to: Draw a Single Bézier Spline" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Bezier splines [Windows Forms], drawing" + - "drawing [Windows Forms], Bezier splines" +ms.assetid: f4f3fe30-f0a6-4743-ac91-11310cebea9f +--- +# How to: Draw a Single Bézier Spline +A Bézier spline is defined by four points: a start point, two control points, and an endpoint. + +## Example + The following example draws a Bézier spline with start point (10, 100) and endpoint (200, 100). The control points are (100, 10) and (150, 150). + + The following illustration shows the resulting Bézier spline along with its start point, control points, and endpoint. The illustration also shows the spline's convex hull, which is a polygon formed by connecting the four points with straight lines. + + ![Illustration of a Bezier Spline.](./media/how-to-draw-a-single-bezier-spline/bezier-spline-illustration.png) + + [!code-csharp[System.Drawing.ConstructingDrawingCurves#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs#31)] + [!code-vb[System.Drawing.ConstructingDrawingCurves#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb#31)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- +- [Bézier Splines in GDI+](bezier-splines-in-gdi.md) +- [How to: Draw a Sequence of Bézier Splines](how-to-draw-a-sequence-of-bezier-splines.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-an-existing-bitmap-to-the-screen.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-an-existing-bitmap-to-the-screen.md new file mode 100644 index 0000000000..daf76693f8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-an-existing-bitmap-to-the-screen.md @@ -0,0 +1,32 @@ +--- +title: "How to: Draw an Existing Bitmap to the Screen" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "bitmaps [Windows Forms], displaying in Windows Forms" + - "bitmaps [Windows Forms], loading in Windows Forms applications" + - "images [Windows Forms], displaying on Windows Forms" +ms.assetid: 5bc558d7-b326-4050-a834-b8600da0de95 +--- +# How to: Draw an Existing Bitmap to the Screen +You can easily draw an existing image on the screen. First you need to create a object by using the bitmap constructor that takes a file name, . This constructor accepts images with several different file formats, including BMP, GIF, JPEG, PNG, and TIFF. After you have created the object, pass that object to the method of a object. + +## Example + This example creates a object from a JPEG file and then draws the bitmap with its upper-left corner at (60, 10). + + The following illustration shows the bitmap drawn at the specified location: + + ![Screenshot that shows an image at a specified position.](./media/how-to-draw-an-existing-bitmap-to-the-screen/bitmap-specified-position.png) + + [!code-csharp[System.Drawing.WorkingWithImages#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#21)] + [!code-vb[System.Drawing.WorkingWithImages#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#21)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-an-outlined-shape.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-an-outlined-shape.md new file mode 100644 index 0000000000..a5e0f12d1b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-an-outlined-shape.md @@ -0,0 +1,44 @@ +--- +title: "How to: Draw an Outlined Shape" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "Graphics.DrawEllipse" +helpviewer_keywords: + - "ellipses [Windows Forms], drawing" + - "circles [Windows Forms], drawing" + - "drawing [Windows Forms], shapes" + - "circular shapes" + - "forms [Windows Forms], drawing circular shapes" + - "circles" + - "outlined shapes [Windows Forms], examples" + - "outlined shapes [Windows Forms], drawing" + - "drawing [Windows Forms], circular shapes" + - "shapes [Windows Forms], drawing" +ms.assetid: f4f9214c-607e-407d-8cdd-6549f0278451 +--- +# How to: Draw an Outlined Shape +This example draws outlined ellipses and rectangles on a form. + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#6](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#6)] + [!code-csharp[System.Drawing.ConceptualHowTos#6](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#6)] + [!code-vb[System.Drawing.ConceptualHowTos#6](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#6)] + +## Compiling the Code + You cannot call this method in the event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the method. + +## Robust Programming + You should always call on any objects that consume system resources, such as and objects. + +## See also + +- +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-cardinal-splines.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-cardinal-splines.md new file mode 100644 index 0000000000..2c3c405f7f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-cardinal-splines.md @@ -0,0 +1,49 @@ +--- +title: "How to: Draw Cardinal Splines" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "cardinal splines [Windows Forms], drawing" + - "drawing [Windows Forms], cardinal splines" + - "graphics [Windows Forms], cardinal splines" +ms.assetid: a4a41e80-4461-4b47-b6bd-2c5e68881994 +--- +# How to: Draw Cardinal Splines +A cardinal spline is a curve that passes smoothly through a given set of points. To draw a cardinal spline, create a object and pass the address of an array of points to the method. + +### Drawing a Bell-Shaped Cardinal Spline + +- The following example draws a bell-shaped cardinal spline that passes through five designated points. The following illustration shows the curve and five points. + + ![Diagram that shows a bell-shaped cardinal spline.](./media/how-to-draw-cardinal-splines/bell-shaped-cardinal-spline.png) + + [!code-csharp[System.Drawing.ConstructingDrawingCurves#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs#21)] + [!code-vb[System.Drawing.ConstructingDrawingCurves#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb#21)] + +### Drawing a Closed Cardinal Spline + +- Use the method of the class to draw a closed cardinal spline. In a closed cardinal spline, the curve continues through the last point in the array and connects with the first point in the array. The following example draws a closed cardinal spline that passes through six designated points. The following illustration shows the closed spline along with the six points: + + ![Diagram that shows a closed cardinal spline.](./media/how-to-draw-cardinal-splines/closed-cardinal-spine.png) + + [!code-csharp[System.Drawing.ConstructingDrawingCurves#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs#22)] + [!code-vb[System.Drawing.ConstructingDrawingCurves#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb#22)] + +### Changing the Bend of a Cardinal Spline + +- Change the way a cardinal spline bends by passing a tension argument to the method. The following example draws three cardinal splines that pass through the same set of points. The following illustration shows the three splines along with their tension values. Note that when the tension is 0, the points are connected by straight lines. + + ![Diagram that shows three cardinal splines.](./media/how-to-draw-cardinal-splines/three-cardinal-splines.png) + + [!code-csharp[System.Drawing.ConstructingDrawingCurves#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs#23)] + [!code-vb[System.Drawing.ConstructingDrawingCurves#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb#23)] + +## Compiling the Code + The preceding examples are designed for use with Windows Forms, and they require `e`, which is a parameter of the event handler. + +## See also + +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [Constructing and Drawing Curves](constructing-and-drawing-curves.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-opaque-and-semitransparent-lines.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-opaque-and-semitransparent-lines.md new file mode 100644 index 0000000000..9b2cea643c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-opaque-and-semitransparent-lines.md @@ -0,0 +1,36 @@ +--- +title: "How to: Draw Opaque and Semitransparent Lines" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "drawing [Windows Forms], lines" + - "transparency [Windows Forms], lines" + - "lines [Windows Forms], drawing alpha blended" + - "alpha blending [Windows Forms], drawing lines" +ms.assetid: 8f2508af-f495-4223-b5cc-646cbbb520eb +--- +# How to: Draw Opaque and Semitransparent Lines +When you draw a line, you must pass a object to the method of the class. One of the parameters of the constructor is a object. To draw an opaque line, set the alpha component of the color to 255. To draw a semitransparent line, set the alpha component to any value from 1 through 254. + + When you draw a semitransparent line over a background, the color of the line is blended with the colors of the background. The alpha component specifies how the line and background colors are mixed; alpha values near 0 place more weight on the background colors, and alpha values near 255 place more weight on the line color. + +## Example + The following example draws a bitmap and then draws three lines that use the bitmap as a background. The first line uses an alpha component of 255, so it is opaque. The second and third lines use an alpha component of 128, so they are semitransparent; you can see the background image through the lines. The statement that sets the property causes the blending for the third line to be done in conjunction with gamma correction. + + [!code-csharp[System.Drawing.AlphaBlending#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs#11)] + [!code-vb[System.Drawing.AlphaBlending#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb#11)] + + The following illustration shows the output of the following code: + + ![Illustration that shows opaque and semitransparent output](./media/how-to-draw-opaque-and-semitransparent-lines/opaque-semitransparent-lines.png) + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Alpha Blending Lines and Fills](alpha-blending-lines-and-fills.md) +- [How to: Give Your Control a Transparent Background](../controls/how-to-give-your-control-a-transparent-background.md) +- [How to: Draw with Opaque and Semitransparent Brushes](how-to-draw-with-opaque-and-semitransparent-brushes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-at-a-specified-location.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-at-a-specified-location.md new file mode 100644 index 0000000000..0fbee248e8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-at-a-specified-location.md @@ -0,0 +1,47 @@ +--- +title: "How to: Draw Text at a Specified Location" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "text [Windows Forms], drawing at specified locations [Windows Forms]" + - "drawing text" + - "drawing text [Windows Forms], specified locations [Windows Forms]" + - "Windows Forms, drawing text at a specified location" +ms.assetid: 60816423-1c38-465e-980d-2c2b64d74086 +--- +# How to: Draw Text at a Specified Location +When you perform custom drawing, you can draw text in a single horizontal line starting at a specified point. You can draw text in this manner by using the overloaded method of the class that takes a or parameter. The method also requires a and + + You can also use the overloaded method of the that takes a . also requires a and a . + + The following illustration shows the output of text drawn at a specified point when you use the overloaded method. + + ![Screenshot that shows the output of text at a specified point.](./media/how-to-draw-text-at-a-specified-location/font-text-specified-point.png) + +### To draw a line of text with GDI+ + +1. Use the method, passing the text you want, or , , and . + + [!code-csharp[System.Drawing.AlignDrawnText#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs#30)] + [!code-vb[System.Drawing.AlignDrawnText#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb#30)] + +### To draw a line of text with GDI + +1. Use the method, passing the text you want, , , and . + + [!code-csharp[System.Drawing.AlignDrawnText#40](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs#40)] + [!code-vb[System.Drawing.AlignDrawnText#40](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb#40)] + +## Compiling the Code + The previous examples require: + +- `e`, which is a parameter of . + +## See also + +- [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) +- [Using Fonts and Text](using-fonts-and-text.md) +- [How to: Construct Font Families and Fonts](how-to-construct-font-families-and-fonts.md) +- [How to: Draw Wrapped Text in a Rectangle](how-to-draw-wrapped-text-in-a-rectangle.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-on-a-windows-form.md new file mode 100644 index 0000000000..0e62b991d0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-on-a-windows-form.md @@ -0,0 +1,38 @@ +--- +title: "How to: Draw Text on a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "forms [Windows Forms], drawing text" + - "text [Windows Forms], drawing" +ms.assetid: 5d2447a9-21a1-4adc-b954-5516f2bb9b2c +--- +# How to: Draw Text on a Windows Form +The following code example shows how to use the method of the to draw text on a form. Alternatively, you can use for drawing text on a form. For more information, see [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md). + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#7](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#7)] + [!code-csharp[System.Drawing.ConceptualHowTos#7](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#7)] + [!code-vb[System.Drawing.ConceptualHowTos#7](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#7)] + +## Compiling the Code + You cannot call the method in the event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the method. + +## Robust Programming + The following conditions may cause an exception: + +- The Arial font is not installed. + +## See also + +- +- +- +- +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-with-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-with-gdi.md new file mode 100644 index 0000000000..2abfdb50bb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-text-with-gdi.md @@ -0,0 +1,38 @@ +--- +title: "How to: Draw Text with GDI" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "GDI [Windows Forms], drawing text [Windows Forms]" + - "text [Windows Forms], drawing with TextRenderer" + - "drawing [Windows Forms], text" + - "Windows Forms, drawing text with GDI" +ms.assetid: 2a19fe5d-2ace-451c-94db-01cb1118ef7b +--- +# How to: Draw Text with GDI +With the method in the class, you can access GDI functionality for drawing text on a form or control. GDI text rendering typically offers better performance and more accurate text measuring than GDI+. + +> [!NOTE] +> The methods of the class are not supported for printing. When printing, always use the methods of the class. + +## Example + The following code example demonstrates how to draw text on multiple lines within a rectangle using the method. + + [!code-csharp[System.Windows.Forms.TextRendererExamples#7](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/CS/Form1.cs#7)] + [!code-vb[System.Windows.Forms.TextRendererExamples#7](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/VB/Form1.vb#7)] + + To render text with the class, you need an , such as a and a , a location to draw the text, and the color in which it should be drawn. Optionally, you can specify the text formatting by using the enumeration. + + For more information about obtaining a , see [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md). For more information about constructing a , see [How to: Construct Font Families and Fonts](how-to-construct-font-families-and-fonts.md). + +## Compiling the Code + The preceding code example is designed for use with Windows Forms, and it requires the `e`, which is a parameter of . + +## See also + +- +- +- +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-vertical-text-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-vertical-text-on-a-windows-form.md new file mode 100644 index 0000000000..1104c1c7e5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-vertical-text-on-a-windows-form.md @@ -0,0 +1,41 @@ +--- +title: "How to: Draw Vertical Text on a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "StringFormat.FormatFlags" + - "Graphics.DrawString" +helpviewer_keywords: + - "text [Windows Forms], drawing vertical" + - "strings [Windows Forms], drawing vertical" + - "text [Windows Forms], drawing" + - "text [Windows Forms], vertical text" +ms.assetid: 717a6131-00f6-4373-b574-9894e8317799 +--- +# How to: Draw Vertical Text on a Windows Form +The following code example shows how to draw vertical text on a form by using the method of . + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#8](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#8)] + [!code-csharp[System.Drawing.ConceptualHowTos#8](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#8)] + [!code-vb[System.Drawing.ConceptualHowTos#8](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#8)] + +## Compiling the Code + You cannot call this method in the event handler. The drawn content will not be redrawn if the form is resized or obscured by another form. To make your content automatically repaint, you should override the method. + +## Robust Programming + The following conditions may cause an exception: + +- The Arial font is not installed. + +## See also + +- +- +- +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-with-opaque-and-semitransparent-brushes.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-with-opaque-and-semitransparent-brushes.md new file mode 100644 index 0000000000..e1d8e7dcc2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-with-opaque-and-semitransparent-brushes.md @@ -0,0 +1,37 @@ +--- +title: "How to: Draw with Opaque and Semitransparent Brushes" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "semi-transparent shapes [Windows Forms], drawing" + - "transparency [Windows Forms], semi-transparent shapes" + - "alpha blending [Windows Forms], brush" + - "brushes [Windows Forms], using semi-transparent" +ms.assetid: a4f6f6b8-3bc8-440a-84af-d62ef0f8ff40 +--- +# How to: Draw with Opaque and Semitransparent Brushes +When you fill a shape, you must pass a object to one of the fill methods of the class. The one parameter of the constructor is a object. To fill an opaque shape, set the alpha component of the color to 255. To fill a semitransparent shape, set the alpha component to any value from 1 through 254. + + When you fill a semitransparent shape, the color of the shape is blended with the colors of the background. The alpha component specifies how the shape and background colors are mixed; alpha values near 0 place more weight on the background colors, and alpha values near 255 place more weight on the shape color. + +## Example + The following example draws a bitmap and then fills three ellipses that overlap the bitmap. The first ellipse uses an alpha component of 255, so it is opaque. The second and third ellipses use an alpha component of 128, so they are semitransparent; you can see the background image through the ellipses. The call that sets the property causes the blending for the third ellipse to be done in conjunction with gamma correction. + + [!code-csharp[System.Drawing.AlphaBlending#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs#31)] + [!code-vb[System.Drawing.AlphaBlending#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb#31)] + + The following illustration shows the output of the following code: + + ![Illustration that shows opaque and semitransparent output.](./media/how-to-draw-with-opaque-and-semitransparent-brushes/compositingquality-ellipse-semitransparent.png) + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Alpha Blending Lines and Fills](alpha-blending-lines-and-fills.md) +- [How to: Give Your Control a Transparent Background](../controls/how-to-give-your-control-a-transparent-background.md) +- [How to: Draw Opaque and Semitransparent Lines](how-to-draw-opaque-and-semitransparent-lines.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-wrapped-text-in-a-rectangle.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-wrapped-text-in-a-rectangle.md new file mode 100644 index 0000000000..63497ebbdb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-draw-wrapped-text-in-a-rectangle.md @@ -0,0 +1,46 @@ +--- +title: "How to: Draw Wrapped Text in a Rectangle" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, drawing text in a rectangle" + - "text [Windows Forms], drawing in a rectangle" + - "strings [Windows Forms], drawing in a rectangle" +ms.assetid: e1fb432a-dc90-48b5-9b6b-acc14507133d +--- +# How to: Draw Wrapped Text in a Rectangle +You can draw wrapped text in a rectangle by using the overloaded method of the class that takes a or parameter. You will also use a and a . + + You can also draw wrapped text in a rectangle by using the overloaded method of the that takes a and a parameter. You will also use a and a . + + The following illustration shows the output of text drawn in the rectangle when you use the method: + + ![Screenshot that shows the output when using DrawString method.](./media/how-to-draw-wrapped-text-in-a-rectangle/drawstring-method-font-text.png) + +### To draw wrapped text in a rectangle with GDI+ + +1. Use the overloaded method, passing the text you want, or , and . + + [!code-csharp[System.Drawing.AlignDrawnText#50](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs#50)] + [!code-vb[System.Drawing.AlignDrawnText#50](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb#50)] + +### To draw wrapped text in a rectangle with GDI + +1. Use the enumeration value to specify the text should be wrapped with the overloaded method, passing the text you want, , and . + + [!code-csharp[System.Drawing.AlignDrawnText#60](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs#60)] + [!code-vb[System.Drawing.AlignDrawnText#60](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb#60)] + +## Compiling the Code + The previous examples require: + +- `e`, which is a parameter of . + +## See also + +- [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) +- [Using Fonts and Text](using-fonts-and-text.md) +- [How to: Construct Font Families and Fonts](how-to-construct-font-families-and-fonts.md) +- [How to: Draw Text at a Specified Location](how-to-draw-text-at-a-specified-location.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-enumerate-installed-fonts.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-enumerate-installed-fonts.md new file mode 100644 index 0000000000..877e981203 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-enumerate-installed-fonts.md @@ -0,0 +1,30 @@ +--- +title: "How to: Enumerate Installed Fonts" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "fonts [Windows Forms], enumerating installed" + - "examples [Windows Forms], fonts" +ms.assetid: 26d74ef5-0f39-4eeb-8d20-00e66e014abe +--- +# How to: Enumerate Installed Fonts +The class inherits from the abstract base class. You can use an object to enumerate the fonts installed on the computer. The property of an object is an array of objects. + +## Example + The following example lists the names of all the font families installed on the computer. The code retrieves the property of each object in the array returned by the property. As the family names are retrieved, they are concatenated to form a comma-separated list. Then the method of the class draws the comma-separated list in a rectangle. + + If you run the example code, the output will be similar to that shown in the following illustration: + + ![Screenshot that shows the installed font families.](./media/how-to-enumerate-installed-fonts/list-installed-font-families.png) + + [!code-csharp[System.Drawing.FontsAndText#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#11)] + [!code-vb[System.Drawing.FontsAndText#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . In addition, you should import the namespace. + +## See also + +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-extract-the-icon-associated-with-a-file-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-extract-the-icon-associated-with-a-file-in-windows-forms.md new file mode 100644 index 0000000000..c12b65238b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-extract-the-icon-associated-with-a-file-in-windows-forms.md @@ -0,0 +1,32 @@ +--- +title: "How to: Extract the Icon Associated with a File" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "displaying a file name and its file type icon in a ListView control [Windows Forms]" + - "file name extension icons [Windows Forms], displaying in a ListView" + - "extracting icons associated with a file type [Windows Forms]" +ms.assetid: 88e2ad8b-c34f-415a-84f2-dad756b5c928 +--- +# How to: Extract the Icon Associated with a File in Windows Forms +Many files have embedded icons that provide a visual representation of the associated file type. For example, Microsoft Word documents contain an icon that identifies them as Word documents. When displaying files in a list control or table control, you may want to display the icon representing the file type next to each file name. You can do this easily by using the method. + +## Example + The following code example demonstrates how to extract the icon associated with a file and display the file name and its associated icon in a control. + + [!code-csharp[System.Drawing.Icon.ExtractAssociatedIconEx#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/CS/Form1.cs#1)] + [!code-vb[System.Drawing.Icon.ExtractAssociatedIconEx#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/VB/Form1.vb#1)] + +## Compiling the Code + To compile the example: + +- Paste the preceding code into a Windows Form, and call the `ExtractAssociatedIconExample` method from the form's constructor or event-handling method. + + You will need to make sure that your form imports the namespace. + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [ListView Control](../controls/listview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-a-hatch-pattern.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-a-hatch-pattern.md new file mode 100644 index 0000000000..b52a747fa2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-a-hatch-pattern.md @@ -0,0 +1,43 @@ +--- +title: "How to: Fill a Shape with a Hatch Pattern" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "patterns [Windows Forms], adding to shapes" + - "shapes [Windows Forms], filling with patterns" + - "brushes [Windows Forms], using hatch brushes" +ms.assetid: 9c8300ff-187b-404f-af1f-ebd499f5b16f +--- +# How to: Fill a Shape with a Hatch Pattern +A hatch pattern is made from two colors: one for the background and one for the lines that form the pattern over the background. To fill a closed shape with a hatch pattern, use a object. The following example demonstrates how to fill an ellipse with a hatch pattern: + +## Example + The constructor takes three arguments: the hatch style, the color of the hatch line, and the color of the background. The hatch style argument can be any value from the enumeration. There are more than fifty elements in the enumeration; a few of those elements are shown in the following list: + +- + +- + +- + +- + +- + +- + + The following illustration shows the filled ellipse. + + ![Screenshot of what an ellipse filled with a hatch pattern looks like.](./media/how-to-fill-a-shape-with-a-hatch-pattern/ellipse-filled-hatch.png "hatch1") + + [!code-csharp[System.Drawing.UsingABrush#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#41)] + [!code-vb[System.Drawing.UsingABrush#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#41)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-a-solid-color.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-a-solid-color.md new file mode 100644 index 0000000000..24869173cb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-a-solid-color.md @@ -0,0 +1,28 @@ +--- +title: "How to: Fill a Shape with a Solid Color" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "colors [Windows Forms], adding to shapes" + - "shapes [Windows Forms], filling" +ms.assetid: 06088b31-bac9-4ef3-9ebe-06c2c764d6df +--- +# How to: Fill a Shape with a Solid Color +To fill a shape with a solid color, create a object, and then pass that object as an argument to one of the fill methods of the class. The following example shows how to fill an ellipse with the color red. + +## Example + In the following code, the constructor takes a object as its only argument. The values used by the method represent the alpha, red, green, and blue components of the color. Each of these values must be in the range 0 through 255. The first 255 indicates that the color is fully opaque, and the second 255 indicates that the red component is at full intensity. The two zeros indicate that the green and blue components both have an intensity of 0. + + The four numbers (0, 0, 100, 60) passed to the method specify the location and size of the bounding rectangle for the ellipse. The rectangle has an upper-left corner of (0, 0), a width of 100, and a height of 60. + + [!code-csharp[System.Drawing.UsingABrush#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#11)] + [!code-vb[System.Drawing.UsingABrush#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-an-image-texture.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-an-image-texture.md new file mode 100644 index 0000000000..4a08c0b910 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-a-shape-with-an-image-texture.md @@ -0,0 +1,32 @@ +--- +title: "How to: Fill a Shape with an Image Texture" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "images [Windows Forms], using with brushes" + - "bitmaps [Windows Forms], using texture" + - "shapes [Windows Forms], filling with images" +ms.assetid: 508da5a6-2433-4d2b-9680-eaeae4e96e3b +--- +# How to: Fill a Shape with an Image Texture +You can fill a closed shape with a texture by using the class and the class. + +## Example + The following example fills an ellipse with an image. The code constructs an object, and then passes the address of that object as an argument to a constructor. The third statement scales the image, and the fourth statement fills the ellipse with repeated copies of the scaled image. + + In the following code, the property contains the transformation that is applied to the image before it is drawn. Assume that the original image has a width of 640 pixels and a height of 480 pixels. The transform shrinks the image to 75×75 by setting the horizontal and vertical scaling values. + +> [!NOTE] +> In the following example, the image size is 75×75, and the ellipse size is 150×250. Because the image is smaller than the ellipse it is filling, the ellipse is tiled with the image. Tiling means that the image is repeated horizontally and vertically until the boundary of the shape is reached. For more information about tiling, see [How to: Tile a Shape with an Image](how-to-tile-a-shape-with-an-image.md). + + [!code-csharp[System.Drawing.UsingABrush#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#21)] + [!code-vb[System.Drawing.UsingABrush#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#21)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-open-figures.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-open-figures.md new file mode 100644 index 0000000000..42313efb80 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-fill-open-figures.md @@ -0,0 +1,31 @@ +--- +title: "How to: Fill Open Figures" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "open figures [Windows Forms], filling" + - "figures [Windows Forms], filling" +ms.assetid: 5a36b0e4-f1f4-46c0-a85a-22ae98491950 +--- +# How to: Fill Open Figures +You can fill a path by passing a object to the method. The method fills the path according to the fill mode (alternate or winding) currently set for the path. If the path has any open figures, the path is filled as if those figures were closed. GDI+ closes a figure by drawing a straight line from its ending point to its starting point. + +## Example + The following example creates a path that has one open figure (an arc) and one closed figure (an ellipse). The method fills the path according to the default fill mode, which is . + + The following illustration shows the output of the example code. Note that the path is filled (according to ) as if the open figure were closed by a straight line from its ending point to its starting point. + + ![Diagram that shows the output of the FillPath method](./media/how-to-fill-open-figures/fill-path-alternate-mode.png) + + [!code-csharp[System.Drawing.ConstructingDrawingPaths#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/CS/Class1.cs#11)] + [!code-vb[System.Drawing.ConstructingDrawingPaths#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- +- [Graphics Paths in GDI+](graphics-paths-in-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-flatten-a-curved-path-into-a-line.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-flatten-a-curved-path-into-a-line.md new file mode 100644 index 0000000000..b486c57981 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-flatten-a-curved-path-into-a-line.md @@ -0,0 +1,25 @@ +--- +title: "How to: Flatten a Curved Path into a Line" +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [Windows Forms], flattening curves into lines" + - "curves [Windows Forms], flattening" + - "GraphicsPath object" + - "paths [Windows Forms], flattening" + - "drawing [Windows Forms], flattening curves" +ms.assetid: e654b8de-25f4-4735-9208-42e4514a589c +--- +# How to: Flatten a Curved Path into a Line +A object stores a sequence of lines and Bézier splines. You can add several types of curves (ellipses, arcs, cardinal splines) to a path, but each curve is converted to a Bézier spline before it is stored in the path. Flattening a path consists of converting each Bézier spline in the path to a sequence of straight lines. The following illustration shows a path before and after flattening. + + ![Straight Lines and Curves](./media/aboutgdip02-art32a.gif "AboutGdip02_Art32A") + +### To Flatten a Path + +- call the method of a object. The method receives a flatness argument that specifies the maximum distance between the flattened path and the original path. + +## See also + +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [Constructing and Drawing Paths](constructing-and-drawing-paths.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-improve-performance-by-avoiding-automatic-scaling.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-improve-performance-by-avoiding-automatic-scaling.md new file mode 100644 index 0000000000..6710a7dc9e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-improve-performance-by-avoiding-automatic-scaling.md @@ -0,0 +1,40 @@ +--- +title: "How to: Improve Performance by Avoiding Automatic Scaling" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "automatic scaling" + - "images [Windows Forms], improving performance" + - "images [Windows Forms], using without automatic scaling" + - "performance [Windows Forms], improving image" +ms.assetid: 5fe2c95d-8653-4d55-bf0d-e5afa28f223b +--- +# How to: Improve Performance by Avoiding Automatic Scaling +GDI+ may automatically scale an image as you draw it, which would decrease performance. Alternatively, you can control the scaling of the image by passing the dimensions of the destination rectangle to the method. + + For example, the following call to the method specifies an upper-left corner of (50, 30) but does not specify a destination rectangle. + + [!code-csharp[System.Drawing.WorkingWithImages#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#31)] + [!code-vb[System.Drawing.WorkingWithImages#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#31)] + + Although this is the easiest version of the method in terms of the number of required arguments, it is not necessarily the most efficient. If the resolution used by GDI+ (usually 96 dots per inch) is different from the resolution stored in the object, then the method will scale the image. For example, suppose an object has a width of 216 pixels and a stored horizontal resolution value of 72 dots per inch. Because 216/72 is 3, will scale the image so that it has a width of 3 inches at a resolution of 96 dots per inch. That is, will display an image that has a width of 96x3 = 288 pixels. + + Even if your screen resolution is different from 96 dots per inch, GDI+ will probably scale the image as if the screen resolution were 96 dots per inch. That is because a GDI+ object is associated with a device context, and when GDI+ queries the device context for the screen resolution, the result is usually 96, regardless of the actual screen resolution. You can avoid automatic scaling by specifying the destination rectangle in the method. + +## Example + The following example draws the same image twice. In the first case, the width and height of the destination rectangle are not specified, and the image is automatically scaled. In the second case, the width and height (measured in pixels) of the destination rectangle are specified to be the same as the width and height of the original image. The following illustration shows the image rendered twice: + + ![Screenshot that shows images with scaled texture.](./media/how-to-improve-performance-by-avoiding-automatic-scaling/two-scaled-texture-images.png) + + [!code-csharp[System.Drawing.WorkingWithImages#32](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#32)] + [!code-vb[System.Drawing.WorkingWithImages#32](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#32)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Replace Texture.jpg with an image name and path that are valid on your system. + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-inherit-forms-using-the-inheritance-picker-dialog-box.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-inherit-forms-using-the-inheritance-picker-dialog-box.md new file mode 100644 index 0000000000..0ab2f81ece --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-inherit-forms-using-the-inheritance-picker-dialog-box.md @@ -0,0 +1,57 @@ +--- +title: "How to: Inherit Forms Using the Inheritance Picker Dialog Box" +ms.date: "03/30/2017" +helpviewer_keywords: + - "inheritance [Windows Forms], forms" + - "Inheritance Picker dialog box" + - "inherited forms [Windows Forms], creating" +ms.assetid: 969b4c04-12aa-4297-93a2-0ae747447823 +--- +# How to: Inherit Forms Using the Inheritance Picker + +The easiest way to inherit a form or other object is to use the **Inheritance Picker** dialog box. With it, you can take advantage of code or user interfaces (UI) you have already created in other solutions. + +> [!NOTE] +> In order to inherit from a form with the **Inheritance Picker** dialog box, the project containing that form must have been built into an executable file or DLL. To build the project, choose **Build Solution** from the **Build** menu. + +## Create a Windows Form by using the Inheritance Picker + +1. In Visual Studio, from the **Project** menu, choose **Add Windows Form**. + + The **Add New Item** dialog box opens. + +2. Search the **Inherited Form** template either from the searchbox or by clicking on the **Windows Forms** category, select it, and name it in the **Name** box. Click the **Add** button to proceed. + + The **Inheritance Picker** dialog box opens. If the current project already contains forms, they are displayed in the **Inheritance Picker** dialog box. + +3. To inherit from a form in another assembly, click the **Browse** button. + +4. Within the **Select a file which contains a component to inherit from** dialog box, navigate to the project containing the form or module you desire. + +5. Click the name of the .exe or .dll file to select it and click the **Open** button. + + This returns you to the **Inheritance Picker** dialog box, where the component is now listed, along with the project in which it is located. + +6. Select the component. + + In **Solution Explorer**, the component is added to your project. If it has a UI, controls that are part of the inherited form will be marked with a glyph (![Screenshot of the Visual Basic inheritance symbol.](./media/how-to-inherit-forms-using-the-inheritance-picker-dialog-box/visual-basic-inheritance-glyph.gif)), and, when selected, have a border indicating the level of security that the control has on the superclassed form. The behaviors that correspond to the different security levels are listed in the table below. + + |Security level of control|Available interaction through Designer and Code Editor with Inherited Form| + |-------------------------------|--------------------------------------------------------------------------------| + |Public|Standard border with sizing handles: control may be sized and moved. The control can be accessed internally by the class which declares it and externally by other classes.| + |Protected|Standard border with sizing handles: control may be sized and moved. Can be accessed internally by the class that declares it and any class that inherits from the parent class, but cannot be accessed by external classes.| + |Protected Internal (Protected Friend in Visual Basic)|Standard border with sizing handles: control may be sized and moved. Can be accessed internally by the class that declares it, by any class that inherits from the parent class, and by other members of the assembly that contains it.| + |Internal (Friend in Visual Basic)|Standard border with no sizing handles, shown on the form, properties visible in **Properties** window. However, all aspects of the control will be considered read-only. You cannot move or size the control, or change its properties. If the control is a container of other controls, like a group box, new controls cannot be added and existing controls cannot be removed, even if those controls were public. The control can only be accessed by other members of the assembly that contains it.| + |Private|Standard border with no sizing handles, shown on the form, properties visible in **Properties** window. However, all aspects of the control will be considered read-only. You cannot move or size the control, or change its properties. If the control is a container of other controls, like a group box, new controls cannot be added and existing controls cannot be removed, even if those controls were public. The control can only be accessed by the class that declares it.| + + For information about how to alter a base form's appearance, see [Effects of Modifying a Base Form's Appearance](effects-of-modifying-base-form-appearance.md). + + > [!NOTE] + > When you combine inherited controls and components with standard controls and components on Windows Forms, you might encounter conflicts with the z-ordering. You can correct this by modifying the z-order, which is done by clicking in the **Format** menu, pointing to **Order**, and then clicking **Bring To Front** or **Send To Back**. For more information about the z-order of controls, see [How to: Layer Objects on Windows Forms](../controls/how-to-layer-objects-on-windows-forms.md). + +## See also + +- [Inherits Statement](https://docs.microsoft.com/dotnet/visual-basic/language-reference/statements/inherits-statement) +- [using](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/using) +- [Effects of Modifying a Base Form's Appearance](effects-of-modifying-base-form-appearance.md) +- [Windows Forms Visual Inheritance](windows-forms-visual-inheritance.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-inherit-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-inherit-windows-forms.md new file mode 100644 index 0000000000..d618554754 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-inherit-windows-forms.md @@ -0,0 +1,45 @@ +--- +title: Form inheritance +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "inherited forms [Windows Forms], creating at run-time" + - "inheritance [Windows Forms], forms" + - "Windows Forms, inheritance" +ms.assetid: cb3e1c0f-3d2a-4cdc-b0d1-c92eae567ffb +--- +# How to: Inherit Windows Forms + +Creating new Windows Forms by inheriting from base forms is a handy way to duplicate your best efforts without going through the process of entirely recreating a form every time you require it. + +For more information about inheriting forms at design time using the **Inheritance Picker** dialog box and how to visually distinguish between security levels of inherited controls, see [How to: Inherit Forms Using the Inheritance Picker Dialog Box](how-to-inherit-forms-using-the-inheritance-picker-dialog-box.md). + +> [!NOTE] +> In order to inherit from a form, the file or namespace containing that form must have been built into an executable file or DLL. To build the project, choose **Build** from the **Build** menu. Also, a reference to the namespace must be added to the class inheriting the form. + +## Inherit a form programmatically + +1. In your class, add a reference to the namespace containing the form you wish to inherit from. + +2. In the class definition, add a reference to the form to inherit from. The reference should include the namespace that contains the form, followed by a period, then the name of the base form itself. + + ```vb + Public Class Form2 + Inherits Namespace1.Form1 + ``` + + ```csharp + public class Form2 : Namespace1.Form1 + ``` + + When inheriting forms, keep in mind that issues may arise with regard to event handlers being called twice, because each event is being handled by both the base class and the inherited class. For more information on how to avoid this problem, see [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers). + +## See also + +- [Inherits Statement](https://docs.microsoft.com/dotnet/visual-basic/language-reference/statements/inherits-statement) +- [Imports Statement (.NET Namespace and Type)](https://docs.microsoft.com/dotnet/visual-basic/language-reference/statements/imports-statement-net-namespace-and-type) +- [using](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/using) +- [Effects of Modifying a Base Form's Appearance](effects-of-modifying-base-form-appearance.md) +- [Windows Forms Visual Inheritance](windows-forms-visual-inheritance.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-join-lines.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-join-lines.md new file mode 100644 index 0000000000..ea2a0f6363 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-join-lines.md @@ -0,0 +1,36 @@ +--- +title: "How to: Join Lines" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "miter line join style" + - "bevel line join style" + - "line join" + - "drawing [Windows Forms], joining lines" + - "GraphicsPath object" + - "round line join style" + - "lines [Windows Forms], joining" + - "graphics [Windows Forms], joining lines" +ms.assetid: 9fc480c2-3c75-4fd1-8ab5-296a99e820e2 +--- +# How to: Join Lines +A line join is the common area that is formed by two lines whose ends meet or overlap. GDI+ provides three line join styles: miter, bevel, and round. Line join style is a property of the class. When you specify a line join style for a object, that join style will be applied to all the connected lines in any object drawn using that pen. + + The following illustration shows the results of the beveled line join example. + + ![Illustration that shows joined lines.](./media/how-to-join-lines/joined-beveled-lines.gif) + +## Example + You can specify the line join style by using the property of the class. The example demonstrates a beveled line join between a horizontal line and a vertical line. In the following code, the value assigned to the property is a member of the enumeration. The other members of the enumeration are and . + + [!code-csharp[System.Drawing.UsingAPen#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#31)] + [!code-vb[System.Drawing.UsingAPen#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#31)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-list-installed-decoders.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-list-installed-decoders.md new file mode 100644 index 0000000000..be37649494 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-list-installed-decoders.md @@ -0,0 +1,31 @@ +--- +title: "How to: List Installed Decoders" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "image codecs [Windows Forms], listing" + - "image decoders [Windows Forms], listing" +ms.assetid: 11417191-8c95-40ca-8024-779e61706fb6 +--- +# How to: List Installed Decoders +You may want to list the image decoders available on a computer, to determine whether your application can read a particular image file format. The class provides the static methods so that you can determine which image decoders are available. returns an array of objects. + +## Example + The following code example outputs the list of installed decoders and their property values. + + [!code-csharp[UsingImageEncodersDecoders#2](~/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs#2)] + [!code-vb[UsingImageEncodersDecoders#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb#2)] + +## Compiling the Code + This example requires: + +- A Windows Forms application. + +- A , which is a parameter of . + +## See also + +- [How to: List Installed Encoders](how-to-list-installed-encoders.md) +- [Using Image Encoders and Decoders in Managed GDI+](using-image-encoders-and-decoders-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-list-installed-encoders.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-list-installed-encoders.md new file mode 100644 index 0000000000..9804fb3fac --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-list-installed-encoders.md @@ -0,0 +1,31 @@ +--- +title: "How to: List Installed Encoders" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "image codecs [Windows Forms], listing" + - "image encoders [Windows Forms], listing" +ms.assetid: 49e8e4e9-7a67-42d9-86bf-08821cdc282e +--- +# How to: List Installed Encoders +You may want to list the image encoders available on a computer, to determine whether your application can save to a particular image file format. The class provides the static methods so that you can determine which image encoders are available. returns an array of objects. + +## Example + The following code example outputs the list of installed encoders and their property values. + + [!code-csharp[UsingImageEncodersDecoders#1](~/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs#1)] + [!code-vb[UsingImageEncodersDecoders#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- A Windows Forms application. + +- A , which is a parameter of . + +## See also + +- [How to: List Installed Decoders](how-to-list-installed-decoders.md) +- [Using Image Encoders and Decoders in Managed GDI+](using-image-encoders-and-decoders-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-load-and-display-metafiles.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-load-and-display-metafiles.md new file mode 100644 index 0000000000..1d830f1aa3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-load-and-display-metafiles.md @@ -0,0 +1,32 @@ +--- +title: "How to: Load and Display Metafiles" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "examples [Windows Forms], metafiles" + - "metafiles [Windows Forms], displaying" +ms.assetid: 60af1714-f148-4d85-a739-0557965ffa73 +--- +# How to: Load and Display Metafiles +The class, which inherits from the class, provides methods for recording, displaying, and examining vector images. + +## Example + To display a vector image (metafile) on the screen, you need a object and a object. Pass the name of a file (or a stream) to a constructor. After you have created a object, pass that object to the method of a object. + + The example creates a object from an EMF (enhanced metafile) file and then draws the image with its upper-left corner at (60, 10). + + The following illustration shows the metafile drawn at the specified location. + + ![Screenshot showing image position.](./media/how-to-load-and-display-metafiles/metafile-drawn-specified-location.png "imageposition2") + + [!code-csharp[System.Drawing.WorkingWithImages#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#41)] + [!code-vb[System.Drawing.WorkingWithImages#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#41)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-manually-manage-buffered-graphics.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-manually-manage-buffered-graphics.md new file mode 100644 index 0000000000..01a764587e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-manually-manage-buffered-graphics.md @@ -0,0 +1,38 @@ +--- +title: "How to: Manually Manage Buffered Graphics" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "flicker [Windows Forms], reducing by manually managing graphics" + - "graphics [Windows Forms], managing buffered" +ms.assetid: 4c2a90ee-bbbe-4ff6-9170-1b06c195c918 +--- +# How to: Manually Manage Buffered Graphics +For more advanced double buffering scenarios, you can use the .NET Framework classes to implement your own double-buffering logic. The class responsible for allocating and managing individual graphics buffers is the class. Every application has its own default that manages all of the default double buffering for that application. You can retrieve a reference to this instance by calling the . + +### To obtain a reference to the default BufferedGraphicsContext + +- Set the property, as shown in the following code example. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#11)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#11)] + + > [!NOTE] + > You do not need to call the `Dispose` method on the reference that you receive from the class. The handles all of the memory allocation and distribution for default instances. + + For graphically intensive applications such as animation, you can sometimes improve performance by using a dedicated instead of the provided by the . This enables you to create and manage graphics buffers individually, without incurring the performance overhead of managing all the other buffered graphics associated with your application, though the memory consumed by the application will be greater. + +### To create a dedicated BufferedGraphicsContext + +- Declare and create a new instance of the class, as shown in the following code example. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#12)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#12)] + +## See also + +- +- [Double Buffered Graphics](double-buffered-graphics.md) +- [How to: Manually Render Buffered Graphics](how-to-manually-render-buffered-graphics.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-manually-render-buffered-graphics.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-manually-render-buffered-graphics.md new file mode 100644 index 0000000000..79316da1ac --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-manually-render-buffered-graphics.md @@ -0,0 +1,47 @@ +--- +title: "How to: Manually Render Buffered Graphics" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "flicker [Windows Forms], reducing by manually rendering graphics" + - "graphics [Windows Forms], rendering" +ms.assetid: 5192295e-bd8e-45f7-8bd6-5c4f6bd21e61 +--- +# How to: Manually Render Buffered Graphics +If you are managing your own buffered graphics, you will need to be able to create and render graphics buffers. You can create instances of the class that is associated with drawing surfaces on your screen by calling the method. This method creates a instance that is associated with a particular rendering surface, such as a form or control. After you have created a instance, you can draw graphics to the buffer it represents through the property. After you have performed all graphics operations, you can copy the contents of the buffer to the screen by calling the method. + +> [!NOTE] +> If you perform your own rendering, memory consumption will increase, though the increase may only be slight. + +### To manually display buffered graphics + +1. Obtain a reference to an instance of the class. For more information, see [How to: Manually Manage Buffered Graphics](how-to-manually-manage-buffered-graphics.md). + +2. Create an instance of the class by calling the method, as shown in the following code example. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#21)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#21)] + +3. Draw graphics to the graphics buffer by setting the property. For example: + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#22)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#22)] + +4. When you have completed all of your drawing operations to the graphics buffer, call the method to render the buffer, either to the drawing surface associated with that buffer, or to a specified drawing surface, as shown in the following code example. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#23)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#23)] + +5. After you are finished rendering graphics, call the `Dispose` method on the instance to free system resources. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#24](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#24)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#24](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#24)] + +## See also + +- +- +- [Double Buffered Graphics](double-buffered-graphics.md) +- [How to: Manually Manage Buffered Graphics](how-to-manually-manage-buffered-graphics.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-obtain-font-metrics.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-obtain-font-metrics.md new file mode 100644 index 0000000000..7f2a9775ed --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-obtain-font-metrics.md @@ -0,0 +1,55 @@ +--- +title: "How to: Obtain Font Metrics" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "fonts [Windows Forms], obtaining metrics" + - "font metrics [Windows Forms], obtaining" +ms.assetid: ff7c0616-67f7-4fa2-84ee-b8d642f2b09b +--- +# How to: Obtain Font Metrics +The class provides the following methods that retrieve various metrics for a particular family/style combination: + +- (FontStyle) + +- (FontStyle) + +- (FontStyle) + +- (FontStyle) + + The values returned by these methods are in font design units, so they are independent of the size and units of a particular object. + + The following illustration shows the various metrics: + + ![Illustration of font metrics: ascent, descent, and line spacing.](./media/how-to-obtain-font-metrics/various-font-metrics.png) + +## Example + The following example displays the metrics for the regular style of the Arial font family. The code also creates a object (based on the Arial family) with size 16 pixels and displays the metrics (in pixels) for that particular object. + + The following illustration shows the output of the example code: + + ![Example code output of Arial font metrics.](./media/how-to-obtain-font-metrics/example-output-code-arial-font.png) + + Note the first two lines of output in the preceding illustration. The object returns a size of 16, and the object returns an em height of 2,048. These two numbers (16 and 2,048) are the key to converting between font design units and the units (in this case pixels) of the object. + + For example, you can convert the ascent from design units to pixels as follows: + + ![Formula showing the conversion from design units to pixels](./media/how-to-obtain-font-metrics/convert-font-units-example.png) + + The following code positions text vertically by setting the data member of a object. The y-coordinate is increased by `font.Height` for each new line of text. The property of a object returns the line spacing (in pixels) for that particular object. In this example, the number returned by is 19. Note that this is the same as the number (rounded up to an integer) obtained by converting the line-spacing metric to pixels. + + Note that the em height (also called size or em size) is not the sum of the ascent and the descent. The sum of the ascent and the descent is called the cell height. The cell height minus the internal leading is equal to the em height. The cell height plus the external leading is equal to the line spacing. + + [!code-csharp[System.Drawing.FontsAndText#71](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#71)] + [!code-vb[System.Drawing.FontsAndText#71](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#71)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-perform-drag-and-drop-operations-between-applications.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-perform-drag-and-drop-operations-between-applications.md new file mode 100644 index 0000000000..ec39410e77 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-perform-drag-and-drop-operations-between-applications.md @@ -0,0 +1,39 @@ +--- +title: "How to: Perform Drag-and-Drop Operations Between Applications" +ms.date: "03/30/2017" +helpviewer_keywords: + - "drag and drop [Windows Forms], between applications" +ms.assetid: fa347436-2b12-4dd6-8507-59d7241f6a06 +--- +# How to: Perform Drag-and-Drop Operations Between Applications +Performing drag-and-drop operations between applications is no different than enabling this action within an application, as long as both applications involved behave according to the "contract" established between the and properties. + + In the following procedure, you will use a Windows-based application you create and the WordPad word processor that is included with the Windows operating system to perform drag-and-drop operations between applications. WordPad has a certain set of allowed effects for text being dragged and dropped; the Windows-based application you will write code for will work with these effects so that drag-and-drop operations may be completed successfully. + +### To perform a drag-and-drop procedure between applications + +1. Create a new Windows Forms application. + +2. Add a control to your form. + +3. Configure the control to receive dropped data. + + For more information, see [Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms](walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md). + +4. Run your Windows-based application, and while the application is running, run WordPad. + + WordPad is a text editor installed by Windows that allows drag-and-drop operations. It is accessible by pressing the **Start** button, selecting **Run**, and then typing `WordPad` into the text box of the **Run** dialog box and clicking **OK**. + +5. Once WordPad is open, type a string of text into it. + +6. Using the mouse, select the text, and then drag the selected text over to the control in your Windows-based application. + + Observe that when you mouse over the control (and, consequently, raise the event), the cursor changes, and you can drop the selected text into the control. + + Additionally, you can configure your control to allow text strings to be dragged and dropped into WordPad. For more information, see [Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms](walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md). + +## See also + +- [How to: Add Data to the Clipboard](how-to-add-data-to-the-clipboard.md) +- [How to: Retrieve Data from the Clipboard](how-to-retrieve-data-from-the-clipboard.md) +- [Drag-and-Drop Operations and Clipboard Support](drag-and-drop-operations-and-clipboard-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-a-multi-page-text-file-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-a-multi-page-text-file-in-windows-forms.md new file mode 100644 index 0000000000..4c97493017 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-a-multi-page-text-file-in-windows-forms.md @@ -0,0 +1,61 @@ +--- +title: "How to: Print a Multi-Page Text File" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "printing [Windows Forms], printing multiple pages" + - "text [Windows Forms], printing Windows Forms" + - "Windows Forms, printing text" + - "printing [Windows Forms], text" +ms.assetid: 362427f8-03d4-4826-b49f-60ab066ad322 +--- +# How to: Print a Multi-Page Text File in Windows Forms +It is very common for Windows-based applications to print text. The class provides methods for drawing objects (graphics or text) to a device, such as a screen or printer. + +> [!NOTE] +> The methods of are not supported for printing. You should always use the methods of , as shown in the following code example, to draw text for printing purposes. + +### To print text + +1. Add a component and a string to your form. + + [!code-csharp[System.Drawing.Printing.PrintExamples#8](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs#8)] + [!code-vb[System.Drawing.Printing.PrintExamples#8](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb#8)] + +2. If printing a document, set the property to the document you wish to print, and open and read the documents contents to the string you added previously. + + [!code-csharp[System.Drawing.Printing.PrintExamples#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs#1)] + [!code-vb[System.Drawing.Printing.PrintExamples#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb#1)] + +3. In the event handler, use the property of the class and the document contents to calculate line length and lines per page. After each page is drawn, check to see if it is the last page, and set the property of the accordingly. The event is raised until is `false`. Also, make sure the event is associated with its event-handling method. + + In the following code example, the event handler is used to print the contents of the "testPage.txt" file in the same font as is used on the form. + + [!code-csharp[System.Drawing.Printing.PrintExamples#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs#2)] + [!code-vb[System.Drawing.Printing.PrintExamples#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb#2)] + +4. Call the method to raise the event. + + [!code-csharp[System.Drawing.Printing.PrintExamples#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs#5)] + [!code-vb[System.Drawing.Printing.PrintExamples#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb#5)] + +## Example + [!code-csharp[System.Drawing.Printing.PrintExamples#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs#0)] + [!code-vb[System.Drawing.Printing.PrintExamples#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb#0)] + +## Compiling the Code + This example requires: + +- A text file named testPage.txt containing the text to print, located in the root of drive C:\\. Edit the code to print a different file. + +- References to the System, System.Windows.Forms, System.Drawing assemblies. + +- For information about building this example from the command line for Visual Basic or Visual C#, see [Building from the Command Line](https://docs.microsoft.com/dotnet/visual-basic/reference/command-line-compiler/building-from-the-command-line) or [Command-line Building With csc.exe](https://docs.microsoft.com/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe). You can also build this example in Visual Studio by pasting the code into a new project. + +## See also + +- +- +- [Windows Forms Print Support](windows-forms-print-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-a-windows-form.md new file mode 100644 index 0000000000..54f244a18f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-a-windows-form.md @@ -0,0 +1,36 @@ +--- +title: "How to: Print a Windows Form" +description: Learn how to programmatically print a copy of the current Windows Form by using the CopyFromScreen method. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, printing" + - "printing [Windows Forms]" + - "printing a form" + - "printing [Windows Forms], printing a form" +ms.assetid: c8dff5f8-f56a-4c07-ae31-64643b31f8fc +--- +# How to: Print a Windows Form +As part of the development process, you typically will want to print a copy of your Windows Form. The following code example shows how to print a copy of the current form by using the method. + +## Example + [!code-csharp[System.Drawing.Graphics.CopyFromScreen#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/CS/Form1.cs#1)] + [!code-vb[System.Drawing.Graphics.CopyFromScreen#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/VB/Form1.vb#1)] + +## Robust Programming + The following conditions may cause an exception: + +- You do not have permission to access the printer. + +- There is no printer installed. + +## .NET Framework Security + In order to run this code example, you must have permission to access the printer you use with your computer. + +## See also + +- +- [How to: Render Images with GDI+](how-to-render-images-with-gdi.md) +- [How to: Print Graphics in Windows Forms](how-to-print-graphics-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-graphics-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-graphics-in-windows-forms.md new file mode 100644 index 0000000000..e378359c07 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-graphics-in-windows-forms.md @@ -0,0 +1,67 @@ +--- +title: "How to: Print Graphics" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "graphics [Windows Forms], printing" + - "printing [Windows Forms], graphics" +ms.assetid: 32b891e6-52ff-4fea-a9ff-2ce5db20a4c6 +--- +# How to: Print Graphics in Windows Forms +Frequently, you will want to print graphics in your Windows-based application. The class provides methods for drawing objects to a device, such as a screen or printer. + +### To print graphics + +1. Add a component to your form. + +2. In the event handler, use the property of the class to instruct the printer on what kind of graphics to print. + + The following code example shows an event handler used to create a blue ellipse within a bounding rectangle. The rectangle has the following location and dimensions: beginning at 100, 150 with a width of 250 and a height of 250. + + ```vb + Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage + e.Graphics.FillEllipse(Brushes.Blue, New Rectangle(100, 150, 250, 250)) + End Sub + ``` + + ```csharp + private void printDocument1_PrintPage(object sender, + System.Drawing.Printing.PrintPageEventArgs e) + { + e.Graphics.FillRectangle(Brushes.Blue, + new Rectangle(100, 150, 250, 250)); + } + ``` + + ```cpp + private: + void printDocument1_PrintPage(System::Object ^ sender, + System::Drawing::Printing::PrintPageEventArgs ^ e) + { + e->Graphics->FillRectangle(Brushes::Blue, + Rectangle(100, 150, 250, 250)); + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.printDocument1.PrintPage += new + System.Drawing.Printing.PrintPageEventHandler + (this.printDocument1_PrintPage); + ``` + + ```cpp + this->printDocument1->PrintPage += gcnew + System::Drawing::Printing::PrintPageEventHandler + (this, &Form1::printDocument1_PrintPage); + ``` + +## See also + +- +- +- [Windows Forms Print Support](windows-forms-print-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-in-windows-forms-using-print-preview.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-in-windows-forms-using-print-preview.md new file mode 100644 index 0000000000..d2804efd30 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-print-in-windows-forms-using-print-preview.md @@ -0,0 +1,64 @@ +--- +title: Print Using Print Preview +description: Learn how to add print preview services to your application by using the Windows Forms PrintPreviewDialog control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "printing [Windows Forms], using print preview" + - "printing [Windows Forms], with print preview" + - "print preview" +ms.assetid: 4a16f7e2-ae10-4485-b0ae-3d558334d0fe +--- +# How to: Print in Windows Forms Using Print Preview +It is very common in Windows Forms programming to offer print preview in addition to printing services. An easy way to add print preview services to your application is to use a control in combination with the event-handling logic for printing a file. + +### To preview a text document with a PrintPreviewDialog control + +1. Add a , , and two strings to your form. + + [!code-csharp[System.Drawing.Printing.PrintPreviewExample#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs#1)] + [!code-vb[System.Drawing.Printing.PrintPreviewExample#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb#1)] + +2. Set the property to the document you wish to print, and open and read the document's contents to the string you added previously. + + [!code-csharp[System.Drawing.Printing.PrintPreviewExample#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs#2)] + [!code-vb[System.Drawing.Printing.PrintPreviewExample#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb#2)] + +3. As you would for printing the document, in the event handler, use the property of the class and the file contents to calculate lines per page and render the document's contents. After each page is drawn, check to see if it is the last page, and set the property of the accordingly. The event is raised until is `false`. When the document has finished rendering, reset the string to be rendered. Also, make sure the event is associated with its event-handling method. + + > [!NOTE] + > You may have already completed steps 2 and 3 if you have implemented printing in your application. + + In the following code example, the event handler is used to print the "testPage.txt" file in the same font used on the form. + + [!code-csharp[System.Drawing.Printing.PrintPreviewExample#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs#3)] + [!code-vb[System.Drawing.Printing.PrintPreviewExample#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb#3)] + +4. Set the property of the control to the component on the form. + + [!code-csharp[System.Drawing.Printing.PrintPreviewExample#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs#5)] + [!code-vb[System.Drawing.Printing.PrintPreviewExample#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb#5)] + +5. Call the method on the control. You would typically call from the event-handling method of a button. Calling raises the event and renders the output to the control. When the user clicks the print icon on the dialog, the event is raised again, sending the output to the printer instead of the preview dialog. This is why the string is reset at the end of the rendering process in step 3. + + The following code example shows the event-handling method for a button on the form. This event-handling method calls the methods to read the document and show the print preview dialog. + + [!code-csharp[System.Drawing.Printing.PrintPreviewExample#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs#4)] + [!code-vb[System.Drawing.Printing.PrintPreviewExample#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb#4)] + +## Example + [!code-csharp[System.Drawing.Printing.PrintPreviewExample#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs#0)] + [!code-vb[System.Drawing.Printing.PrintPreviewExample#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Windows.Forms, System.Drawing assemblies. + +## See also + +- [How to: Print a Multi-Page Text File in Windows Forms](how-to-print-a-multi-page-text-file-in-windows-forms.md) +- [Windows Forms Print Support](windows-forms-print-support.md) +- [More Secure Printing in Windows Forms](../more-secure-printing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-provide-help-in-a-windows-application.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-provide-help-in-a-windows-application.md new file mode 100644 index 0000000000..7ecef9cfbf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-provide-help-in-a-windows-application.md @@ -0,0 +1,55 @@ +--- +title: "How to: Provide Help in a Windows Application" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Help [Windows Forms], Windows applications" + - "HTML Help [Windows Forms], Windows Forms" + - "Windows applications [Windows Forms], providing Help" + - "HelpProvider component [Windows Forms]" + - "forms [Windows Forms], providing Help" +ms.assetid: 7c4e5cec-2bd2-4f0b-8d75-c2b88929bd61 +--- +# How to: Provide Help in a Windows Application + +You can make use of the component to attach Help topics within a Help file to specific controls on Windows Forms. The Help file can be either HTML or HTMLHelp 1.x or greater format. + +## Provide Help + +1. In Visual Studio, from the **Toolbox**, drag a component to your form. + + The component will reside in the tray at the bottom of the Windows Forms Designer. + +2. In the **Properties** window, set the property to the .chm, .col, or .htm Help file. + +3. Select another control you have on your form, and in the **Properties** window, set the property. + + This is the string passed through the component to your Help file to summon the appropriate Help topic. + +4. In the **Properties** window, set the property to a value of the enumeration. + + This determines the way in which the **HelpKeyword** property is passed to the Help system. The following table shows the possible settings and their descriptions. + + |Member Name|Description| + |-----------------|-----------------| + |AssociateIndex|Specifies that the index for a specified topic is performed in the specified URL.| + |Find|Specifies that the search page of a specified URL is displayed.| + |Index|Specifies that the index of a specified URL is displayed.| + |KeywordIndex|Specifies a keyword to search for and the action to take in the specified URL.| + |TableOfContents|Specifies that the table of contents of the HTML 1.0 Help file is displayed.| + |Topic|Specifies that the topic referenced by the specified URL is displayed.| + + At run time, pressing F1 when the control—for which you have set the **HelpKeyword** and **HelpNavigator** properties—has focus will open the Help file you associated with that component. + + Currently, the **HelpNamespace** property supports Help files in the following three formats: HTMLHelp 1.x, HTMLHelp 2.0, and HTML. Thus, you can set the **HelpNamespace** property to an `http://` address, such as a Web page. If this is done, it will open the default browser to the Web page with the string specified in the **HelpKeyword** property used as the anchor. The anchor is used to jump to a specific part of an HTML page. + +> [!IMPORTANT] +> Be careful to check any information that is sent from a client before using it in your application. Malicious users might try to send or inject executable script, SQL statements, or other code. Before you display a user's input, store it in a database, or work with it, check that it does not contain potentially unsafe information. A typical way to check is to use a regular expression to look for keywords such as "SCRIPT" when you receive input from a user. + +You can also use the component to show pop-up Help, even if you have it configured to display Help files for the controls on your Windows Forms. For more information, see [How to: Display Pop-up Help](how-to-display-pop-up-help.md). + +## See also + +- [How to: Display Pop-up Help](how-to-display-pop-up-help.md) +- [Control Help Using ToolTips](control-help-using-tooltips.md) +- [Integrating User Help in Windows Forms](integrating-user-help-in-windows-forms.md) +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-read-image-metadata.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-read-image-metadata.md new file mode 100644 index 0000000000..8f1c977ed3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-read-image-metadata.md @@ -0,0 +1,130 @@ +--- +title: "How to: Read Image Metadata" +desription: Learn how to read the Windows Forms PropertyItems property of an Image object to retrieve all the metadata from a file. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "metadata [Windows Forms], property item" + - "metadata [Windows Forms], reading image" +ms.assetid: 72ec0b31-0be7-444a-9575-1dbcb864e0be +--- +# How to: Read Image Metadata + +Some image files contain metadata that you can read to determine features of the image. For example, a digital photograph might contain metadata that you can read to determine the make and model of the camera used to capture the image. With GDI+, you can read existing metadata, and you can also write new metadata to image files. + +GDI+ stores an individual piece of metadata in a object. You can read the property of an object to retrieve all the metadata from a file. The property returns an array of objects. + +A object has the following four properties: `Id`, `Value`, `Len`, and `Type`. + +## Id + +A tag that identifies the metadata item. Some values that can be assigned to are shown in the following table: + +|Hexadecimal value|Description| +|-----------------------|-----------------| +|0x0320

0x010F

0x0110

0x9003

0x829A

0x5090

0x5091|Image title

Equipment manufacturer

Equipment model

ExifDTOriginal

Exif exposure time

Luminance table

Chrominance table| + +## Value + +An array of values. The format of the values is determined by the property. + +## Len + +The length (in bytes) of the array of values pointed to by the property. + +## Type + +The data type of the values in the array pointed to by the `Value` property. The formats indicated by the `Type` property values are shown in the following table: + +|Numeric value|Description| +|-------------------|-----------------| +|1|A `Byte`| +|2|An array of `Byte` objects encoded as ASCII| +|3|A 16-bit integer| +|4|A 32-bit integer| +|5|An array of two `Byte` objects that represent a rational number| +|6|Not used| +|7|Undefined| +|8|Not used| +|9|`SLong`| +|10|`SRational`| + +## Example + +The following code example reads and displays the seven pieces of metadata in the file `FakePhoto.jpg`. The second (index 1) property item in the list has 0x010F (equipment manufacturer) and 2 (ASCII-encoded byte array). The code example displays the value of that property item. + +[!code-csharp[System.Drawing.WorkingWithImages#51](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#51)] +[!code-vb[System.Drawing.WorkingWithImages#51](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#51)] + +The code produces output similar to the following: + +```output + Property Item 0 + + id: 0x320 + + type: 2 + + length: 16 bytes + + Property Item 1 + + id: 0x10f + + type: 2 + + length: 17 bytes + + Property Item 2 + + id: 0x110 + + type: 2 + + length: 7 bytes + + Property Item 3 + + id: 0x9003 + + type: 2 + + length: 20 bytes + + Property Item 4 + + id: 0x829a + + type: 5 + + length: 8 bytes + + Property Item 5 + + id: 0x5090 + + type: 3 + + length: 128 bytes + + Property Item 6 + + id: 0x5091 + + type: 3 + + length: 128 bytes + + The equipment make is Northwind Camera. + ``` + +## Compiling the Code + +The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Handle the form's event and paste this code into the paint event handler. You must replace `FakePhoto.jpg` with an image name and path valid on your system and import the `System.Drawing.Imaging` namespace. + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-read-settings-at-run-time-with-csharp.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-read-settings-at-run-time-with-csharp.md new file mode 100644 index 0000000000..3ac7360827 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-read-settings-at-run-time-with-csharp.md @@ -0,0 +1,27 @@ +--- +title: "How To: Read Settings at Run Time With C#" +description: Learn how to read both Application-scoped and User-scoped settings at run time with C# via the Properties object. +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], reading" + - "application settings [Windows Forms], run time" + - "application settings [Windows Forms], C#" +ms.assetid: dbe8bf09-5e1c-49da-9192-154033d7240b +--- +# How To: Read Settings at Run Time With C\# + +You can read both Application-scoped and User-scoped settings at run time via the Properties object. The Properties object exposes all of the default settings for the project via the Properties.Settings.Default member in the default namespace of the project they are defined in. + +## To Read Settings at Run Time with C\# + +Access the appropriate setting via the Properties.Settings.Default member. The following example shows how to assign a setting named `myColor` to a BackColor property. It requires you to have previously created a Settings file containing a setting named `myColor` of type `System.Drawing.Color`. For information about creating a Settings file, see [How To: Create a New Setting at Design Time](how-to-create-a-new-setting-at-design-time.md). + +```csharp +this.BackColor = Properties.Settings.Default.myColor; +``` + +## See also + +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [How To: Write User Settings at Run Time with C#](how-to-write-user-settings-at-run-time-with-csharp.md) +- [Application Settings Overview](application-settings-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md new file mode 100644 index 0000000000..0409f95279 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md @@ -0,0 +1,37 @@ +--- +title: "How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls" +description: Learn how to reduce graphics flicker with double buffering for Windows Forms and use controls to address the flicker problems associated with paint operations. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "flicker [Windows Forms], reducing in Windows Forms" + - "graphics [Windows Forms], reducing double-buffered flicker" +ms.assetid: 91083d3a-653f-4f15-a467-0f37b2aa39d6 +--- +# How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls +Double buffering uses a memory buffer to address the flicker problems associated with multiple paint operations. When double buffering is enabled, all paint operations are first rendered to a memory buffer instead of the drawing surface on the screen. After all paint operations are completed, the memory buffer is copied directly to the drawing surface associated with it. Because only one graphics operation is performed on the screen, the image flickering associated with complex painting operations is eliminated.For most applications, the default double buffering provided by the .NET Framework will provide the best results. Standard Windows Forms controls are double buffered by default. You can enable default double buffering in your forms and authored controls in two ways. You can either set the property to `true`, or you can call the method to set the flag to `true`. Both methods will enable default double buffering for your form or control and provide flicker-free graphics rendering. Calling the method is recommended only for custom controls for which you have written all the rendering code. + + For more advanced double buffering scenarios, such as animation or advanced memory management, you can implement your own double buffering logic. For more information, see [How to: Manually Manage Buffered Graphics](how-to-manually-manage-buffered-graphics.md). + +### To reduce flicker + +- Set the property to `true`. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#31)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#31)] + + \- or - + +- Call the method to set the flag to `true`. + + [!code-csharp[System.Windows.Forms.LegacyBufferedGraphics#32](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs#32)] + [!code-vb[System.Windows.Forms.LegacyBufferedGraphics#32](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb#32)] + +## See also + +- +- +- [Double Buffered Graphics](double-buffered-graphics.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-render-images-with-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-render-images-with-gdi.md new file mode 100644 index 0000000000..15ba243f32 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-render-images-with-gdi.md @@ -0,0 +1,86 @@ +--- +title: "How to: Render Images with GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "images [Windows Forms], creating" + - "GDI+, rendering existing images" +ms.assetid: c128b79a-3e31-47d8-9e66-3470f570a056 +--- +# How to: Render Images with GDI+ +You can use GDI+ to render images that exist as files in your applications. You do this by creating a new object of an class (such as ), creating a object that refers to the drawing surface you want to use, and calling the method of the object. The image will be painted onto the drawing surface represented by the graphics class. You can use the Image Editor to create and edit image files at design time, and render them with GDI+ at run time. For more information, see [Image Editor for Icons](/cpp/windows/image-editor-for-icons). + +### To render an image with GDI+ + +1. Create an object representing the image you want to display. This object must be a member of a class that inherits from , such as or . An example is shown: + + ```vb + ' Uses the System.Environment.GetFolderPath to get the path to the + ' current user's MyPictures folder. + Dim myBitmap as New Bitmap _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.MyPictures)) + ``` + + ```csharp + // Uses the System.Environment.GetFolderPath to get the path to the + // current user's MyPictures folder. + Bitmap myBitmap = new Bitmap + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.MyPictures)); + ``` + + ```cpp + // Uses the System.Environment.GetFolderPath to get the path to the + // current user's MyPictures folder. + Bitmap^ myBitmap = gcnew Bitmap + (System::Environment::GetFolderPath + (System::Environment::SpecialFolder::MyPictures)); + ``` + +2. Create a object that represents the drawing surface you want to use. For more information, see [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md). + + ```vb + ' Creates a Graphics object that represents the drawing surface of + ' Button1. + Dim g as Graphics = Button1.CreateGraphics + ``` + + ```csharp + // Creates a Graphics object that represents the drawing surface of + // Button1. + Graphics g = Button1.CreateGraphics(); + ``` + + ```cpp + // Creates a Graphics object that represents the drawing surface of + // Button1. + Graphics^ g = button1->CreateGraphics(); + ``` + +3. Call the of your graphics object to render the image. You must specify both the image to be drawn, and the coordinates where it is to be drawn. + + ```vb + g.DrawImage(myBitmap, 1, 1) + ``` + + ```csharp + g.DrawImage(myBitmap, 1, 1); + ``` + + ```cpp + g->DrawImage(myBitmap, 1, 1); + ``` + +## See also + +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) +- [Pens, Lines, and Rectangles in GDI+](pens-lines-and-rectangles-in-gdi.md) +- [How to: Draw Text on a Windows Form](how-to-draw-text-on-a-windows-form.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Drawing Lines or Closed Figures](/cpp/windows/drawing-lines-or-closed-figures-image-editor-for-icons) +- [Image Editor for Icons](/cpp/windows/image-editor-for-icons) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-retrieve-data-from-the-clipboard.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-retrieve-data-from-the-clipboard.md new file mode 100644 index 0000000000..26a4d1a795 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-retrieve-data-from-the-clipboard.md @@ -0,0 +1,57 @@ +--- +title: "How to: Retrieve Data from the Clipboard" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "pasting Clipboard data" + - "Clipboard [Windows Forms], retrieving data" +ms.assetid: 99612537-2c8a-449f-aab5-2b3b28d656e7 +--- +# How to: Retrieve Data from the Clipboard + +The class provides methods that you can use to interact with the Windows operating system Clipboard feature. Many applications use the Clipboard as a temporary repository for data. For example, word processors use the Clipboard during cut-and-paste operations. The Clipboard is also useful for transferring information from one application to another. + +Some applications store data on the Clipboard in multiple formats to increase the number of other applications that can potentially use the data. A Clipboard format is a string that identifies the format. An application that uses the identified format can retrieve the associated data on the Clipboard. The class provides predefined format names for your use. You can also use your own format names or use an object's type as its format. For information about adding data to the Clipboard, see [How to: Add Data to the Clipboard](how-to-add-data-to-the-clipboard.md). + +To determine whether the Clipboard contains data in a particular format, use one of the `Contains`*Format* methods or the method. To retrieve data from the Clipboard, use one of the `Get`*Format* methods or the method. These methods are new in .NET Framework 2.0. + +To access data from the Clipboard by using versions earlier than .NET Framework 2.0, use the method and call the methods of the returned . To determine whether a particular format is available in the returned object, for example, call the method. + +> [!NOTE] +> All Windows-based applications share the system Clipboard. Therefore, the contents are subject to change when you switch to another application. +> +> The class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your `Main` method is marked with the attribute. + +### To retrieve data from the Clipboard in a single, common format + +1. Use the , , , or method. Optionally, use the corresponding `Contains`*Format* methods first to determine whether data is available in a particular format. These methods are available only in .NET Framework 2.0. + + [!code-csharp[System.Windows.Forms.Clipboard#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#2)] + [!code-vb[System.Windows.Forms.Clipboard#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#2)] + +### To retrieve data from the Clipboard in a custom format + +1. Use the method with a custom format name. This method is available only in .NET Framework 2.0. + + You can also use predefined format names with the method. For more information, see . + + [!code-csharp[System.Windows.Forms.Clipboard#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#3)] + [!code-vb[System.Windows.Forms.Clipboard#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#3)] + [!code-csharp[System.Windows.Forms.Clipboard#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#100)] + [!code-vb[System.Windows.Forms.Clipboard#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#100)] + +### To retrieve data from the Clipboard in multiple formats + +1. Use the method. You must use this method to retrieve data from the Clipboard on versions earlier than .NET Framework 2.0. + + [!code-csharp[System.Windows.Forms.Clipboard#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#4)] + [!code-vb[System.Windows.Forms.Clipboard#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#4)] + [!code-csharp[System.Windows.Forms.Clipboard#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs#100)] + [!code-vb[System.Windows.Forms.Clipboard#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb#100)] + +## See also + +- [Drag-and-Drop Operations and Clipboard Support](drag-and-drop-operations-and-clipboard-support.md) +- [How to: Add Data to the Clipboard](how-to-add-data-to-the-clipboard.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-rotate-colors.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-rotate-colors.md new file mode 100644 index 0000000000..fbdae03000 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-rotate-colors.md @@ -0,0 +1,49 @@ +--- +title: "How to: Rotate Colors" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "colors [Windows Forms], rotating" + - "examples [Windows Forms], rotating colors" +ms.assetid: e2e4c300-159c-4f4a-9b56-103b0f7cbc05 +--- +# How to: Rotate Colors +Rotation in a four-dimensional color space is difficult to visualize. We can make it easier to visualize rotation by agreeing to keep one of the color components fixed. Suppose we agree to keep the alpha component fixed at 1 (fully opaque). Then we can visualize a three-dimensional color space with red, green, and blue axes as shown in the following illustration. + + ![Illustration that shows rotation with red, green, and blue axes.](./media/how-to-rotate-colors/rotation-red-green-blue-axes.gif) + + A color can be thought of as a point in 3D space. For example, the point (1, 0, 0) in space represents the color red, and the point (0, 1, 0) in space represents the color green. + + The following illustration shows what it means to rotate the color (1, 0, 0) through an angle of 60 degrees in the Red-Green plane. Rotation in a plane parallel to the Red-Green plane can be thought of as rotation about the blue axis. + + ![Illustration that shows rotation about the blue axis.](./media/how-to-rotate-colors/rotation-about-blue-axis.gif) + + The following illustration shows how to initialize a color matrix to perform rotations about each of the three coordinate axes (red, green, blue): + + ![Initialize a color matrix to perform rotations about three axes.](./media/how-to-rotate-colors/rotation-about-three-axes.gif) + +## Example + The following example takes an image that is all one color (1, 0, 0.6) and applies a 60-degree rotation about the blue axis. The angle of the rotation is swept out in a plane that is parallel to the red-green plane. + + The following illustration shows the original image on the left and the color-rotated image on the right: + + ![Illustration that shows original image and color-rotated image.](./media/how-to-rotate-colors/original-color-rotated-images.png) + + The following illustration shows a visualization of the color rotation performed in the following code: + + ![Illustration that shows the visualization of the color rotation.](./media/how-to-rotate-colors/visualization-color-rotation.gif) + + [!code-csharp[System.Drawing.RotateColors#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RotateColors/CS/Form1.cs#1)] + [!code-vb[System.Drawing.RotateColors#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RotateColors/VB/Form1.vb#1)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Replace `RotationInput.bmp` with an image file name and path valid on your system. + +## See also + +- +- +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Recoloring Images](recoloring-images.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-rotate-reflect-and-skew-images.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-rotate-reflect-and-skew-images.md new file mode 100644 index 0000000000..0441dca44d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-rotate-reflect-and-skew-images.md @@ -0,0 +1,47 @@ +--- +title: "How to: Rotate, Reflect, and Skew Images" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "images [Windows Forms], reflecting" + - "images [Windows Forms], rotating" + - "images [Windows Forms], skewing" +ms.assetid: a3bf97eb-63ed-425a-ba07-dcc65efb567c +--- +# How to: Rotate, Reflect, and Skew Images +You can rotate, reflect, and skew an image by specifying destination points for the upper-left, upper-right, and lower-left corners of the original image. The three destination points determine an affine transformation that maps the original rectangular image to a parallelogram. + +## Example + For example, suppose the original image is a rectangle with upper-left corner at (0, 0), upper-right corner at (100, 0), and lower-left corner at (0, 50). Now suppose you map those three points to destination points as follows. + +|Original point|Destination point| +|--------------------|-----------------------| +|Upper-left (0, 0)|(200, 20)| +|Upper-right (100, 0)|(110, 100)| +|Lower-left (0, 50)|(250, 30)| + + The following illustration shows the original image and the image mapped to the parallelogram. The original image has been skewed, reflected, rotated, and translated. The x-axis along the top edge of the original image is mapped to the line that runs through (200, 20) and (110, 100). The y-axis along the left edge of the original image is mapped to the line that runs through (200, 20) and (250, 30). + + ![The original image and the image mapped to the parallelogram.](./media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-illustration.gif) + + The following illustration shows a similar transformation applied to a photographic image: + + ![The picture of a climber and the picture mapped to the parallelogram.](./media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-photo.png) + + The following illustration shows a similar transformation applied to a metafile: + + ![Illustration of shapes and text and that mapped to the parallelogram.](./media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-metafile.png) + + The following example produces the images shown in the first illustration. + + [!code-csharp[System.Drawing.WorkingWithImages#61](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#61)] + [!code-vb[System.Drawing.WorkingWithImages#61](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#61)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Make sure to replace `Stripes.bmp` with the path to an image that is valid on your system. + +## See also + +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-send-data-to-the-active-mdi-child.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-send-data-to-the-active-mdi-child.md new file mode 100644 index 0000000000..595d6c7e57 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-send-data-to-the-active-mdi-child.md @@ -0,0 +1,94 @@ +--- +title: "How to: Send Data to the Active MDI Child" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "child forms" + - "MDI [Windows Forms], sending data to forms" + - "Clipboard [Windows Forms], pasting" + - "Clipboard [Windows Forms], getting data from" +ms.assetid: 1047d2fe-1235-46db-aad9-563aea1d743b +--- +# How to: Send Data to the Active MDI Child +Often, within the context of [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md), you will need to send data to the active child window, such as when the user pastes data from the Clipboard into an MDI application. + +> [!NOTE] +> For information about verifying which child window has focus and sending its contents to the Clipboard, see [Determining the Active MDI Child](how-to-determine-the-active-mdi-child.md). + +### To send data to the active MDI child window from the Clipboard + +1. Within a method, copy the text on the Clipboard to the active control of the active child form. + + > [!NOTE] + > This example assumes there is an MDI parent form (`Form1`) that has one or more MDI child windows containing a control. For more information, see [Creating MDI Parent Forms](how-to-create-mdi-parent-forms.md). + + ```vb + Public Sub mniPaste_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles mniPaste.Click + + ' Determine the active child form. + Dim activeChild As Form = Me.ParentForm.ActiveMDIChild + + ' If there is an active child form, find the active control, which + ' in this example should be a RichTextBox. + If (Not activeChild Is Nothing) Then + Try + Dim theBox As RichTextBox = Ctype(activeChild.ActiveControl, RichTextBox) + If (Not theBox Is Nothing) Then + ' Create a new instance of the DataObject interface. + Dim data As IDataObject = Clipboard.GetDataObject() + ' If the data is text, then set the text of the + ' RichTextBox to the text in the clipboard. + If (data.GetDataPresent(DataFormats.Text)) Then + theBox.SelectedText = data.GetData(DataFormats.Text).ToString() + End If + End If + Catch + MessageBox.Show("You need to select a RichTextBox.") + End Try + End If + End Sub + ``` + + ```csharp + protected void mniPaste_Click (object sender, System.EventArgs e) + { + // Determine the active child form. + Form activeChild = this.ParentForm.ActiveMdiChild; + + // If there is an active child form, find the active control, which + // in this example should be a RichTextBox. + if (activeChild != null) + { + try + { + RichTextBox theBox = (RichTextBox)activeChild.ActiveControl; + if (theBox != null) + { + // Create a new instance of the DataObject interface. + IDataObject data = Clipboard.GetDataObject(); + // If the data is text, then set the text of the + // RichTextBox to the text in the clipboard. + if (data.GetDataPresent(DataFormats.Text)) + { + theBox.SelectedText = data.GetData(DataFormats.Text).ToString(); + } + } + } + catch + { + MessageBox.Show("You need to select a RichTextBox."); + } + } + } + ``` + +## See also + +- [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md) +- [How to: Create MDI Parent Forms](how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](how-to-create-mdi-child-forms.md) +- [How to: Determine the Active MDI Child](how-to-determine-the-active-mdi-child.md) +- [How to: Arrange MDI Child Forms](how-to-arrange-mdi-child-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-jpeg-compression-level.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-jpeg-compression-level.md new file mode 100644 index 0000000000..8574eed6cd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-jpeg-compression-level.md @@ -0,0 +1,131 @@ +--- +title: "How to: Set JPEG Compression Level" +description: Learn how to adjust the quality of a JPEG image by modifying its compression level on Windows Forms. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "images [Windows Forms], changing encoder parameters" + - "JPEG images [Windows Forms], setting quality level" +ms.assetid: 4b9a74e3-9504-43c1-9f28-ace651d0772e +--- +# How to: Set JPEG Compression Level +You may want to modify the parameters of an image when you save the image to disk to minimize the file size or improve its quality. You can adjust the quality of a JPEG image by modifying its compression level. To specify the compression level when you save a JPEG image, you must create an object and pass it to the method of the class. Initialize the object so that it has an array that consists of one . When you create the , specify the encoder, and the desired compression level. + +## Example + The following example code creates an object and saves three JPEG images. Each JPEG image is saved with a different quality level, by modifying the `long` value passed to the constructor. A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression. + +```csharp +private void VaryQualityLevel() + { + // Get a bitmap. The using statement ensures objects + // are automatically disposed from memory after use. + using (Bitmap bmp1 = new Bitmap(@"C:\TestPhoto.jpg")) + { + ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); + + // Create an Encoder object based on the GUID + // for the Quality parameter category. + System.Drawing.Imaging.Encoder myEncoder = + System.Drawing.Imaging.Encoder.Quality; + + // Create an EncoderParameters object. + // An EncoderParameters object has an array of EncoderParameter + // objects. In this case, there is only one + // EncoderParameter object in the array. + EncoderParameters myEncoderParameters = new EncoderParameters(1); + + EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); + myEncoderParameters.Param[0] = myEncoderParameter; + bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters); + + myEncoderParameter = new EncoderParameter(myEncoder, 100L); + myEncoderParameters.Param[0] = myEncoderParameter; + bmp1.Save(@"C:\TestPhotoQualityHundred.jpg", jpgEncoder, myEncoderParameters); + + // Save the bitmap as a JPG file with zero quality level compression. + myEncoderParameter = new EncoderParameter(myEncoder, 0L); + myEncoderParameters.Param[0] = myEncoderParameter; + bmp1.Save(@"C:\TestPhotoQualityZero.jpg", jpgEncoder, myEncoderParameters); + } + } +``` + +```vb +Private Sub VaryQualityLevel() + ' Get a bitmap. The Using statement ensures objects + ' are automatically disposed from memory after use. + Using bmp1 As New Bitmap("C:\test\TestPhoto.jpg") + Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg) + + ' Create an Encoder object based on the GUID + ' for the Quality parameter category. + Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality + + ' Create an EncoderParameters object. + ' An EncoderParameters object has an array of EncoderParameter + ' objects. In this case, there is only one + ' EncoderParameter object in the array. + Dim myEncoderParameters As New EncoderParameters(1) + + Dim myEncoderParameter As New EncoderParameter(myEncoder, 50L) + myEncoderParameters.Param(0) = myEncoderParameter + bmp1.Save("c:\test\TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters) + + myEncoderParameter = New EncoderParameter(myEncoder, 100L) + myEncoderParameters.Param(0) = myEncoderParameter + bmp1.Save("C:\test\TestPhotoQualityHundred.jpg", jpgEncoder, myEncoderParameters) + + ' Save the bitmap as a JPG file with zero quality level compression. + myEncoderParameter = New EncoderParameter(myEncoder, 0L) + myEncoderParameters.Param(0) = myEncoderParameter + bmp1.Save("C:\test\TestPhotoQualityZero.jpg", jpgEncoder, myEncoderParameters) + End Using +End Sub +``` + +```csharp +private ImageCodecInfo GetEncoder(ImageFormat format) +{ + ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); + foreach (ImageCodecInfo codec in codecs) + { + if (codec.FormatID == format.Guid) + { + return codec; + } + } + return null; +} +``` + +```vb +Private Function GetEncoder(ByVal format As ImageFormat) As ImageCodecInfo + + Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageDecoders() + Dim codec As ImageCodecInfo + For Each codec In codecs + If codec.FormatID = format.Guid Then + Return codec + End If + Next codec + Return Nothing + +End Function +``` + +## Compiling the Code + This example requires: + +- A Windows Forms application. + +- A , which is a parameter of . + +- An image file that is named `TestPhoto.jpg` and located at **c:\\**. + +## See also + +- [How to: Determine the Parameters Supported by an Encoder](how-to-determine-the-parameters-supported-by-an-encoder.md) +- [Types of Bitmaps](types-of-bitmaps.md) +- [Using Image Encoders and Decoders in Managed GDI+](using-image-encoders-and-decoders-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-pen-width-and-alignment.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-pen-width-and-alignment.md new file mode 100644 index 0000000000..591a7d19d3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-pen-width-and-alignment.md @@ -0,0 +1,57 @@ +--- +title: "How to: Set Pen Width and Alignment" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "pens [Windows Forms], setting width" + - "pens [Windows Forms], setting alignment" +ms.assetid: a202af36-4d31-4401-a126-b232f51db581 +--- +# How to: Set Pen Width and Alignment +When you create a , you can supply the pen width as one of the arguments to the constructor. You can also change the pen width with the property of the class. + + A theoretical line has a width of 0. When you draw a line that is 1 pixel wide, the pixels are centered on the theoretical line. If you draw a line that is more than one pixel wide, the pixels are either centered on the theoretical line or appear to one side of the theoretical line. You can set the pen alignment property of a to determine how the pixels drawn with that pen will be positioned relative to theoretical lines. + + The values , , and that appear in the following code examples are members of the enumeration. + + The following code example draws a line twice: once with a black pen of width 1 and once with a green pen of width 10. + +### To vary the width of a pen + +- Set the value of the property to (the default) to specify that pixels drawn with the green pen will be centered on the theoretical line. The following illustration shows the resulting line. + + ![A black thin line with green highlight.](./media/how-to-set-pen-width-and-alignment/green-pixels-centered-line.gif) + + The following code example draws a rectangle twice: once with a black pen of width 1 and once with a green pen of width 10. + + [!code-csharp[System.Drawing.UsingAPen#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#41)] + [!code-vb[System.Drawing.UsingAPen#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#41)] + +### To change the alignment of a pen + +- Set the value of the property to to specify that the pixels drawn with the green pen will be centered on the boundary of the rectangle. + + The following illustration shows the resulting rectangle: + + ![A rectangle drawn with black thin lines with green highlight.](./media/how-to-set-pen-width-and-alignment/green-pixels-centered-rectangle.gif) + + [!code-csharp[System.Drawing.UsingAPen#42](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#42)] + [!code-vb[System.Drawing.UsingAPen#42](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#42)] + +### To create an inset pen + +- Change the green pen's alignment by modifying the third statement in the preceding code example as follows: + + [!code-csharp[System.Drawing.UsingAPen#43](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#43)] + [!code-vb[System.Drawing.UsingAPen#43](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#43)] + + Now the pixels in the wide green line appear on the inside of the rectangle as shown in the following illustration: + + ![A rectangle drawn with black lines with the wide green line inside.](./media/how-to-set-pen-width-and-alignment/green-pixels-inside-rectangle.gif) + +## See also + +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-tab-stops-in-drawn-text.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-tab-stops-in-drawn-text.md new file mode 100644 index 0000000000..572852bf69 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-tab-stops-in-drawn-text.md @@ -0,0 +1,37 @@ +--- +title: "How to: Set Tab Stops in Drawn Text" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "text [Windows Forms], drawing with tab stops" + - "tabs [Windows Forms], drawn text" +ms.assetid: 64878f98-39ba-4303-b63f-0859ab682eeb +--- +# How to: Set Tab Stops in Drawn Text +You can set tab stops for text by calling the method of a object and then passing that object to the method of the class. + +> [!NOTE] +> The does not support adding tab stops to drawn text, although you can expand existing tab stops using the flag. + +## Example + The following example sets tab stops at 150, 250, and 350. Then, the code displays a tabbed list of names and test scores. + + The following illustration shows the tabbed text: + + ![Screenshot that shows a tabbed list of names and scores.](./media/how-to-set-tab-stops-in-drawn-text/tab-list-names-test-scores.png) + + The following code passes two arguments to the method. The second argument is an array that contains tab offsets. The first argument passed to is 0, which indicates that the first offset in the array is measured from position 0, the left edge of the bounding rectangle. + + [!code-csharp[System.Drawing.FontsAndText#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#41)] + [!code-vb[System.Drawing.FontsAndText#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#41)] + +## Compiling the Code + +- The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Using Fonts and Text](using-fonts-and-text.md) +- [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-the-color-of-a-pen.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-the-color-of-a-pen.md new file mode 100644 index 0000000000..77b0ed7d68 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-set-the-color-of-a-pen.md @@ -0,0 +1,35 @@ +--- +title: "How to: Set the Color of a Pen" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "pens [Windows Forms], setting color" + - "colored pens" +ms.assetid: a9df06f9-a6d5-4d9b-a2d1-583943540775 +--- +# How to: Set the Color of a Pen +This example changes the color of a pre-existing object + +## Example + [!code-cpp[System.Drawing.ConceptualHowTos#9](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp#9)] + [!code-csharp[System.Drawing.ConceptualHowTos#9](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs#9)] + [!code-vb[System.Drawing.ConceptualHowTos#9](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb#9)] + +## Compiling the Code + This example requires: + +- A object named `myPen`. + +## Robust Programming + You should call on objects that consume system resources (such as objects) after you are finished using them. + +## See also + +- +- [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) +- [How to: Create a Pen](how-to-create-a-pen.md) +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Pens, Lines, and Rectangles in GDI+](pens-lines-and-rectangles-in-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-shear-colors.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-shear-colors.md new file mode 100644 index 0000000000..a71df3cffd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-shear-colors.md @@ -0,0 +1,42 @@ +--- +title: "How to: Shear Colors" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "colors [Windows Forms], transforming with color matrices" + - "colors [Windows Forms], shearing" +ms.assetid: 0a424171-5b8b-45c4-afef-e9720a6c3e22 +--- +# How to: Shear Colors +Shearing increases or decreases a color component by an amount proportional to another color component. For example, consider the transformation where the red component is increased by one half the value of the blue component. Under such a transformation, the color (0.2, 0.5, 1) would become (0.7, 0.5, 1). The new red component is 0.2 + (1/2)(1) = 0.7. + +## Example + The following example constructs an object from the file ColorBars4.bmp. Then the code applies the shearing transformation described in the preceding paragraph to each pixel in the image. + + The following illustration shows the original image on the left and the sheared image on the right: + + ![Two squares with colored stripes side-by-side illustrating the original image and the sheared image.](./media/how-to-shear-colors/original-image-sheared-image.png) + + The following table lists the color vectors for the four bars before and after the shearing transformation. + +|Original|Sheared| +|--------------|-------------| +|(0, 0, 1, 1)|(0.5, 0, 1, 1)| +|(0.5, 1, 0.5, 1)|(0.75, 1, 0.5, 1)| +|(1, 1, 0, 1)|(1, 1, 0, 1)| +|(0.4, 0.4, 0.4, 1)|(0.6, 0.4, 0.4, 1)| + + [!code-csharp[System.Drawing.Misc3#9](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Misc3/CS/Form1.cs#9)] + [!code-vb[System.Drawing.Misc3#9](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Misc3/VB/Form1.vb#9)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Replace `ColorBars.bmp` with an image name and path valid on your system. + +## See also + +- +- +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Recoloring Images](recoloring-images.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md new file mode 100644 index 0000000000..a756202277 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md @@ -0,0 +1,50 @@ +--- +title: "How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread" +ms.date: "03/30/2017" +dev_langs: + - "vb" +helpviewer_keywords: + - "COM interop [Windows Forms], Windows Forms" + - "COM [Windows Forms]" + - "Windows Forms, unmanaged" + - "ActiveX controls [Windows Forms], COM interop" + - "Windows Forms, interop" +ms.assetid: a9e04765-d2de-4389-a494-a9a6d07aa6ee +--- +# How to: Support COM interop by displaying each Windows Form on its own thread + +You can resolve COM interoperability problems by displaying your form on a .NET Framework message loop, which you can create by using the method. + +To make a Windows Form work correctly from a COM client application, you must run the form on a Windows Forms message loop. To do this, use one of the following approaches: + +- Use the method to display the Windows Form. For more information, see [How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method](com-interop-by-displaying-a-windows-form-shadow.md). + +- Display each Windows Form on a separate thread. + +There is extensive support for this feature in Visual Studio. + +Also see [Walkthrough: Supporting COM Interop by Displaying Each Windows Form on Its Own Thread](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233639(v=vs.100)). + +## Example + +The following code example demonstrates how to display the form on a separate thread and call the method to start a Windows Forms message pump on that thread. To use this approach, you must marshal any calls to the form from the unmanaged application by using the method. + +This approach requires that each instance of a form runs on its own thread by using its own message loop. You cannot have more than one message loop running per thread. Therefore, you cannot change the client application's message loop. However, you can modify the .NET Framework component to start a new thread that uses its own message loop. + +[!code-vb[System.Windows.Forms.ComInterop#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/COMForm.vb#1)] + +[!code-vb[System.Windows.Forms.ComInterop#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/FormManager.vb#10)] + +[!code-vb[System.Windows.Forms.ComInterop#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/Form1.vb#100)] + +## Compile the code + +Compile the `COMForm`, `Form1`, and `FormManager` types into an assembly called `COMWinform.dll`. Register the assembly for COM interop by using one of the methods described in [Packaging an Assembly for COM](https://docs.microsoft.com/dotnet/framework/interop/packaging-an-assembly-for-co). You can now use the assembly and its corresponding type library (.tlb) file in unmanaged applications. For example, you can use the type library as a reference in a Visual Basic 6.0 executable project. + +## See also + +- [Exposing .NET Framework Components to COM](https://docs.microsoft.com/dotnet/framework/interop/exposing-dotnet-components-to-co) +- [Packaging an Assembly for COM](https://docs.microsoft.com/dotnet/framework/interop/packaging-an-assembly-for-co) +- [Registering Assemblies with COM](https://docs.microsoft.com/dotnet/framework/interop/registering-assemblies-with-co) +- [How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method](com-interop-by-displaying-a-windows-form-shadow.md) +- [Windows Forms and Unmanaged Applications Overview](windows-forms-and-unmanaged-applications-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-tile-a-shape-with-an-image.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-tile-a-shape-with-an-image.md new file mode 100644 index 0000000000..799058f8e2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-tile-a-shape-with-an-image.md @@ -0,0 +1,59 @@ +--- +title: "How to: Tile a Shape with an Image" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "texture brushes [Windows Forms], tiling images with" + - "images [Windows Forms], filling shapes with" + - "shapes [Windows Forms], tiling with images" + - "bitmaps [Windows Forms], filling shapes with" +ms.assetid: 6d407891-6e5c-4495-a546-3da5604e9fb8 +--- +# How to: Tile a Shape with an Image +Just as tiles can be placed next to each other to cover a floor, rectangular images can be placed next to each other to fill (tile) a shape. To tile the interior of a shape, use a texture brush. When you construct a object, one of the arguments you pass to the constructor is an object. When you use the texture brush to paint the interior of a shape, the shape is filled with repeated copies of this image. + + The wrap mode property of the object determines how the image is oriented as it is repeated in a rectangular grid. You can make all the tiles in the grid have the same orientation, or you can make the image flip from one grid position to the next. The flipping can be horizontal, vertical, or both. The following examples demonstrate tiling with different types of flipping. + +### To tile an image + +- This example uses the following 75×75 image to tile a 200×200 rectangle. + + ![The tile image that shows a red house and a tree.](./media/how-to-tile-a-shape-with-an-image/rectangle-tile-200x200.gif) + +- The following illustration shows how the rectangle is tiled with the image. Note that all tiles have the same orientation; there is no flipping. + + ![A rectangle tiled with the image using the same orientation for all tiles.](./media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-no-flip.gif) + + [!code-csharp[System.Drawing.UsingABrush#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#31)] + [!code-vb[System.Drawing.UsingABrush#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#31)] + +### To flip an image horizontally while tiling + +- This example uses the same 75×75 image to fill a 200×200 rectangle. The wrap mode is set to flip the image horizontally. The following illustration shows how the rectangle is tiled with the image. Note that as you move from one tile to the next in a given row, the image is flipped horizontally. + + ![A rectangle tiled with the image flipped horizontally.](./media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-flip.gif) + + [!code-csharp[System.Drawing.UsingABrush#32](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#32)] + [!code-vb[System.Drawing.UsingABrush#32](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#32)] + +### To flip an image vertically while tiling + +- This example uses the same 75×75 image to fill a 200×200 rectangle. The wrap mode is set to flip the image vertically. + + [!code-csharp[System.Drawing.UsingABrush#33](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#33)] + [!code-vb[System.Drawing.UsingABrush#33](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#33)] + +### To flip an image horizontally and vertically while tiling + +- This example uses the same 75×75 image to tile a 200×200 rectangle. The wrap mode is set to flip the image both horizontally and vertically. The following illustration shows how the rectangle is tiled by the image. Note that as you move from one tile to the next in a given row, the image is flipped horizontally, and as you move from one tile to the next in a given column, the image is flipped vertically. + + ![A rectangle tiled with the image flipped horizontally and vertically.](./media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-vertical-flip.gif) + + [!code-csharp[System.Drawing.UsingABrush#34](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs#34)] + [!code-vb[System.Drawing.UsingABrush#34](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb#34)] + +## See also + +- [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-translate-image-colors.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-translate-image-colors.md new file mode 100644 index 0000000000..b0cd0b7cc7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-translate-image-colors.md @@ -0,0 +1,50 @@ +--- +title: "How to: Translate Image Colors" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "bitmaps [Windows Forms], changing colors" + - "images [Windows Forms], changing colors" + - "image colors [Windows Forms]" +ms.assetid: 2106fb9a-4d60-4dcf-9220-9f189a6c4d19 +--- +# How to: Translate Image Colors +A translation adds a value to one or more of the four color components. The color matrix entries that represent translations are given in the following table. + +|Component to be translated|Matrix entry| +|--------------------------------|------------------| +|Red|[4][0]| +|Green|[4][1]| +|Blue|[4][2]| +|Alpha|[4][3]| + +## Example + The following example constructs an object from the file ColorBars.bmp. Then the code adds 0.75 to the red component of each pixel in the image. The original image is drawn alongside the transformed image. + + The following illustration shows the original image on the left and the transformed image on the right: + + ![Screenshot of the original and transformed image.](./media/how-to-translate-image-colors/original-image-translate-colors.png) + + The following table lists the color vectors for the four bars before and after the red translation. Note that because the maximum value for a color component is 1, the red component in the second row does not change. (Similarly, the minimum value for a color component is 0.) + +|Original|Translated| +|--------------|----------------| +|Black (0, 0, 0, 1)|(0.75, 0, 0, 1)| +|Red (1, 0, 0, 1)|(1, 0, 0, 1)| +|Green (0, 1, 0, 1)|(0.75, 1, 0, 1)| +|Blue (0, 0, 1, 1)|(0.75, 0, 1, 1)| + + [!code-csharp[System.Drawing.RecoloringImages#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs#11)] + [!code-vb[System.Drawing.RecoloringImages#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. Replace `ColorBars.bmp` with an image file name and path that are valid on your system. + +## See also + +- +- +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Recoloring Images](recoloring-images.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-matrix-to-set-alpha-values-in-images.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-matrix-to-set-alpha-values-in-images.md new file mode 100644 index 0000000000..fc9bb3d29a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-matrix-to-set-alpha-values-in-images.md @@ -0,0 +1,35 @@ +--- +title: "How to: Use a Color Matrix to Set Alpha Values in Images" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "images [Windows Forms], using color matrices for semi-transparent" + - "transparency [Windows Forms], color matrices" + - "matrices [Windows Forms], alpha values" + - "bitmaps [Windows Forms], using color matrices for semi-transparent" +ms.assetid: a27121e6-f7e9-4c09-84e2-f05aa9d2a1bb +--- +# How to: Use a Color Matrix to Set Alpha Values in Images +The class (which inherits from the class) and the class provide functionality for getting and setting pixel values. You can use the class to modify the alpha values for an entire image, or you can call the method of the class to modify individual pixel values. + +## Example + The class has many properties that you can use to modify images during rendering. In the following example, an object is used to set all the alpha values to 80 percent of what they were. This is done by initializing a color matrix and setting the alpha scaling value in the matrix to 0.8. The address of the color matrix is passed to the method of the object, and the object is passed to the method of the object. + + During rendering, the alpha values in the bitmap are converted to 80 percent of what they were. This results in an image that is blended with the background. As the following illustration shows, the bitmap image looks transparent; you can see the solid black line through it. + + ![Screenshot of alpha blending using a matrix.](./media/how-to-use-a-color-matrix-to-set-alpha-values-in-images/alpha-blending-matrix.png "image2") + + Where the image is over the white portion of the background, the image has been blended with the color white. Where the image crosses the black line, the image is blended with the color black. + + [!code-csharp[System.Drawing.AlphaBlending#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs#21)] + [!code-vb[System.Drawing.AlphaBlending#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb#21)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Alpha Blending Lines and Fills](alpha-blending-lines-and-fills.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-matrix-to-transform-a-single-color.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-matrix-to-transform-a-single-color.md new file mode 100644 index 0000000000..902fbd7a9a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-matrix-to-transform-a-single-color.md @@ -0,0 +1,63 @@ +--- +title: "How to: Use a Color Matrix to Transform a Single Color" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "image colors [Windows Forms], transforming" + - "color matrices [Windows Forms], using" +ms.assetid: 44df4556-a433-49c0-ac0f-9a12063a5860 +--- +# How to: Use a Color Matrix to Transform a Single Color +GDI+ provides the and classes for storing and manipulating images. and objects store the color of each pixel as a 32-bit number: 8 bits each for red, green, blue, and alpha. Each of the four components is a number from 0 through 255, with 0 representing no intensity and 255 representing full intensity. The alpha component specifies the transparency of the color: 0 is fully transparent, and 255 is fully opaque. + + A color vector is a 4-tuple of the form (red, green, blue, alpha). For example, the color vector (0, 255, 0, 255) represents an opaque color that has no red or blue, but has green at full intensity. + + Another convention for representing colors uses the number 1 for full intensity. Using that convention, the color described in the preceding paragraph would be represented by the vector (0, 1, 0, 1). GDI+ uses the convention of 1 as full intensity when it performs color transformations. + + You can apply linear transformations (rotation, scaling, and the like) to color vectors by multiplying the color vectors by a 4×4 matrix. However, you cannot use a 4×4 matrix to perform a translation (nonlinear). If you add a dummy fifth coordinate (for example, the number 1) to each of the color vectors, you can use a 5×5 matrix to apply any combination of linear transformations and translations. A transformation consisting of a linear transformation followed by a translation is called an affine transformation. + + For example, suppose you want to start with the color (0.2, 0.0, 0.4, 1.0) and apply the following transformations: + +1. Double the red component + +2. Add 0.2 to the red, green, and blue components + + The following matrix multiplication will perform the pair of transformations in the order listed. + + ![Screenshot of a transformation multiplication matrix.](./media/how-to-use-a-color-matrix-to-transform-a-single-color/multiplication-color-matrix.gif) + + The elements of a color matrix are indexed (zero-based) by row and then column. For example, the entry in the fifth row and third column of matrix M is denoted by M[4][2]. + + The 5×5 identity matrix (shown in the following illustration) has 1s on the diagonal and 0s everywhere else. If you multiply a color vector by the identity matrix, the color vector does not change. A convenient way to form the matrix of a color transformation is to start with the identity matrix and make a small change that produces the desired transformation. + + ![Screenshot of a 5x5 identity matrix for color transformation.](./media/how-to-use-a-color-matrix-to-transform-a-single-color/5x5-identity-matrix-color-transformation.gif) + + For a more detailed discussion of matrices and transformations, see [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md). + +## Example + The following example takes an image that is all one color (0.2, 0.0, 0.4, 1.0) and applies the transformation described in the preceding paragraphs. + + The following illustration shows the original image on the left and the transformed image on the right. + + ![A purple square on the left and a fuchsia square on the right.](./media/how-to-use-a-color-matrix-to-transform-a-single-color/color-transformation.png) + + The code in the following example uses the following steps to perform the recoloring: + +1. Initialize a object. + +2. Create an object and pass the object to the method of the object. + +3. Pass the object to the method of a object. + + [!code-csharp[System.Drawing.RecoloringImages#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs#21)] + [!code-vb[System.Drawing.RecoloringImages#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb#21)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Recoloring Images](recoloring-images.md) +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-remap-table.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-remap-table.md new file mode 100644 index 0000000000..ebbf13f8b1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-color-remap-table.md @@ -0,0 +1,36 @@ +--- +title: "How to: Use a Color Remap Table" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "color tables [Windows Forms], remapping colors with" + - "custom colors [Windows Forms], creating with color remap table" + - "color remap tables [Windows Forms], using" +ms.assetid: 977df1ce-8665-42d4-9fb1-ef7f0ff63419 +--- +# How to: Use a Color Remap Table +Remapping is the process of converting the colors in an image according to a color remap table. The color remap table is an array of objects. Each object in the array has an property and a property. + + When GDI+ draws an image, each pixel of the image is compared to the array of old colors. If a pixel's color matches an old color, its color is changed to the corresponding new color. The colors are changed only for rendering — the color values of the image itself (stored in an or object) are not changed. + + To draw a remapped image, initialize an array of objects. Pass that array to the method of an object, and then pass the object to the method of a object. + +## Example + The following example creates an object from the file RemapInput.bmp. The code creates a color remap table that consists of a single object. The property of the `ColorRemap` object is red, and the property is blue. The image is drawn once without remapping and once with remapping. The remapping process changes all the red pixels to blue. + + The following illustration shows the original image on the left and the remapped image on the right. + + ![Screenshot showing the original image and the remapped image.](./media/how-to-use-a-color-remap-table/original-image-remap-colors.png) + + [!code-csharp[System.Drawing.RecoloringImages#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs#31)] + [!code-vb[System.Drawing.RecoloringImages#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb#31)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Recoloring Images](recoloring-images.md) +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-pen-to-draw-lines.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-pen-to-draw-lines.md new file mode 100644 index 0000000000..2fa8b7925d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-pen-to-draw-lines.md @@ -0,0 +1,28 @@ +--- +title: "How to: Use a Pen to Draw Lines" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "lines [Windows Forms], drawing" + - "pens [Windows Forms], drawing lines" +ms.assetid: 0828c331-a438-4bdd-a4d6-3ef1e59e8795 +--- +# How to: Use a Pen to Draw Lines +To draw lines, you need a object and a object. The object provides the method, and the object stores features of the line, such as color and width. + +## Example + The following example draws a line from (20, 10) to (300, 100). The first statement uses the class constructor to create a black pen. The one argument passed to the constructor is a object created with the method. The values used to create the object — (255, 0, 0, 0) — correspond to the alpha, red, green, and blue components of the color. These values define an opaque black pen. + + [!code-csharp[System.Drawing.UsingAPen#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#11)] + [!code-vb[System.Drawing.UsingAPen#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#11)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) +- [Pens, Lines, and Rectangles in GDI+](pens-lines-and-rectangles-in-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-pen-to-draw-rectangles.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-pen-to-draw-rectangles.md new file mode 100644 index 0000000000..768e1f5f64 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-a-pen-to-draw-rectangles.md @@ -0,0 +1,32 @@ +--- +title: "How to: Use a Pen to Draw Rectangles" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "rectangles [Windows Forms], drawing" + - "pens [Windows Forms], drawing rectangles" +ms.assetid: 54a7fa14-3ad8-4d64-b424-2a12005b250c +--- +# How to: Use a Pen to Draw Rectangles +To draw rectangles, you need a object and a object. The object provides the method, and the object stores features of the line, such as color and width. + +## Example + The following example draws a rectangle with its upper-left corner at (10, 10). The rectangle has a width of 100 and a height of 50. The second argument passed to the constructor indicates that the pen width is 5 pixels. + + When the rectangle is drawn, the pen is centered on the rectangle's boundary. Because the pen width is 5, the sides of the rectangle are drawn 5 pixels wide, such that 1 pixel is drawn on the boundary itself, 2 pixels are drawn on the inside, and 2 pixels are drawn on the outside. For more details on pen alignment, see [How to: Set Pen Width and Alignment](how-to-set-pen-width-and-alignment.md). + + The following illustration shows the resulting rectangle. The dotted lines show where the rectangle would have been drawn if the pen width had been one pixel. The enlarged view of the upper-left corner of the rectangle shows that the thick black lines are centered on those dotted lines. + + ![Screenshot showing the drawn rectangle with black and dotted lines.](./media/how-to-use-a-pen-to-draw-rectangles/drawn-rectangle-black-lines-dotted-lines.gif) + + [!code-csharp[System.Drawing.UsingAPen#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs#21)] + [!code-vb[System.Drawing.UsingAPen#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb#21)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-antialiasing-with-text.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-antialiasing-with-text.md new file mode 100644 index 0000000000..31d18a2777 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-antialiasing-with-text.md @@ -0,0 +1,33 @@ +--- +title: "How to: Use Antialiasing with Text" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "strings [Windows Forms], smoothing drawn" + - "antialiasing [Windows Forms], using with text" + - "text [Windows Forms], smoothing" + - "text [Windows Forms], antialiasing" + - "strings [Windows Forms], antialiasing when drawing" +ms.assetid: 48fc34f3-f236-4b01-a0cb-f0752e6d22ae +--- +# How to: Use Antialiasing with Text +*Antialiasing* refers to the smoothing of jagged edges of drawn graphics and text to improve their appearance or readability. With the managed GDI+ classes, you can render high quality antialiased text, as well as lower quality text. Typically, higher quality rendering takes more processing time than lower quality rendering. To set the text quality level, set the property of a to one of the elements of the enumeration + +## Example + The following code example draws text with two different quality settings. + + [!code-csharp[System.Drawing.FontsAndText#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs#21)] + [!code-vb[System.Drawing.FontsAndText#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb#21)] + + The following illustration shows the output of the example code: + + ![Screenshot that shows text with two different quality settings.](./media/how-to-use-antialiasing-with-text/antialiasing-text-quality-settings.png) + +## Compiling the Code + The preceding code example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-clipping-with-a-region.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-clipping-with-a-region.md new file mode 100644 index 0000000000..56155c8c56 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-clipping-with-a-region.md @@ -0,0 +1,31 @@ +--- +title: "How to: Use Clipping with a Region" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "regions [Windows Forms], clipping" + - "regions [Windows Forms], restricting drawing surface" +ms.assetid: 43d121b4-e14c-4901-b25c-2d6c25ba4e29 +--- +# How to: Use Clipping with a Region +One of the properties of the class is the clip region. All drawing done by a given object is restricted to the clip region of that object. You can set the clip region by calling the method. + +## Example + The following example constructs a path that consists of a single polygon. Then the code constructs a region, based on that path. The region is passed to the method of a object, and then two strings are drawn. + + The following illustration shows the clipped strings: + + ![Screenshot that shows clipped strings.](./media/how-to-use-clipping-with-a-region/clipped-strings-polygon.png) + + [!code-csharp[System.Drawing.MiscLegacyTopics#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#41)] + [!code-vb[System.Drawing.MiscLegacyTopics#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#41)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- [Regions in GDI+](regions-in-gdi.md) +- [Using Regions](using-regions.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-compositing-mode-to-control-alpha-blending.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-compositing-mode-to-control-alpha-blending.md new file mode 100644 index 0000000000..5175871f5d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-compositing-mode-to-control-alpha-blending.md @@ -0,0 +1,56 @@ +--- +title: "How to: Use Compositing Mode to Control Alpha Blending" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "alpha blending [Windows Forms], compositing" + - "colors [Windows Forms], blending" + - "colors [Windows Forms], controlling transparency" +ms.assetid: f331df2d-b395-4b0a-95be-24fec8c9bbb5 +--- +# How to: Use Compositing Mode to Control Alpha Blending +There may be times when you want to create an off-screen bitmap that has the following characteristics: + +- Colors have alpha values that are less than 255. + +- Colors are not alpha blended with each other as you create the bitmap. + +- When you display the finished bitmap, colors in the bitmap are alpha blended with the background colors on the display device. + + To create such a bitmap, construct a blank object, and then construct a object based on that bitmap. Set the compositing mode of the object to . + +## Example + The following example creates a object based on a object. The code uses the object along with two semitransparent brushes (alpha = 160) to paint on the bitmap. The code fills a red ellipse and a green ellipse using the semitransparent brushes. The green ellipse overlaps the red ellipse, but the green is not blended with the red because the compositing mode of the object is set to . + + The code draws the bitmap on the screen twice: once on a white background and once on a multicolored background. The pixels in the bitmap that are part of the two ellipses have an alpha component of 160, so the ellipses are blended with the background colors on the screen. + + The following illustration shows the output of the code example. Note that the ellipses are blended with the background, but they are not blended with each other. + + ![Diagram showing ellipses blended with the background, not each other.](./media/how-to-use-compositing-mode-to-control-alpha-blending/ellipses-blended-background.png) + + The code example contains this statement: + + [!code-csharp[System.Drawing.AlphaBlending#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs#41)] + [!code-vb[System.Drawing.AlphaBlending#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb#41)] + + If you want the ellipses to be blended with each other as well as with the background, change that statement to the following: + + [!code-csharp[System.Drawing.AlphaBlending#42](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs#42)] + [!code-vb[System.Drawing.AlphaBlending#42](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb#42)] + + The following illustration shows the output of the revised code. + + ![Diagram that shows ellipses blended together and with background.](./media/how-to-use-compositing-mode-to-control-alpha-blending/blend-ellipses-background.png) + + [!code-csharp[System.Drawing.AlphaBlending#43](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs#43)] + [!code-vb[System.Drawing.AlphaBlending#43](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb#43)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- +- [Alpha Blending Lines and Fills](alpha-blending-lines-and-fills.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-hit-testing-with-a-region.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-hit-testing-with-a-region.md new file mode 100644 index 0000000000..a212f0b985 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-hit-testing-with-a-region.md @@ -0,0 +1,28 @@ +--- +title: "How to: Use Hit Testing with a Region" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "hit tests [Windows Forms], using regions" + - "regions [Windows Forms], hit testing" +ms.assetid: 3a4c07cb-a40a-4d14-ad35-008f531910a8 +--- +# How to: Use Hit Testing with a Region +The purpose of hit testing is to determine whether the cursor is over a given object, such as an icon or a button. + +## Example + The following example creates a plus-shaped region by forming the union of two rectangular regions. Assume that the variable `point` holds the location of the most recent click. The code checks to see whether `point` is in the plus-shaped region. If the point is in the region (a hit), the region is filled with an opaque red brush. Otherwise, the region is filled with a semitransparent red brush. + + [!code-csharp[System.Drawing.MiscLegacyTopics#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#31)] + [!code-vb[System.Drawing.MiscLegacyTopics#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#31)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of . + +## See also + +- +- [Regions in GDI+](regions-in-gdi.md) +- [How to: Use Clipping with a Region](how-to-use-clipping-with-a-region.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-interpolation-mode-to-control-image-quality-during-scaling.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-interpolation-mode-to-control-image-quality-during-scaling.md new file mode 100644 index 0000000000..1700b32231 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-interpolation-mode-to-control-image-quality-during-scaling.md @@ -0,0 +1,46 @@ +--- +title: "How to: Use Interpolation Mode to Control Image Quality During Scaling" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "interpolation mode [Windows Forms], controlling image quality" + - "images [Windows Forms], scaling" + - "images [Windows Forms], controlling quality" +ms.assetid: fde9bccf-8aa5-4b0d-ba4b-788740627b02 +--- +# How to: Use Interpolation Mode to Control Image Quality During Scaling +The interpolation mode of a object influences the way GDI+ scales (stretches and shrinks) images. The enumeration defines several interpolation modes, some of which are shown in the following list: + +- + +- + +- + +- + +- + + To stretch an image, each pixel in the original image must be mapped to a group of pixels in the larger image. To shrink an image, groups of pixels in the original image must be mapped to single pixels in the smaller image. The effectiveness of the algorithms that perform these mappings determines the quality of a scaled image. Algorithms that produce higher-quality scaled images tend to require more processing time. In the preceding list, is the lowest-quality mode and is the highest-quality mode. + + To set the interpolation mode, assign one of the members of the enumeration to the property of a object. + +## Example + The following example draws an image and then shrinks the image with three different interpolation modes. + + The following illustration shows the original image and the three smaller images. + + ![Screenshot that shows an image with varied interpolation settings.](./media/how-to-use-interpolation-mode-to-control-image-quality-during-scaling/varied-interpolation-settings.png) + + [!code-csharp[System.Drawing.WorkingWithImages#81](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs#81)] + [!code-vb[System.Drawing.WorkingWithImages#81](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb#81)] + +## Compiling the Code + The preceding example is designed for use with Windows Forms, and it requires `e`, which is a parameter of the event handler. + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-the-modifiers-and-generatemember-properties.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-the-modifiers-and-generatemember-properties.md new file mode 100644 index 0000000000..dc3f78fe9c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-use-the-modifiers-and-generatemember-properties.md @@ -0,0 +1,59 @@ +--- +title: "How to: Use the Modifiers and GenerateMember Properties" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "Designer_GenerateMember" + - "Designer_Modifiers" +helpviewer_keywords: + - "base forms" + - "inheritance [Windows Forms], forms" + - "inherited forms [Windows Forms], Windows Forms" + - "inherited forms" + - "form inheritance" + - "Windows Forms, inheritance" +ms.assetid: 3381a5e4-e1a3-44e2-a765-a0b758937b85 +--- +# How to: Use the Modifiers and GenerateMember Properties + +When you place a component on a Windows Form, two properties are provided by the design environment: `GenerateMember` and `Modifiers`. The `GenerateMember` property specifies when the Windows Forms Designer generates a member variable for a component. The `Modifiers` property is the access modifier assigned to that member variable. If the value of the `GenerateMember` property is `false`, the value of the `Modifiers` property has no effect. + +## Specify whether a component is a member of the form + +1. In Visual Studio, in the Windows Forms Designer, open your form. + +2. Open the **Toolbox**, and on the form, place three controls. + +3. Set the `GenerateMember` and `Modifiers` properties for each control according to the following table. + + |Button name|GenerateMember value|Modifiers value| + |-----------------|--------------------------|---------------------| + |`button1`|`true`|`private`| + |`button2`|`true`|`protected`| + |`button3`|`false`|No change| + +4. Build the solution. + +5. In **Solution Explorer**, click the **Show All Files** button. + +6. Open the **Form1** node, and in the **Code Editor**,open the **Form1.Designer.vb** or **Form1.Designer.cs** file. This file contains the code emitted by the Windows Forms Designer. + +7. Find the declarations for the three buttons. The following code example shows the differences specified by the `GenerateMember` and `Modifiers` properties. + + [!code-csharp[System.Windows.Forms.GenerateMember#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.GenerateMember#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/VB/Form1.vb#3)] + + [!code-csharp[System.Windows.Forms.GenerateMember#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.GenerateMember#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/VB/Form1.vb#2)] + +> [!NOTE] +> By default, the Windows Forms Designer assigns the `private` (`Friend` in Visual Basic) modifier to container controls like . If your base or has a container control, it will not accept new children in inherited controls and forms. The solution is to change the modifier of the base container control to `protected` or `public`. + +## See also + +- +- [Windows Forms Visual Inheritance](windows-forms-visual-inheritance.md) +- [Walkthrough: Demonstrating Visual Inheritance](walkthrough-demonstrating-visual-inheritance.md) +- [How to: Inherit Windows Forms](how-to-inherit-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-validate-application-settings.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-validate-application-settings.md new file mode 100644 index 0000000000..bfe3397378 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-validate-application-settings.md @@ -0,0 +1,163 @@ +--- +title: "How to: Validate Application Settings" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "validating application settings" + - "application settings [Windows Forms], Windows Forms" + - "application settings [Windows Forms], validating" +ms.assetid: 9f145ada-4267-436a-aa4c-c4dcffd0afb7 +--- +# How to: Validate Application Settings + +This topic demonstrates how to validate application settings before they are persisted. + +Because application settings are strongly typed, you have some confidence that users cannot assign data of an incorrect type to a given setting. However, a user still may attempt to assign a value to a setting that falls outside of acceptable bounds—for example, supplying a birth date that occurs in the future. , the parent class of all application settings classes, exposes four events to enable such bounds checking. Handling these events puts all of your validation code in a single location, rather than scattering it throughout your project. + +The event you use depends upon when you need to validate your settings, as described in the following table. + +|Event|Occurrence and use| +|-----------|------------------------| +||Occurs after the initial loading of a settings property group.

Use this event to validate initial values for the entire property group before they are used within the application.| +||Occurs before the value of a single settings property is changed.

Use this event to validate a single property before it is changed. It can provide immediate feedback to users regarding their actions and choices.| +||Occurs after the value of a single settings property is changed.

Use this event to validate a single property after it is changed. This event is rarely used for validation unless a lengthy, asynchronous validation process is required.| +||Occurs before the settings property group is stored.

Use this event to validate values for the entire property group before they are persisted to disk.| + +Typically, you will not use all of these events within the same application for validation purposes. For example, it is often possible to fulfill all validation requirements by handling only the event. + +An event handler generally performs one of the following actions when it detects an invalid value: + +- Automatically supplies a value known to be correct, such as the default value. + +- Re-queries the user of server code for information. + +- For events raised before their associated actions, such as and , uses the argument to cancel the operation. + +For more information about event handling, see [Event Handlers Overview](../event-handlers-overview-windows-forms.md). + +The following procedures show how to test for a valid birth date using either the or the event. The procedures were written under the assumption that you have already created your application settings; in this example, we will perform bounds checking on a setting named `DateOfBirth`. For more information about creating settings, see [How to: Create Application Settings](how-to-create-application-settings.md). + +### To obtain the application settings object + +- Obtain a reference to the application settings object (the wrapper instance) by completing one of the following bulleted items: + + - If you created your settings using the Visual Studio Application Settings dialog box in the **Property Editor**, you can retrieve the default settings object generated for your language through the following expression. + + ```csharp + Configuration.Settings.Default + ``` + + ```vb + MySettings.Default + ``` + + -or- + + - If you are a Visual Basic developer and you created your application settings using the Project Designer, you can retrieve your settings by using the [My.Settings Object](https://docs.microsoft.com/dotnet/visual-basic/language-reference/objects/my-settings-object). + + -or- + + - If you created your settings by deriving from directly, you need to instantiate your class manually. + + ```csharp + MyCustomSettings settings = new MyCustomSettings(); + ``` + + ```vb + Dim Settings as New MyCustomSettings() + ``` + +The following procedures were written under the assumption that the application settings object was obtained by completing the last bulleted item in this procedure. + +### To validate Application Settings when a setting is changing + +1. If you are a C# developer, in your form or control's `Load` event, add an event handler for the event. + + -or- + + If you are a Visual Basic developer, you should declare the `Settings` variable using the `WithEvents` keyword. + + ```csharp + public void Form1_Load(Object sender, EventArgs e) + { + settings.SettingChanging += new SettingChangingEventHandler(MyCustomSettings_SettingChanging); + } + ``` + + ```vb + Public Sub Form1_Load(sender as Object, e as EventArgs) + AddHandler settings.SettingChanging, AddressOf MyCustomSettings_SettingChanging + End Sub + ``` + +2. Define the event handler, and write the code inside of it to perform bounds checking on the birth date. + + ```csharp + private void MyCustomSettings_SettingChanging(Object sender, SettingChangingEventArgs e) + { + if (e.SettingName.Equals("DateOfBirth")) + { + var newDate = (DateTime)e.NewValue; + if (newDate > DateTime.Now) + { + e.Cancel = true; + // Inform the user. + } + } + } + ``` + + ```vb + Private Sub MyCustomSettings_SettingChanging(sender as Object, e as SettingChangingEventArgs) Handles Settings.SettingChanging + If (e.SettingName.Equals("DateOfBirth")) Then + Dim NewDate as Date = CType(e.NewValue, Date) + If (NewDate > Date.Now) Then + e.Cancel = True + ' Inform the user. + End If + End If + End Sub + ``` + +### To validate Application Settings when a Save occurs + +1. In your form or control's `Load` event, add an event handler for the event. + + ```csharp + public void Form1_Load(Object sender, EventArgs e) + { + settings.SettingsSaving += new SettingsSavingEventHandler(MyCustomSettings_SettingsSaving); + } + ``` + + ```vb + Public Sub Form1_Load(Sender as Object, e as EventArgs) + AddHandler settings.SettingsSaving, AddressOf MyCustomSettings_SettingsSaving + End Sub + ``` + +2. Define the event handler, and write the code inside of it to perform bounds checking on the birth date. + + ```csharp + private void MyCustomSettings_SettingsSaving(Object sender, SettingsSavingEventArgs e) + { + if (this["DateOfBirth"] > Date.Now) { + e.Cancel = true; + } + } + ``` + + ```vb + Private Sub MyCustomSettings_SettingsSaving(Sender as Object, e as SettingsSavingEventArgs) + If (Me["DateOfBirth"] > Date.Now) Then + e.Cancel = True + End If + End Sub + ``` + +## See also + +- [Creating Event Handlers in Windows Forms](../creating-event-handlers-in-windows-forms.md) +- [How to: Create Application Settings](how-to-create-application-settings.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp.md b/dotnet-desktop-guide/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp.md new file mode 100644 index 0000000000..348f6a464b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp.md @@ -0,0 +1,35 @@ +--- +title: "How To: Write User Settings at Run Time with C#" +description: Learn how to write settings at run time with C# by persisting the changes to the settings between application sessions by calling the Save method. +ms.date: "03/30/2017" +helpviewer_keywords: + - "application settings [Windows Forms], run time" + - "application settings [Windows Forms], writing user settings" + - "application settings [Windows Forms], C#" +ms.assetid: 9d061c7d-b33b-470f-a36d-edccb1d6f9a3 +--- +# How To: Write User Settings at Run Time with C\# + +Settings that are application-scoped are read-only, and can only be changed at design time or by altering the .config file in between application sessions. Settings that are user-scoped, however, can be written at run time just as you would change any property value. The new value persists for the duration of the application session. You can persist the changes to the settings between application sessions by calling the Save method. + +## How To: Write and Persist User Settings at Run Time with C\# + +1. Access the setting and assign it a new value as shown in this example: + + ```csharp + Properties.Settings.Default.myColor = Color.AliceBlue; + ``` + +2. If you want to persist the changes to the settings between application sessions, call the Save method as shown in this example: + + ```csharp + Properties.Settings.Default.Save(); + ``` + +User settings are saved in a file within a subfolder of the user’s local hidden application data folder. + +## See also + +- [Using Application Settings and User Settings](using-application-settings-and-user-settings.md) +- [How To: Read Settings at Run Time With C#](how-to-read-settings-at-run-time-with-csharp.md) +- [Application Settings Overview](application-settings-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/images-bitmaps-and-metafiles.md b/dotnet-desktop-guide/framework/winforms/advanced/images-bitmaps-and-metafiles.md new file mode 100644 index 0000000000..7598227db4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/images-bitmaps-and-metafiles.md @@ -0,0 +1,36 @@ +--- +title: "Images, Bitmaps, and Metafiles" +ms.date: "03/30/2017" +helpviewer_keywords: + - "metafiles [Windows Forms], about metafiles" + - "bitmaps [Windows Forms], about bitmaps" + - "images [Windows Forms], about images" + - "Windows Forms, images" +ms.assetid: 7152b45b-a55c-49bc-8c78-ae002a844f71 +--- +# Images, Bitmaps, and Metafiles +The `Image` class is an abstract base class that provides methods for working with raster images (bitmaps) and vector images (metafiles). The `Bitmap` class and the class both inherit from the `Image` class. The `Bitmap` class expands on the capabilities of the `Image` class by providing additional methods for loading, saving, and manipulating raster images. The class expands on the capabilities of the `Image` class by providing additional methods for recording and examining vector images. + +## In This Section + [Types of Bitmaps](types-of-bitmaps.md) + Discusses the various image formats. + + [Metafiles in GDI+](metafiles-in-gdi.md) + Discusses GDI+ support for metafiles. + + [Drawing, Positioning, and Cloning Images in GDI+](drawing-positioning-and-cloning-images-in-gdi.md) + Discusses methods for drawing vector and raster images with managed code. + + [Cropping and Scaling Images in GDI+](cropping-and-scaling-images-in-gdi.md) + Discusses methods for cropping and scaling vector and raster images with managed code + +## Reference + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members + +## Related Sections + [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) + Contains links to topics that demonstrate how to use images in your application. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/index.md b/dotnet-desktop-guide/framework/winforms/advanced/index.md new file mode 100644 index 0000000000..d01d08c02b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/index.md @@ -0,0 +1,60 @@ +--- +title: Enhance apps +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, enhancing" + - "Windows Forms, adding features" +ms.assetid: 733d1219-d6ad-4256-a55b-9eccf47f5a06 +--- +# Enhancing Windows Forms Applications +Windows Forms contains many features that you can use to enhance your Windows-based applications to meet the specific needs of your users. The following topics describe these features and how to use them. + +## In This Section + [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) + Contains links to topics that describe and show how to use the graphics interface in Windows Forms. + + [Application Settings for Windows Forms](application-settings-for-windows-forms.md). + Contains links to topics that describe and show how to use the **Application Settings** feature. + + [Windows Forms Print Support](windows-forms-print-support.md) + Contains links to topics that describe and show how to print files from Windows Forms applications. + + [Drag-and-Drop Operations and Clipboard Support](drag-and-drop-operations-and-clipboard-support.md) + Contains links to topics that describe and show how to use the drag-and-drop feature and the Clipboard in Windows Forms. + + [Networking in Windows Forms Applications](networking-in-windows-forms-applications.md) + Contains links to topics that describe and show how to use networking in Windows Forms. + + [Globalizing Windows Forms applications](globalizing-windows-forms.md) + Contains links to topics that show how to globalize Windows Forms applications. + + [Windows Forms and Unmanaged Applications](windows-forms-and-unmanaged-applications.md) + Contains links to topics that describe and show how to access COM components from Windows Form applications. + + [System Information and Windows Forms](system-information-and-windows-forms.md) + Describes how to use system information in Windows Forms. + + [Power Management in Windows Forms](power-management-in-windows-forms.md) + Describes how to manage power use in Windows Forms applications. + + [Windows Forms Visual Inheritance](windows-forms-visual-inheritance.md) + Describes how to inherit from a base form. + + [Multiple-Document Interface (MDI) Applications](multiple-document-interface-mdi-applications.md) + Describes how to create multiple-document interface (MDI) applications. + + [Integrating User Help in Windows Forms](integrating-user-help-in-windows-forms.md) + Describes how to integrate user help in your applications. + + [Windows Forms Accessibility](windows-forms-accessibility.md) + Describes how to make your applications available to a wide variety of users. + + [Using WPF Controls](using-wpf-controls.md) + Describes how to use WPF controls in your Windows Forms-based applications. + +## Related Sections + [Help Systems in Windows Forms Applications](help-systems-in-windows-forms-applications.md) + Contains links to topics that describe and show how to provide user help in Windows Forms applications. + + [Getting Started with Windows Forms](../getting-started-with-windows-forms.md) + Contains links to topics that describe how to use the basic features of Windows Forms. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/integrating-user-help-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/integrating-user-help-in-windows-forms.md new file mode 100644 index 0000000000..13fd1f4c9a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/integrating-user-help-in-windows-forms.md @@ -0,0 +1,39 @@ +--- +title: "Integrating User Help" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Help [Windows Forms], Windows Forms (using designer)" + - "Windows Forms, Help (using designer)" + - "HTML Help [Windows Forms], Windows Forms (using designer)" + - "Help [Windows Forms], Windows applications (using designer)" + - "forms. Help (using designer)" + - "Windows applications [Windows Forms], Help (using designer)" +ms.assetid: a8563d25-8a75-4bc7-a024-f1870591b50f +--- +# Integrating User Help in Windows Forms +An essential, but often overlooked, aspect of building Windows-based applications is the Help system, as this is where users turn for assistance in times of confusion. Windows Forms support two different types of Help, each provided by the [HelpProvider Component](../controls/helpprovider-component-windows-forms.md). The first involves pointing the user to a Help file of either HTML or HTML Help 1.*x* or greater format. The second can display brief "What's This"-type Help on individual controls; this is especially useful on dialog boxes. Both types of Help can be used on the same form. + + Additionally, the [ToolTip Component](../controls/tooltip-component-windows-forms.md) can be used to provide individual Help for controls on Windows Forms. + +## In This Section + [How to: Provide Help in a Windows Application](how-to-provide-help-in-a-windows-application.md) + Explains how to use the `HelpProvider` component to link controls to files in a Help system. + + [How to: Display Pop-up Help](how-to-display-pop-up-help.md) + Explains how to use the `HelpProvider` component to show pop-up Help on Windows Forms. + + [Control Help Using ToolTips](control-help-using-tooltips.md) + Describes using the `ToolTip` component to show control-specific Help. + +## Related Sections + [HelpProvider Component](../controls/helpprovider-component-windows-forms.md) + Explains the basics of the `HelpProvider` component. + + [ToolTip Component](../controls/tooltip-component-windows-forms.md) + Explains the basics of the `ToolTip` component. + + [Windows Forms Overview](../windows-forms-overview.md) + Explains the basics of Windows Forms. + + [Windows Forms](../index.yml) + Provides an overview of Windows Forms. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/international-fonts-in-windows-forms-and-controls.md b/dotnet-desktop-guide/framework/winforms/advanced/international-fonts-in-windows-forms-and-controls.md new file mode 100644 index 0000000000..ed0e594955 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/international-fonts-in-windows-forms-and-controls.md @@ -0,0 +1,83 @@ +--- +title: International fonts in forms and controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "fonts [Windows Forms], international" + - "international applications [Windows Forms], character display" + - "fonts [Windows Forms], globalization considerations" + - "localization [Windows Forms], fonts" + - "Windows Forms controls, labels" + - "font fallback in Windows Forms" + - "globalization [Windows Forms], character sets" +dev_langs: + - "csharp" + - "vb" +ms.assetid: 2c3066df-9bac-479a-82b2-79e484b346a3 +--- +# International fonts in Windows Forms and controls + +In International applications, the recommended method of selecting fonts is to use font fallback wherever possible. Font fallback means that the system determines what script the character belongs to. + +## Using font fallback + +To take advantage of this feature, don't set the property for your form or any other element. The application will automatically use the default system font, which differs from one localized language of the operating system to another. When the application runs, the system will automatically provide the correct font for the culture selected in the operating system. + +There's an exception to the rule of not setting the font, which is for changing the font style. This might be important for an application in which the user clicks a button to make text in a text box appear in boldface. To do that, you would write a function to change the text box's font style to bold, based on whatever the form's font is. It's important to call this function in two places: in the button's event handler and in the event handler. If the function is called only in the event handler and some other piece of code changes the font family of the entire form, the text box doesn't change with the rest of the form. + +```vb +Private Sub MakeBold() + ' Change the TextBox to a bold version of the form font + TextBox1.Font = New Font(Me.Font, FontStyle.Bold) +End Sub + +Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + ' Clicking this button makes the TextBox bold + MakeBold() +End Sub + +Private Sub Form1_FontChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.FontChanged + ' If the TextBox is already bold and the form's font changes, + ' change the TextBox to a bold version of the new form font + If (TextBox1.Font.Style = FontStyle.Bold) Then + MakeBold() + End If +End Sub +``` + +```csharp +private void button1_Click(object sender, System.EventArgs e) +{ + // Clicking this button makes the TextBox bold + MakeBold(); +} + +private void MakeBold() +{ + // Change the TextBox to a bold version of the form's font + textBox1.Font = new Font(this.Font, FontStyle.Bold); +} + +private void Form1_FontChanged(object sender, System.EventArgs e) +{ + // If the TextBox is already bold and the form's font changes, + // change the TextBox to a bold version of the new form font + if (textBox1.Font.Style == FontStyle.Bold) + { + MakeBold(); + } +} +``` + +However, when you localize your application, the bold font may display poorly for certain languages. If this is a concern, you want the localizers to have the option of switching the font from bold to regular text. Since localizers are typically not developers and don't have access to source code, only to resource files, this option needs to be set in the resource files. To do this, you would set the property to `true`. This results in the font setting being written out to the resource files, where localizers can edit it. You then write code after the `InitializeComponent` method to reset the font based on whatever the form's font is, but using the font style specified in the resource file. + +```vb +TextBox1.Font = New System.Drawing.Font(Me.Font, TextBox1.Font.Style) +``` + +```csharp +textBox1.Font = new System.Drawing.Font(this.Font, textBox1.Font.Style); +``` + +## See also + +- [Using Fonts and Text](using-fonts-and-text.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/lines-curves-and-shapes.md b/dotnet-desktop-guide/framework/winforms/advanced/lines-curves-and-shapes.md new file mode 100644 index 0000000000..bb2f6e3e92 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/lines-curves-and-shapes.md @@ -0,0 +1,50 @@ +--- +title: "Lines, Curves, and Shapes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "shapes [Windows Forms], filling" + - "splines [Windows Forms], drawing" + - "shapes. drawing" + - "lines [Windows Forms], drawing" + - "curves [Windows Forms], drawing" +ms.assetid: ace6e8d4-4e94-486b-9681-758a6667dc7f +--- +# Lines, Curves, and Shapes +The vector graphics portion of GDI+ is used to draw lines, draw curves, and to draw and fill shapes. + +## In This Section + [Vector Graphics Overview](vector-graphics-overview.md) + Discusses vector graphics. + + [Pens, Lines, and Rectangles in GDI+](pens-lines-and-rectangles-in-gdi.md) + Discusses drawing lines and rectangles. + + [Ellipses and Arcs in GDI+](ellipses-and-arcs-in-gdi.md) + Defines arcs and ellipses and identifies the classes needed to draw them. + + [Polygons in GDI+](polygons-in-gdi.md) + Defines polygons and identifies the classes needed to draw them. + + [Cardinal Splines in GDI+](cardinal-splines-in-gdi.md) + Defines cardinal splines and identifies the classes needed to draw them. + + [Bézier Splines in GDI+](bezier-splines-in-gdi.md) + Defines Bezier splines and identifies the classes needed to draw them. + + [Graphics Paths in GDI+](graphics-paths-in-gdi.md) + Describes paths and how to create and draw them. + + [Brushes and Filled Shapes in GDI+](brushes-and-filled-shapes-in-gdi.md) + Describes brush types and how to use them. + + [Open and Closed Curves in GDI+](open-and-closed-curves-in-gdi.md) + Defines open and closed curves and how to draw and fill them. + + [Regions in GDI+](regions-in-gdi.md) + Describes the methods associated with regions. + + [Restricting the Drawing Surface in GDI+](restricting-the-drawing-surface-in-gdi.md) + Describes clipping and how to use it. + + [Antialiasing with Lines and Curves](antialiasing-with-lines-and-curves.md) + Defines antialiasing and how use antialiasing when drawing lines and curves. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/managing-the-state-of-a-graphics-object.md b/dotnet-desktop-guide/framework/winforms/advanced/managing-the-state-of-a-graphics-object.md new file mode 100644 index 0000000000..856fe7d7df --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/managing-the-state-of-a-graphics-object.md @@ -0,0 +1,150 @@ +--- +title: "Managing the State of a Graphics Object" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "graphics [Windows Forms], managing state" + - "graphics [Windows Forms], clipping" +ms.assetid: 6207cad1-7a34-4bd6-bfc1-db823ca7a73e +--- +# Managing the State of a Graphics Object +The class is at the heart of GDI+. To draw anything, you obtain a object, set its properties, and call its methods , , , and the like). + + The following example calls the method of a object. The first argument passed to the method is a object. + +```vb +Dim graphics As Graphics = e.Graphics +Dim pen As New Pen(Color.Blue) ' Opaque blue +graphics.DrawRectangle(pen, 10, 10, 200, 100) +``` + +```csharp +Graphics graphics = e.Graphics; +Pen pen = new Pen(Color.Blue); // Opaque blue +graphics.DrawRectangle(pen, 10, 10, 200, 100); +``` + +## Graphics State + A object does more than provide drawing methods, such as and . A object also maintains graphics state, which can be divided into the following categories: + +- Quality settings + +- Transformations + +- Clipping region + +### Quality Settings + A object has several properties that influence the quality of the items that are drawn. For example, you can set the property to specify the type of antialiasing (if any) applied to text. Other properties that influence quality are , , , and . + + The following example draws two ellipses, one with the smoothing mode set to and one with the smoothing mode set to : + +```vb +Dim graphics As Graphics = e.Graphics +Dim pen As New Pen(Color.Blue) + +graphics.SmoothingMode = SmoothingMode.AntiAlias +graphics.DrawEllipse(pen, 0, 0, 200, 100) +graphics.SmoothingMode = SmoothingMode.HighSpeed +graphics.DrawEllipse(pen, 0, 150, 200, 100) +``` + +```csharp +Graphics graphics = e.Graphics; +Pen pen = new Pen(Color.Blue); + +graphics.SmoothingMode = SmoothingMode.AntiAlias; +graphics.DrawEllipse(pen, 0, 0, 200, 100); +graphics.SmoothingMode = SmoothingMode.HighSpeed; +graphics.DrawEllipse(pen, 0, 150, 200, 100); +``` + +### Transformations + A object maintains two transformations (world and page) that are applied to all items drawn by that object. Any affine transformation can be stored in the world transformation. Affine transformations include scaling, rotating, reflecting, skewing, and translating. The page transformation can be used for scaling and for changing units (for example, pixels to inches). For more information, see [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md). + + The following example sets the world and page transformations of a object. The world transformation is set to a 30-degree rotation. The page transformation is set so that the coordinates passed to the second will be treated as millimeters instead of pixels. The code makes two identical calls to the method. The world transformation is applied to the first call, and both transformations (world and page) are applied to the second call. + +```vb +Dim graphics As Graphics = e.Graphics +Dim pen As New Pen(Color.Red) + +graphics.ResetTransform() +graphics.RotateTransform(30) ' world transformation +graphics.DrawEllipse(pen, 0, 0, 100, 50) +graphics.PageUnit = GraphicsUnit.Millimeter ' page transformation +graphics.DrawEllipse(pen, 0, 0, 100, 50) +``` + +```csharp +Graphics graphics = e.Graphics; +Pen pen = new Pen(Color.Red); + +graphics.ResetTransform(); +graphics.RotateTransform(30); // world transformation +graphics.DrawEllipse(pen, 0, 0, 100, 50); +graphics.PageUnit = GraphicsUnit.Millimeter; // page transformation +graphics.DrawEllipse(pen, 0, 0, 100, 50); +``` + + The following illustration shows the two ellipses. Note that the 30-degree rotation is about the origin of the coordinate system (upper-left corner of the client area), not about the centers of the ellipses. Also note that the pen width of 1 means 1 pixel for the first ellipse and 1 millimeter for the second ellipse. + + ![Illustration that shows two ellipses: rotation and pen width.](./media/managing-the-state-of-a-graphics-object/set-rotation-pen-width-drawellipse-method.png) + +### Clipping Region + A object maintains a clipping region that applies to all items drawn by that object. You can set the clipping region by calling the method. + + The following example creates a plus-shaped region by forming the union of two rectangles. That region is designated as the clipping region of a object. Then the code draws two lines that are restricted to the interior of the clipping region. + +```vb +Dim graphics As Graphics = e.Graphics + +' Opaque red, width 5 +Dim pen As New Pen(Color.Red, 5) + +' Opaque aqua +Dim brush As New SolidBrush(Color.FromArgb(255, 180, 255, 255)) + +' Create a plus-shaped region by forming the union of two rectangles. +Dim [region] As New [Region](New Rectangle(50, 0, 50, 150)) +[region].Union(New Rectangle(0, 50, 150, 50)) +graphics.FillRegion(brush, [region]) + +' Set the clipping region. +graphics.SetClip([region], CombineMode.Replace) + +' Draw two clipped lines. +graphics.DrawLine(pen, 0, 30, 150, 160) +graphics.DrawLine(pen, 40, 20, 190, 150) +``` + +```csharp +Graphics graphics = e.Graphics; + +// Opaque red, width 5 +Pen pen = new Pen(Color.Red, 5); + +// Opaque aqua +SolidBrush brush = new SolidBrush(Color.FromArgb(255, 180, 255, 255)); + +// Create a plus-shaped region by forming the union of two rectangles. +Region region = new Region(new Rectangle(50, 0, 50, 150)); +region.Union(new Rectangle(0, 50, 150, 50)); +graphics.FillRegion(brush, region); + +// Set the clipping region. +graphics.SetClip(region, CombineMode.Replace); + +// Draw two clipped lines. +graphics.DrawLine(pen, 0, 30, 150, 160); +graphics.DrawLine(pen, 40, 20, 190, 150); +``` + + The following illustration shows the clipped lines: + + ![Diagram that shows the limited clip region.](./media/managing-the-state-of-a-graphics-object/set-clipping-region-setclip-method.png) + +## See also + +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Using Nested Graphics Containers](using-nested-graphics-containers.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/matrix-representation-of-transformations.md b/dotnet-desktop-guide/framework/winforms/advanced/matrix-representation-of-transformations.md new file mode 100644 index 0000000000..74389935b4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/matrix-representation-of-transformations.md @@ -0,0 +1,103 @@ +--- +title: "Matrix Representation of Transformations" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "composite transformations" + - "transformations [Windows Forms], linear" + - "matrices" + - "translations in matrix representation" + - "transformations [Windows Forms], composite" + - "vectors" + - "linear transformations" + - "transformations [Windows Forms], matrix representation of" + - "transformations [Windows Forms], translation" + - "affine transformations" +ms.assetid: 0659fe00-9e0c-41c4-9118-016f2404c905 +--- +# Matrix Representation of Transformations +An m×n matrix is a set of numbers arranged in m rows and n columns. The following illustration shows several matrices. + + ![Transformations](./media/aboutgdip05-art04.gif "AboutGdip05_art04") + + You can add two matrices of the same size by adding individual elements. The following illustration shows two examples of matrix addition. + + ![Transformations](./media/aboutgdip05-art05.gif "AboutGdip05_art05") + + An m×n matrix can be multiplied by an n×p matrix, and the result is an m×p matrix. The number of columns in the first matrix must be the same as the number of rows in the second matrix. For example, a 4×2 matrix can be multiplied by a 2×3 matrix to produce a 4×3 matrix. + + Points in the plane and rows and columns of a matrix can be thought of as vectors. For example, (2, 5) is a vector with two components, and (3, 7, 1) is a vector with three components. The dot product of two vectors is defined as follows: + + (a, b) • (c, d) = ac + bd + + (a, b, c) • (d, e, f) = ad + be + cf + + For example, the dot product of (2, 3) and (5, 4) is (2)(5) + (3)(4) = 22. The dot product of (2, 5, 1) and (4, 3, 1) is (2)(4) + (5)(3) + (1)(1) = 24. Note that the dot product of two vectors is a number, not another vector. Also note that you can calculate the dot product only if the two vectors have the same number of components. + + Let A(i, j) be the entry in matrix A in the ith row and the jth column. For example A(3, 2) is the entry in matrix A in the 3rd row and the 2nd column. Suppose A, B, and C are matrices, and AB = C. The entries of C are calculated as follows: + + C(i, j) = (row i of A) • (column j of B) + + The following illustration shows several examples of matrix multiplication. + + ![Transformations](./media/aboutgdip05-art06.gif "AboutGdip05_art06") + + If you think of a point in a plane as a 1×2 matrix, you can transform that point by multiplying it by a 2×2 matrix. The following illustration shows several transformations applied to the point (2, 1). + + ![Transformations](./media/aboutgdip05-art07.gif "AboutGdip05_art07") + + All of the transformations shown in the preceding figure are linear transformations. Certain other transformations, such as translation, are not linear, and cannot be expressed as multiplication by a 2×2 matrix. Suppose you want to start with the point (2, 1), rotate it 90 degrees, translate it 3 units in the x direction, and translate it 4 units in the y direction. You can accomplish this by using a matrix multiplication followed by a matrix addition. + + ![Transformations](./media/aboutgdip05-art08.gif "AboutGdip05_art08") + + A linear transformation (multiplication by a 2×2 matrix) followed by a translation (addition of a 1×2 matrix) is called an affine transformation. An alternative to storing an affine transformation in a pair of matrices (one for the linear part and one for the translation) is to store the entire transformation in a 3×3 matrix. To make this work, a point in the plane must be stored in a 1×3 matrix with a dummy 3rd coordinate. The usual technique is to make all 3rd coordinates equal to 1. For example, the point (2, 1) is represented by the matrix [2 1 1]. The following illustration shows an affine transformation (rotate 90 degrees; translate 3 units in the x direction, 4 units in the y direction) expressed as multiplication by a single 3×3 matrix. + + ![Transformations](./media/aboutgdip05-art09.gif "AboutGdip05_art09") + + In the preceding example, the point (2, 1) is mapped to the point (2, 6). Note that the third column of the 3×3 matrix contains the numbers 0, 0, 1. This will always be the case for the 3×3 matrix of an affine transformation. The important numbers are the six numbers in columns 1 and 2. The upper-left 2×2 portion of the matrix represents the linear part of the transformation, and the first two entries in the 3rd row represent the translation. + + ![Transformations](./media/aboutgdip05-art10.gif "AboutGdip05_art10") + + In GDI+ you can store an affine transformation in a object. Because the third column of a matrix that represents an affine transformation is always (0, 0, 1), you specify only the six numbers in the first two columns when you construct a object. The statement `Matrix myMatrix = new Matrix(0, 1, -1, 0, 3, 4)` constructs the matrix shown in the preceding figure. + +## Composite Transformations + A composite transformation is a sequence of transformations, one followed by the other. Consider the matrices and transformations in the following list: + +||| +|-|-| +|Matrix A|Rotate 90 degrees| +|Matrix B|Scale by a factor of 2 in the x direction| +|Matrix C|Translate 3 units in the y direction| + + If we start with the point (2, 1) — represented by the matrix [2 1 1] — and multiply by A, then B, then C, the point (2, 1) will undergo the three transformations in the order listed. + + [2 1 1]ABC = [-2 5 1] + + Rather than store the three parts of the composite transformation in three separate matrices, you can multiply A, B, and C together to get a single 3×3 matrix that stores the entire composite transformation. Suppose ABC = D. Then a point multiplied by D gives the same result as a point multiplied by A, then B, then C. + + [2 1 1]D = [-2 5 1] + + The following illustration shows the matrices A, B, C, and D. + + ![Transformations](./media/aboutgdip05-art12.gif "AboutGdip05_art12") + + The fact that the matrix of a composite transformation can be formed by multiplying the individual transformation matrices means that any sequence of affine transformations can be stored in a single object. + +> [!CAUTION] +> The order of a composite transformation is important. In general, rotate, then scale, then translate is not the same as scale, then rotate, then translate. Similarly, the order of matrix multiplication is important. In general, ABC is not the same as BAC. + + The class provides several methods for building a composite transformation: , , , , , and . The following example creates the matrix of a composite transformation that first rotates 30 degrees, then scales by a factor of 2 in the y direction, and then translates 5 units in the x direction: + + [!code-csharp[System.Drawing.CoordinateSystems#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#11)] + [!code-vb[System.Drawing.CoordinateSystems#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#11)] + + The following illustration shows the matrix. + + ![Transformations](./media/aboutgdip05-art13.gif "AboutGdip05_art13") + +## See also + +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) +- [Using Transformations in Managed GDI+](using-transformations-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art01.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art01.gif new file mode 100644 index 0000000000..22c9f89e93 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art01.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art02.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art02.gif new file mode 100644 index 0000000000..bc88ad6fa4 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art02.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art03.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art03.gif new file mode 100644 index 0000000000..82902c948f Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art03.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art04.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art04.gif new file mode 100644 index 0000000000..bf5325bc0f Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art04.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art05.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art05.gif new file mode 100644 index 0000000000..65415d7fa8 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art05.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art06.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art06.gif new file mode 100644 index 0000000000..ae509c7927 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art06.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art07.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art07.gif new file mode 100644 index 0000000000..60dd5454b7 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art07.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art08.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art08.gif new file mode 100644 index 0000000000..73aab32ffc Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art08.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art09.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art09.gif new file mode 100644 index 0000000000..242c2f6bc5 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art09.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art10.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art10.gif new file mode 100644 index 0000000000..c0fef60a51 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art10.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art11a.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art11a.gif new file mode 100644 index 0000000000..7830f0a2a0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art11a.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art12.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art12.gif new file mode 100644 index 0000000000..2990c2d056 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art12.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art13.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art13.gif new file mode 100644 index 0000000000..923c9a5671 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art13.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art14.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art14.gif new file mode 100644 index 0000000000..6f26669076 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art14.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art15.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art15.gif new file mode 100644 index 0000000000..1b31f1f9f2 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art15.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art16.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art16.gif new file mode 100644 index 0000000000..37878a4269 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art16.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art17.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art17.gif new file mode 100644 index 0000000000..6f43acbffd Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art17.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art18.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art18.gif new file mode 100644 index 0000000000..72aa8e8425 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art18.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art19.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art19.gif new file mode 100644 index 0000000000..265e98f59a Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art19.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art20.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art20.gif new file mode 100644 index 0000000000..c584987d34 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art20.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art21.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art21.gif new file mode 100644 index 0000000000..998018469a Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art21.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art22.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art22.gif new file mode 100644 index 0000000000..3a8b0f8a95 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art22.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art23.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art23.gif new file mode 100644 index 0000000000..2a12dc4619 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art23.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art24.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art24.gif new file mode 100644 index 0000000000..bfcf627a20 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art24.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art25.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art25.gif new file mode 100644 index 0000000000..27af4c8433 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art25.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art26.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art26.gif new file mode 100644 index 0000000000..5ee43ae9a4 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art26.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art27.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art27.gif new file mode 100644 index 0000000000..8885e26ae4 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art27.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art28.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art28.gif new file mode 100644 index 0000000000..ba8acea14a Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art28.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art29.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art29.gif new file mode 100644 index 0000000000..618a003215 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art29.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art30.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art30.gif new file mode 100644 index 0000000000..6b37968d09 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art30.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art31.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art31.gif new file mode 100644 index 0000000000..03ceff6418 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art31.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art32a.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art32a.gif new file mode 100644 index 0000000000..da50ab4f96 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art32a.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art33.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art33.gif new file mode 100644 index 0000000000..74dde235df Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art33.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art34.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art34.gif new file mode 100644 index 0000000000..206f8be9f3 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art34.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art35.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art35.gif new file mode 100644 index 0000000000..2171e163d4 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art35.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art36.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art36.gif new file mode 100644 index 0000000000..db39732ea2 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip02-art36.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art01.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art01.gif new file mode 100644 index 0000000000..5d20854c14 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art01.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art02.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art02.gif new file mode 100644 index 0000000000..d9113276fa Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art02.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art03.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art03.gif new file mode 100644 index 0000000000..463e7a7a84 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art03.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art03a.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art03a.gif new file mode 100644 index 0000000000..1151f0607d Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art03a.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art04.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art04.gif new file mode 100644 index 0000000000..a007dfda62 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art04.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art05.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art05.gif new file mode 100644 index 0000000000..9d657b31a7 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art05.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art06.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art06.gif new file mode 100644 index 0000000000..1d1b63cbc3 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art06.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art07.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art07.gif new file mode 100644 index 0000000000..7ba514bf9f Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip03-art07.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art01.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art01.gif new file mode 100644 index 0000000000..d9d7fefa8f Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art01.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art02.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art02.gif new file mode 100644 index 0000000000..4182c88d5c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art02.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art03.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art03.gif new file mode 100644 index 0000000000..c77a4aa449 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art03.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art04.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art04.gif new file mode 100644 index 0000000000..90739082bc Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art04.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art05.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art05.gif new file mode 100644 index 0000000000..0a6cdd4001 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art05.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art06.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art06.gif new file mode 100644 index 0000000000..5ac67469ee Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art06.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art07.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art07.gif new file mode 100644 index 0000000000..382ffd50d6 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art07.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art08.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art08.gif new file mode 100644 index 0000000000..80adf3d02a Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art08.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art09.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art09.gif new file mode 100644 index 0000000000..ee0dc9e144 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art09.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art10.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art10.gif new file mode 100644 index 0000000000..5853ca9cbb Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art10.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art12.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art12.gif new file mode 100644 index 0000000000..140c14f3cc Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art12.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art13.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art13.gif new file mode 100644 index 0000000000..d529cf766e Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art13.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art14.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art14.gif new file mode 100644 index 0000000000..af6c4dbfb2 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art14.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art15.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art15.gif new file mode 100644 index 0000000000..c7ba5d535c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art15.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art16.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art16.gif new file mode 100644 index 0000000000..d0b742becc Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/aboutgdip05-art16.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-apply-gamma-correction-to-a-gradient/two-rectangles-gamma-gradient.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-apply-gamma-correction-to-a-gradient/two-rectangles-gamma-gradient.png new file mode 100644 index 0000000000..7d8948ffe6 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-apply-gamma-correction-to-a-gradient/two-rectangles-gamma-gradient.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-ellipse-rectangle.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-ellipse-rectangle.png new file mode 100644 index 0000000000..30263f1123 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-ellipse-rectangle.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-line-ellipse-rectangle.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-line-ellipse-rectangle.png new file mode 100644 index 0000000000..e01c3976d9 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-line-ellipse-rectangle.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-line-ellipse.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-line-ellipse.png new file mode 100644 index 0000000000..163b74d1c0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-linear-gradient/gradient-line-ellipse.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/focus-scales-aqua-inner-outer-ellipse.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/focus-scales-aqua-inner-outer-ellipse.png new file mode 100644 index 0000000000..ba6fba572a Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/focus-scales-aqua-inner-outer-ellipse.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-brush-filled-triangle.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-brush-filled-triangle.png new file mode 100644 index 0000000000..6e816c1e9c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-brush-filled-triangle.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-painted-path-gradient-brush.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-painted-path-gradient-brush.png new file mode 100644 index 0000000000..177f19797e Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-painted-path-gradient-brush.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-center-point-outside.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-center-point-outside.png new file mode 100644 index 0000000000..f345d08d2c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-center-point-outside.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-extended-beyond-boundary.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-extended-beyond-boundary.png new file mode 100644 index 0000000000..66f2c6978d Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-extended-beyond-boundary.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-filled-ellipse-center-point.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-filled-ellipse-center-point.png new file mode 100644 index 0000000000..fb38e080c4 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-filled-ellipse-center-point.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-filled-ellipse.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-filled-ellipse.png new file mode 100644 index 0000000000..618e63d9f8 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-path-gradient/gradient-path-filled-ellipse.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-private-font-collection/various-fonts-text-output.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-private-font-collection/various-fonts-text-output.png new file mode 100644 index 0000000000..ca10162f42 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-a-private-font-collection/various-fonts-text-output.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-thumbnail-images/construct-thumbnail-image.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-thumbnail-images/construct-thumbnail-image.png new file mode 100644 index 0000000000..9748af968a Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-thumbnail-images/construct-thumbnail-image.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-vertical-text/vertical-font-text-graphic.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-vertical-text/vertical-font-text-graphic.png new file mode 100644 index 0000000000..a77f046997 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-create-vertical-text/vertical-font-text-graphic.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-crop-and-scale-images/original-image-cropped-image.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-crop-and-scale-images/original-image-cropped-image.png new file mode 100644 index 0000000000..15b03a1c24 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-crop-and-scale-images/original-image-cropped-image.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-custom-dashed-line/dashed-line-illustration.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-custom-dashed-line/dashed-line-illustration.gif new file mode 100644 index 0000000000..a1bb9251dd Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-custom-dashed-line/dashed-line-illustration.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-line-filled-with-a-texture/bitmap-textured-ellipse.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-line-filled-with-a-texture/bitmap-textured-ellipse.png new file mode 100644 index 0000000000..4496011289 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-line-filled-with-a-texture/bitmap-textured-ellipse.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-line-with-line-caps/line-cap-arrowhead-example.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-line-with-line-caps/line-cap-arrowhead-example.gif new file mode 100644 index 0000000000..bf94c6fb6e Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-line-with-line-caps/line-cap-arrowhead-example.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-sequence-of-bezier-splines/bezier-spline-seven-points.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-sequence-of-bezier-splines/bezier-spline-seven-points.png new file mode 100644 index 0000000000..02102a64ae Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-sequence-of-bezier-splines/bezier-spline-seven-points.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-single-bezier-spline/bezier-spline-illustration.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-single-bezier-spline/bezier-spline-illustration.png new file mode 100644 index 0000000000..a34043c996 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-a-single-bezier-spline/bezier-spline-illustration.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-an-existing-bitmap-to-the-screen/bitmap-specified-position.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-an-existing-bitmap-to-the-screen/bitmap-specified-position.png new file mode 100644 index 0000000000..45244275a6 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-an-existing-bitmap-to-the-screen/bitmap-specified-position.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/bell-shaped-cardinal-spline.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/bell-shaped-cardinal-spline.png new file mode 100644 index 0000000000..519b53b6a7 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/bell-shaped-cardinal-spline.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/closed-cardinal-spine.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/closed-cardinal-spine.png new file mode 100644 index 0000000000..2ff3764633 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/closed-cardinal-spine.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/three-cardinal-splines.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/three-cardinal-splines.png new file mode 100644 index 0000000000..95b016fcea Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-cardinal-splines/three-cardinal-splines.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-opaque-and-semitransparent-lines/opaque-semitransparent-lines.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-opaque-and-semitransparent-lines/opaque-semitransparent-lines.png new file mode 100644 index 0000000000..15fb734fd1 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-opaque-and-semitransparent-lines/opaque-semitransparent-lines.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-text-at-a-specified-location/font-text-specified-point.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-text-at-a-specified-location/font-text-specified-point.png new file mode 100644 index 0000000000..43512d1562 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-text-at-a-specified-location/font-text-specified-point.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-with-opaque-and-semitransparent-brushes/compositingquality-ellipse-semitransparent.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-with-opaque-and-semitransparent-brushes/compositingquality-ellipse-semitransparent.png new file mode 100644 index 0000000000..7a71eacf8e Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-with-opaque-and-semitransparent-brushes/compositingquality-ellipse-semitransparent.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-wrapped-text-in-a-rectangle/drawstring-method-font-text.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-wrapped-text-in-a-rectangle/drawstring-method-font-text.png new file mode 100644 index 0000000000..bfd7473a4c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-draw-wrapped-text-in-a-rectangle/drawstring-method-font-text.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-enumerate-installed-fonts/list-installed-font-families.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-enumerate-installed-fonts/list-installed-font-families.png new file mode 100644 index 0000000000..7c875f185d Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-enumerate-installed-fonts/list-installed-font-families.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-fill-a-shape-with-a-hatch-pattern/ellipse-filled-hatch.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-fill-a-shape-with-a-hatch-pattern/ellipse-filled-hatch.png new file mode 100644 index 0000000000..7ddecd8978 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-fill-a-shape-with-a-hatch-pattern/ellipse-filled-hatch.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-fill-open-figures/fill-path-alternate-mode.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-fill-open-figures/fill-path-alternate-mode.png new file mode 100644 index 0000000000..25483d0ce2 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-fill-open-figures/fill-path-alternate-mode.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-improve-performance-by-avoiding-automatic-scaling/two-scaled-texture-images.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-improve-performance-by-avoiding-automatic-scaling/two-scaled-texture-images.png new file mode 100644 index 0000000000..7f1cc80fdd Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-improve-performance-by-avoiding-automatic-scaling/two-scaled-texture-images.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-inherit-forms-using-the-inheritance-picker-dialog-box/visual-basic-inheritance-glyph.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-inherit-forms-using-the-inheritance-picker-dialog-box/visual-basic-inheritance-glyph.gif new file mode 100644 index 0000000000..467e2ddae9 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-inherit-forms-using-the-inheritance-picker-dialog-box/visual-basic-inheritance-glyph.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-join-lines/joined-beveled-lines.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-join-lines/joined-beveled-lines.gif new file mode 100644 index 0000000000..fdaec0d415 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-join-lines/joined-beveled-lines.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-load-and-display-metafiles/metafile-drawn-specified-location.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-load-and-display-metafiles/metafile-drawn-specified-location.png new file mode 100644 index 0000000000..067b9889b5 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-load-and-display-metafiles/metafile-drawn-specified-location.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/convert-font-units-example.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/convert-font-units-example.png new file mode 100644 index 0000000000..6a6dab10d0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/convert-font-units-example.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/example-output-code-arial-font.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/example-output-code-arial-font.png new file mode 100644 index 0000000000..1777e2ee6f Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/example-output-code-arial-font.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/various-font-metrics.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/various-font-metrics.png new file mode 100644 index 0000000000..46bde8db6c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-obtain-font-metrics/various-font-metrics.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/original-color-rotated-images.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/original-color-rotated-images.png new file mode 100644 index 0000000000..2e186d52f3 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/original-color-rotated-images.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-about-blue-axis.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-about-blue-axis.gif new file mode 100644 index 0000000000..8ae7bb3ec8 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-about-blue-axis.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-about-three-axes.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-about-three-axes.gif new file mode 100644 index 0000000000..a8219a4fec Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-about-three-axes.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-red-green-blue-axes.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-red-green-blue-axes.gif new file mode 100644 index 0000000000..fb40414eac Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/rotation-red-green-blue-axes.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/visualization-color-rotation.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/visualization-color-rotation.gif new file mode 100644 index 0000000000..42ec6ca855 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-colors/visualization-color-rotation.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-illustration.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-illustration.gif new file mode 100644 index 0000000000..c3681fcd12 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-illustration.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-metafile.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-metafile.png new file mode 100644 index 0000000000..30f5479739 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-metafile.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-photo.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-photo.png new file mode 100644 index 0000000000..b2c0094314 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-rotate-reflect-and-skew-images/reflected-skewed-rotated-photo.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-centered-line.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-centered-line.gif new file mode 100644 index 0000000000..361d374b05 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-centered-line.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-centered-rectangle.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-centered-rectangle.gif new file mode 100644 index 0000000000..51047e6d5b Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-centered-rectangle.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-inside-rectangle.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-inside-rectangle.gif new file mode 100644 index 0000000000..f93b705ba7 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-pen-width-and-alignment/green-pixels-inside-rectangle.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-tab-stops-in-drawn-text/tab-list-names-test-scores.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-tab-stops-in-drawn-text/tab-list-names-test-scores.png new file mode 100644 index 0000000000..24e625ef13 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-set-tab-stops-in-drawn-text/tab-list-names-test-scores.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-shear-colors/original-image-sheared-image.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-shear-colors/original-image-sheared-image.png new file mode 100644 index 0000000000..fe5ed3c88d Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-shear-colors/original-image-sheared-image.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tile-200x200.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tile-200x200.gif new file mode 100644 index 0000000000..55c7711779 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tile-200x200.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-flip.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-flip.gif new file mode 100644 index 0000000000..0dbbaddee0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-flip.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-vertical-flip.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-vertical-flip.gif new file mode 100644 index 0000000000..0660d5aaae Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-horizontal-vertical-flip.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-no-flip.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-no-flip.gif new file mode 100644 index 0000000000..c31dd28b51 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-tile-a-shape-with-an-image/rectangle-tiled-image-no-flip.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-translate-image-colors/original-image-translate-colors.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-translate-image-colors/original-image-translate-colors.png new file mode 100644 index 0000000000..e8eb3076bd Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-translate-image-colors/original-image-translate-colors.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-set-alpha-values-in-images/alpha-blending-matrix.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-set-alpha-values-in-images/alpha-blending-matrix.png new file mode 100644 index 0000000000..7feb1f0de2 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-set-alpha-values-in-images/alpha-blending-matrix.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/5x5-identity-matrix-color-transformation.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/5x5-identity-matrix-color-transformation.gif new file mode 100644 index 0000000000..46982e9bdd Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/5x5-identity-matrix-color-transformation.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/color-transformation.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/color-transformation.png new file mode 100644 index 0000000000..122f7e8a0d Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/color-transformation.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/multiplication-color-matrix.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/multiplication-color-matrix.gif new file mode 100644 index 0000000000..f2c762f9ce Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-matrix-to-transform-a-single-color/multiplication-color-matrix.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-remap-table/original-image-remap-colors.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-remap-table/original-image-remap-colors.png new file mode 100644 index 0000000000..15cac6cec5 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-color-remap-table/original-image-remap-colors.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-pen-to-draw-rectangles/drawn-rectangle-black-lines-dotted-lines.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-pen-to-draw-rectangles/drawn-rectangle-black-lines-dotted-lines.gif new file mode 100644 index 0000000000..344a9ffd51 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-a-pen-to-draw-rectangles/drawn-rectangle-black-lines-dotted-lines.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-antialiasing-with-text/antialiasing-text-quality-settings.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-antialiasing-with-text/antialiasing-text-quality-settings.png new file mode 100644 index 0000000000..aae28807e4 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-antialiasing-with-text/antialiasing-text-quality-settings.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-clipping-with-a-region/clipped-strings-polygon.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-clipping-with-a-region/clipped-strings-polygon.png new file mode 100644 index 0000000000..41a2032afc Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-clipping-with-a-region/clipped-strings-polygon.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-compositing-mode-to-control-alpha-blending/blend-ellipses-background.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-compositing-mode-to-control-alpha-blending/blend-ellipses-background.png new file mode 100644 index 0000000000..790810deb0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-compositing-mode-to-control-alpha-blending/blend-ellipses-background.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-compositing-mode-to-control-alpha-blending/ellipses-blended-background.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-compositing-mode-to-control-alpha-blending/ellipses-blended-background.png new file mode 100644 index 0000000000..1d6bdf473c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-compositing-mode-to-control-alpha-blending/ellipses-blended-background.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-interpolation-mode-to-control-image-quality-during-scaling/varied-interpolation-settings.png b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-interpolation-mode-to-control-image-quality-during-scaling/varied-interpolation-settings.png new file mode 100644 index 0000000000..790118ffa5 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/how-to-use-interpolation-mode-to-control-image-quality-during-scaling/varied-interpolation-settings.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/managing-the-state-of-a-graphics-object/set-clipping-region-setclip-method.png b/dotnet-desktop-guide/framework/winforms/advanced/media/managing-the-state-of-a-graphics-object/set-clipping-region-setclip-method.png new file mode 100644 index 0000000000..fcd3c2e901 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/managing-the-state-of-a-graphics-object/set-clipping-region-setclip-method.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/managing-the-state-of-a-graphics-object/set-rotation-pen-width-drawellipse-method.png b/dotnet-desktop-guide/framework/winforms/advanced/media/managing-the-state-of-a-graphics-object/set-rotation-pen-width-drawellipse-method.png new file mode 100644 index 0000000000..9a2c5aa0fc Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/managing-the-state-of-a-graphics-object/set-rotation-pen-width-drawellipse-method.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/using-a-gradient-brush-to-fill-shapes/rectangle-ellipse-gradient-brush.png b/dotnet-desktop-guide/framework/winforms/advanced/media/using-a-gradient-brush-to-fill-shapes/rectangle-ellipse-gradient-brush.png new file mode 100644 index 0000000000..ee49184f14 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/using-a-gradient-brush-to-fill-shapes/rectangle-ellipse-gradient-brush.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-container-clipped-lines.png b/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-container-clipped-lines.png new file mode 100644 index 0000000000..af7c5af9ab Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-container-clipped-lines.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-containers-illustration.png b/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-containers-illustration.png new file mode 100644 index 0000000000..6a1b74b5af Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-containers-illustration.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-containers-three-strings.png b/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-containers-three-strings.png new file mode 100644 index 0000000000..ad8ad5800e Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/using-nested-graphics-containers/nested-containers-three-strings.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/using-transformations-to-scale-colors/four-bar-scale-multiple-colors.png b/dotnet-desktop-guide/framework/winforms/advanced/media/using-transformations-to-scale-colors/four-bar-scale-multiple-colors.png new file mode 100644 index 0000000000..5c2fb80a5b Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/using-transformations-to-scale-colors/four-bar-scale-multiple-colors.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/using-transformations-to-scale-colors/four-bar-scale-one-color.png b/dotnet-desktop-guide/framework/winforms/advanced/media/using-transformations-to-scale-colors/four-bar-scale-one-color.png new file mode 100644 index 0000000000..7fa7b08051 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/using-transformations-to-scale-colors/four-bar-scale-one-color.png differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/walkthrough-creating-an-accessible-windows-based-application/visual-basic-pizza-order-form.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/walkthrough-creating-an-accessible-windows-based-application/visual-basic-pizza-order-form.gif new file mode 100644 index 0000000000..823fc4e89c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/walkthrough-creating-an-accessible-windows-based-application/visual-basic-pizza-order-form.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/media/walkthrough-demonstrating-visual-inheritance/visual-basic-inheritance-glyph.gif b/dotnet-desktop-guide/framework/winforms/advanced/media/walkthrough-demonstrating-visual-inheritance/visual-basic-inheritance-glyph.gif new file mode 100644 index 0000000000..467e2ddae9 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/advanced/media/walkthrough-demonstrating-visual-inheritance/visual-basic-inheritance-glyph.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/advanced/metafiles-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/metafiles-in-gdi.md new file mode 100644 index 0000000000..8b3b889ff0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/metafiles-in-gdi.md @@ -0,0 +1,36 @@ +--- +title: "Metafiles in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "images [Windows Forms], metafiles" + - "GDI+, metafiles" + - "metafiles" +ms.assetid: 51da872c-c783-440f-8bf6-1e580a966c31 +--- +# Metafiles in GDI+ +GDI+ provides the class so that you can record and display metafiles. A metafile, also called a vector image, is an image that is stored as a sequence of drawing commands and settings. The commands and settings recorded in a object can be stored in memory or saved to a file or stream. + +## Metafile Formats + GDI+ can display metafiles that have been stored in the following formats: + +- Windows Metafile (WMF) + +- Enhanced Metafile (EMF) + +- EMF+ + + GDI+ can record metafiles in the EMF and EMF+ formats, but not in the WMF format. + + EMF+ is an extension to EMF that allows GDI+ records to be stored. There are two variations on the EMF+ format: EMF+ Only and EMF+ Dual. EMF+ Only metafiles contain only GDI+ records. Such metafiles can be displayed by GDI+ but not by GDI. EMF+ Dual metafiles contain GDI+ and GDI records. Each GDI+ record in an EMF+ Dual metafile is paired with an alternate GDI record. Such metafiles can be displayed by GDI+ or by GDI. + + The following example displays a metafile that was previously saved as a file. The metafile is displayed with its upper-left corner at (100, 100). + + [!code-csharp[System.Drawing.ImagesBitmapsMetafiles#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs#21)] + [!code-vb[System.Drawing.ImagesBitmapsMetafiles#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb#21)] + +## See also + +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/multiple-document-interface-mdi-applications.md b/dotnet-desktop-guide/framework/winforms/advanced/multiple-document-interface-mdi-applications.md new file mode 100644 index 0000000000..ac79ffa994 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/multiple-document-interface-mdi-applications.md @@ -0,0 +1,32 @@ +--- +title: "Multiple-Document Interface (MDI) Applications" +description: Learn how Windows Forms multiple-document interface (MDI) applications enable you to display multiple documents at the same time, with each document displayed in its own window. +ms.date: "03/30/2017" +helpviewer_keywords: + - "forms [Windows Forms], MDI" + - "windows [Windows Forms], mDI" + - "Windows Forms, MDI applications" + - "MDI" +ms.assetid: 599faf75-13cf-49cc-ad3c-255545e5cb97 +--- +# Multiple-Document Interface (MDI) Applications +Multiple-document interface (MDI) applications enable you to display multiple documents at the same time, with each document displayed in its own window. MDI applications often have a Window menu item with submenus for switching between windows or documents. + +> [!NOTE] +> There are some behavior differences between MDI forms and single-document interface (SDI) windows in Windows Forms. The `Opacity` property does not affect the appearance of MDI child forms. Additionally, the method does not affect the behavior of MDI child forms. + +## In This Section + [How to: Create MDI Parent Forms](how-to-create-mdi-parent-forms.md) + Gives directions for creating the container for the multiple documents within an MDI application. + + [How to: Create MDI Child Forms](how-to-create-mdi-child-forms.md) + Gives directions for creating one or more windows that operate within an MDI parent form. + + [How to: Determine the Active MDI Child](how-to-determine-the-active-mdi-child.md) + Gives directions for verifying the child window that has focus (and sending its contents to the Clipboard). + + [How to: Send Data to the Active MDI Child](how-to-send-data-to-the-active-mdi-child.md) + Gives directions for transporting information to the active child window. + + [How to: Arrange MDI Child Forms](how-to-arrange-mdi-child-forms.md) + Gives directions for tiling, cascading, or arranging the child windows of an MDI application. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/networking-in-windows-forms-applications.md b/dotnet-desktop-guide/framework/winforms/advanced/networking-in-windows-forms-applications.md new file mode 100644 index 0000000000..e5110f0f52 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/networking-in-windows-forms-applications.md @@ -0,0 +1,30 @@ +--- +title: Networking +ms.date: "03/30/2017" +helpviewer_keywords: + - "networking [Windows Forms], Windows Forms" + - "Windows Forms, networking" +ms.assetid: babf8af3-8000-46e2-8c68-a42127efabba +--- +# Networking in Windows Forms Applications +The .NET Framework provides classes for displaying Web pages, downloading Web content, interacting with file transfer protocol (FTP) sites, and consuming Web Services, making it easy to build network functionality into your application. The following resources will help you understand the networking technologies of the .NET Framework and how you can integrate them into Windows Forms. + +## Reference + + The root namespace for classes in the .NET Framework that handle network connectivity. + + + A convenient class for retrieving Web or HTTP-based content programmatically. + + + A class for retrieving and sending files with FTP. + + + A managed wrapper class for the `WebBrowser` control that is included with Windows. + +## Related Sections + [Network Programming in the .NET Framework](https://docs.microsoft.com/dotnet/framework/network-programming/index) + An introduction to networking in the .NET Framework. + + [Windows Forms Data Binding](../windows-forms-data-binding.md) + Describes how to display database content in your application, either from a local data store or a database located on a network. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/open-and-closed-curves-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/open-and-closed-curves-in-gdi.md new file mode 100644 index 0000000000..2103acb3a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/open-and-closed-curves-in-gdi.md @@ -0,0 +1,52 @@ +--- +title: "Open and Closed Curves in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "curves [Windows Forms], filling" + - "GDI+, curves" + - "curves [Windows Forms], drawing" + - "curves" +ms.assetid: 08d2cc9a-dc9d-4eed-bcbb-2c8e2ca5d3ae +--- +# Open and Closed Curves in GDI+ +The following illustration shows two curves: one open and one closed. + + ![Open & Closed curves](./media/aboutgdip02-art24.gif "Aboutgdip02_art24") + +## Managed Interface for Curves + Closed curves have an interior and therefore can be filled with a brush. The class in GDI+ provides the following methods for filling closed shapes and curves: , , , , , , and . Whenever you call one of these methods, you must pass one of the specific brush types (, , , , or ) as an argument. + + The method is a companion to the method. Just as the method draws a portion of the outline of an ellipse, the method fills a portion of the interior of an ellipse. The following example draws an arc and fills the corresponding portion of the interior of the ellipse: + + [!code-csharp[LinesCurvesAndShapes#21](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#21)] + [!code-vb[LinesCurvesAndShapes#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#21)] + + The following illustration shows the arc and the filled pie. + + ![Open & Closed curves](./media/aboutgdip02-art25.gif "Aboutgdip02_art25") + + The method is a companion to the method. Both methods automatically close the curve by connecting the ending point to the starting point. The following example draws a curve that passes through (0, 0), (60, 20), and (40, 50). Then, the curve is automatically closed by connecting (40, 50) to the starting point (0, 0), and the interior is filled with a solid color. + + [!code-csharp[LinesCurvesAndShapes#22](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#22)] + [!code-vb[LinesCurvesAndShapes#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#22)] + + The method fills the interiors of the separate pieces of a path. If a piece of a path doesn't form a closed curve or shape, the method automatically closes that piece of the path before filling it. The following example draws and fills a path that consists of an arc, a cardinal spline, a string, and a pie: + + [!code-csharp[LinesCurvesAndShapes#23](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#23)] + [!code-vb[LinesCurvesAndShapes#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#23)] + + The following illustration shows the path with and without the solid fill. Note that the text in the string is outlined, but not filled, by the method. It is the method that paints the interiors of the characters in the string. + + ![String in a path](./media/aboutgdip02-art26.gif "Aboutgdip02_art26") + +## See also + +- +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) +- [Constructing and Drawing Paths](constructing-and-drawing-paths.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/overview-of-graphics.md b/dotnet-desktop-guide/framework/winforms/advanced/overview-of-graphics.md new file mode 100644 index 0000000000..2ca840dcda --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/overview-of-graphics.md @@ -0,0 +1,29 @@ +--- +title: "Overview of Graphics" +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [Windows Forms], using managed interface" + - "graphics [Windows Forms], about graphics" +ms.assetid: a602aef8-a8c8-4c36-9816-74e7bad96a68 +--- +# Overview of Graphics +GDI+ is an application programming interface (API) that forms the subsystem of the Microsoft Windows operating system. GDI+ is responsible for displaying information on screens and printers. As its name suggests, GDI+ is the successor to GDI, the Graphics Device Interface included with earlier versions of Windows. + +## Managed Class Interface + The GDI+ API is exposed through a set of classes deployed as managed code. This set of classes is called the *managed class interface* to GDI+. The following namespaces make up the managed class interface: + +- + +- + +- + +- + +- + + With a Graphics Device Interface, such as GDI+, you can display information on a screen or printer without having to be concerned about the details of a particular display device. The programmer makes calls to methods provided by GDI+ classes. Those methods, in turn, make the appropriate calls to specific device drivers. GDI+ insulates the application from the graphics hardware. It is this insulation that enables a programmer to create device-independent applications. + +## See also + +- [Graphics Overview](graphics-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/pens-lines-and-rectangles-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/pens-lines-and-rectangles-in-gdi.md new file mode 100644 index 0000000000..7e50c8200a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/pens-lines-and-rectangles-in-gdi.md @@ -0,0 +1,71 @@ +--- +title: "Pens, Lines, and Rectangles in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "lines" + - "GDI+, lines" + - "drawing [Windows Forms], rectangles" + - "rectangles" + - "drawing [Windows Forms], lines" + - "GDI+, pens" + - "examples [Windows Forms], drawing lines and shapes" + - "examples [Windows Forms], pens" + - "GDI+, rectangles" + - "examples [Windows Forms], GDI+" + - "lines [Windows Forms], dashed" +ms.assetid: 30b25aae-e3eb-4479-bdb8-187cf651fc84 +--- +# Pens, Lines, and Rectangles in GDI+ +To draw lines with GDI+ you need to create a object and a object. The object provides the methods that actually do the drawing, and the object stores attributes, such as line color, width, and style. + +## Drawing a Line + To draw a line, call the method of the object. The object is passed as one of the arguments to the method. The following example draws a line from the point (4, 2) to the point (12, 6): + + [!code-csharp[LinesCurvesAndShapes#41](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#41)] + [!code-vb[LinesCurvesAndShapes#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#41)] + + is an overloaded method of the class, so there are several ways you can supply it with arguments. For example, you can construct two objects and pass the objects as arguments to the method: + + [!code-csharp[LinesCurvesAndShapes#42](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#42)] + [!code-vb[LinesCurvesAndShapes#42](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#42)] + +## Constructing a Pen + You can specify certain attributes when you construct a object. For example, one `Pen` constructor allows you to specify color and width. The following example draws a blue line of width 2 from (0, 0) to (60, 30): + + [!code-csharp[LinesCurvesAndShapes#43](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#43)] + [!code-vb[LinesCurvesAndShapes#43](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#43)] + +## Dashed Lines and Line Caps + The object also exposes properties, such as , that you can use to specify features of the line. The following example draws a dashed line from (100, 50) to (300, 80): + + [!code-csharp[LinesCurvesAndShapes#44](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#44)] + [!code-vb[LinesCurvesAndShapes#44](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#44)] + + You can use the properties of the object to set many more attributes of the line. The and properties specify the appearance of the ends of the line; the ends can be flat, square, rounded, triangular, or a custom shape. The property lets you specify whether connected lines are mitered (joined with sharp corners), beveled, rounded, or clipped. The following illustration shows lines with various cap and join styles. + + ![Lines](./media/aboutgdip02-art04.gif "Aboutgdip02_art04") + +## Drawing a Rectangle + Drawing rectangles with GDI+ is similar to drawing lines. To draw a rectangle, you need a object and a object. The object provides a method, and the object stores attributes, such as line width and color. The object is passed as one of the arguments to the method. The following example draws a rectangle with its upper-left corner at (100, 50), a width of 80, and a height of 40: + + [!code-csharp[LinesCurvesAndShapes#45](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#45)] + [!code-vb[LinesCurvesAndShapes#45](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#45)] + + is an overloaded method of the class, so there are several ways you can supply it with arguments. For example, you can construct a object and pass the object to the method as an argument: + + [!code-csharp[LinesCurvesAndShapes#46](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#46)] + [!code-vb[LinesCurvesAndShapes#46](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#46)] + + A object has methods and properties for manipulating and gathering information about the rectangle. For example, the and methods change the size and position of the rectangle. The method tells you whether the rectangle intersects another given rectangle, and the method tells you whether a given point is inside the rectangle. + +## See also + +- +- +- +- [How to: Create a Pen](how-to-create-a-pen.md) +- [How to: Draw a Line on a Windows Form](how-to-draw-a-line-on-a-windows-form.md) +- [How to: Draw an Outlined Shape](how-to-draw-an-outlined-shape.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/polygons-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/polygons-in-gdi.md new file mode 100644 index 0000000000..b7e2752d5c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/polygons-in-gdi.md @@ -0,0 +1,33 @@ +--- +title: "Polygons in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "polygons" + - "drawing [Windows Forms], polygons" + - "GDI+, polygons" +ms.assetid: a72213d2-d69a-4c2b-a75c-be7b20390c13 +--- +# Polygons in GDI+ +A polygon is a closed shape with three or more straight sides. For example, a triangle is a polygon with three sides, a rectangle is a polygon with four sides, and a pentagon is a polygon with five sides. The following illustration shows several polygons. + + ![Polygons](./media/aboutgdip02-art07.gif "Aboutgdip02_art07") + +## Drawing a Polygon + To draw a polygon, you need a object, a object, and an array of (or ) objects. The object provides the method. The object stores attributes, such as width and color, of the line used to render the polygon, and the array of objects stores the points to be connected by straight lines. The object and the array of objects are passed as arguments to the method. The following example draws a three-sided polygon. Note that there are only three points in `myPointArray`: (0, 0), (50, 30), and (30, 60). The method automatically closes the polygon by drawing a line from (30, 60) back to the starting point (0, 0). + + [!code-csharp[LinesCurvesAndShapes#111](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#111)] + [!code-vb[LinesCurvesAndShapes#111](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#111)] + + The following illustration shows the polygon. + + ![Polygon](./media/aboutgdip02-art08.gif "Aboutgdip02_art08") + +## See also + +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Create a Pen](how-to-create-a-pen.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/power-management-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/power-management-in-windows-forms.md new file mode 100644 index 0000000000..05e7b94b21 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/power-management-in-windows-forms.md @@ -0,0 +1,34 @@ +--- +title: "Power Management" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "battery states" + - "power states" +ms.assetid: ad04a801-5682-4d88-92c5-26eb9cdb209a +--- +# Power Management in Windows Forms +Your Windows Forms applications can take advantage of the power management features in the Windows operating system. Your applications can monitor the power status of a computer and take action when a status change occurs. For example, if your application is running on a portable computer, you might want to disable certain features in your application when the computer's battery charge falls under a certain level. + + The .NET Framework provides a event that occurs whenever there is a change in power status, such as when a user suspends or resumes the operating system, or when the AC power status or battery status changes. The property of the class can be used to query for the current status, as shown in the following code example. + + [!code-csharp[PowerMode#1](~/samples/snippets/csharp/VS_Snippets_Winforms/powermode/cs/form1.cs#1)] + [!code-vb[PowerMode#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/powermode/vb/form1.vb#1)] + + Besides the enumerations, the property also contains enumerations for determining battery capacity () and battery charge percentage (, ). + + You can use the method of the to put a computer into hibernation or suspend mode. If the `force` argument is set to `false`, the operating system will broadcast an event to all applications requesting permission to suspend. If the `disableWakeEvent` argument is set to `true`, the operating system disables all wake events. + + The following code example demonstrates how to put a computer into hibernation. + + [!code-csharp[PowerMode#2](~/samples/snippets/csharp/VS_Snippets_Winforms/powermode/cs/form1.cs#2)] + [!code-vb[PowerMode#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/powermode/vb/form1.vb#2)] + +## See also + +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/advanced/properties-on-windows-forms-controls-that-support-accessibility-guidelines.md b/dotnet-desktop-guide/framework/winforms/advanced/properties-on-windows-forms-controls-that-support-accessibility-guidelines.md new file mode 100644 index 0000000000..5671045968 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/properties-on-windows-forms-controls-that-support-accessibility-guidelines.md @@ -0,0 +1,29 @@ +--- +title: Accessibility properties on controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, accessibility properties of controls" + - "accessibility [Windows Forms], Windows Forms control properties" +ms.assetid: ad3567a6-313b-4708-9e15-f487a831f049 +--- +# Properties on Windows Forms Controls That Support Accessibility Guidelines +Controls on the standard toolbox for Windows Forms support many of the accessibility guidelines, including exposing the keyboard focus and exposing the screen elements. + +## Planning Ahead for Accessibility + The controls' properties can be used to support other accessibility guidelines as shown in the following table. Additionally, you should use menus to provide access to program features. + +|Control Property|Considerations for Accessibility| +|----------------------|--------------------------------------| +|AccessibleDescription|The description is reported to accessibility aids such as screen readers. Accessibility aids are specialized programs and devices that help people with disabilities use computers more effectively.| +|AccessibleName|The name that will be reported to the accessibility aids.| +|AccessibleRole|Describes the use of the element in the user interface.| +|TabIndex|Creates a sensible navigational path through the form. It is important for controls without intrinsic labels, such as text boxes, to have their associated label immediately precede them in the tab order.| +|Text|Use the "&" character to create access keys. Using access keys is part of providing documented keyboard access to features.| +|Font Size|If the font size is not adjustable, then it should be set to 10 points or larger. Once the form's font size is set, all the controls added to the form thereafter will have the same size.| +|Forecolor|If this property is set to the default, then the user's color preferences will be used on the form.| +|Backcolor|If this property is set to the default, then the user's color preferences will be used on the form.| +|BackgroundImage|Leave this property blank to make text more readable.| + +## See also + +- [Walkthrough: Creating an Accessible Windows-based Application](walkthrough-creating-an-accessible-windows-based-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/recoloring-images.md b/dotnet-desktop-guide/framework/winforms/advanced/recoloring-images.md new file mode 100644 index 0000000000..f264819b2d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/recoloring-images.md @@ -0,0 +1,47 @@ +--- +title: "Recoloring Images" +ms.date: "03/30/2017" +helpviewer_keywords: + - "images [Windows Forms], recoloring" + - "recoloring images" + - "examples [Windows Forms], recoloring images" +ms.assetid: f28c54fd-9c80-4f6f-b242-55f7ffcda84b +--- +# Recoloring Images +Recoloring is the process of adjusting image colors. Some examples of recoloring are changing one color to another, adjusting a color's intensity relative to another color, adjusting the brightness or contrast of all colors, and converting colors to shades of gray. + +## In This Section + [How to: Use a Color Matrix to Transform a Single Color](how-to-use-a-color-matrix-to-transform-a-single-color.md) + Discusses using a color matrix to transform a color. + + [How to: Translate Image Colors](how-to-translate-image-colors.md) + Shows how to translate colors using a color matrix. + + [Using Transformations to Scale Colors](using-transformations-to-scale-colors.md) + Explains how to scale colors using a color matrix. + + [How to: Rotate Colors](how-to-rotate-colors.md) + Describes how to rotate a color using a color matrix. + + [How to: Shear Colors](how-to-shear-colors.md) + Defines shearing and explains how to shear colors using a color matrix. + + [How to: Use a Color Remap Table](how-to-use-a-color-remap-table.md) + Defines remapping and shows how to use a color remap table. + +## Reference + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. + +## Related Sections + [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) + Provides a list of topics regarding the different types of images. + + [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) + Contains a list of topics that show how to use different types of images. + + [Using Managed Graphics Classes](using-managed-graphics-classes.md) + Contains a list of topics describing how to use managed graphics classes. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/regions-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/regions-in-gdi.md new file mode 100644 index 0000000000..01e7a5e42f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/regions-in-gdi.md @@ -0,0 +1,40 @@ +--- +title: "Regions in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "GDI+, regions" + - "drawing [Windows Forms], regions" + - "regions" +ms.assetid: 52184f9b-16dd-4bbd-85be-029112644ceb +--- +# Regions in GDI+ +A region is a portion of the display area of an output device. Regions can be simple (a single rectangle) or complex (a combination of polygons and closed curves). The following illustration shows two regions: one constructed from a rectangle, and the other constructed from a path. + + ![Regions](./media/aboutgdip02-art27.gif "AboutGdip02_Art27") + +## Using Regions + Regions are often used for clipping and hit testing. Clipping involves restricting drawing to a certain region of the display area, usually the portion that needs to be updated. Hit testing involves checking to determine whether the cursor is in a certain region of the screen when a mouse button is pressed. + + You can construct a region from a rectangle or a path. You can also create complex regions by combining existing regions. The class provides the following methods for combining regions: , , , , and . + + The intersection of two regions is the set of all points belonging to both regions. The union is the set of all points belonging to one or the other or both regions. The complement of a region is the set of all points that are not in the region. The following illustration shows the intersection and union of the two regions shown in the preceding illustration. + + ![Regions](./media/aboutgdip02-art28.gif "AboutGdip02_Art28") + + The method, applied to a pair of regions, produces a region that contains all points that belong to one region or the other, but not both. The method, applied to a pair of regions, produces a region that contains all points in the first region that are not in the second region. The following illustration shows the regions that result from applying the and methods to the two regions shown at the beginning of this topic. + + ![Regions](./media/aboutgdip02-art29.gif "AboutGdip02_Art29") + + To fill a region, you need a object, a object, and a object. The object provides the method, and the object stores attributes of the fill, such as color or pattern. The following example fills a region with a solid color. + + [!code-csharp[LinesCurvesAndShapes#61](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#61)] + [!code-vb[LinesCurvesAndShapes#61](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#61)] + +## See also + +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [Using Regions](using-regions.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/restricting-the-drawing-surface-in-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/restricting-the-drawing-surface-in-gdi.md new file mode 100644 index 0000000000..fa6b69078b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/restricting-the-drawing-surface-in-gdi.md @@ -0,0 +1,33 @@ +--- +title: "Restricting the Drawing Surface in GDI+" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "GDI+, clipping" + - "clipping [Windows Forms], using GDI+" + - "GDI+, restricting drawing surface" +ms.assetid: 8b5f71d9-d2f0-4540-9c41-740f90fd4c26 +--- +# Restricting the Drawing Surface in GDI+ +Clipping involves restricting drawing to a certain rectangle or region. The following illustration shows the string "Hello" clipped to a heart-shaped region. + + ![Restricted Drawing Surface](./media/aboutgdip02-art30.gif "AboutGdip02_Art30") + +## Clipping with Regions + Regions can be constructed from paths, and paths can contain the outlines of strings, so you can use outlined text for clipping. The following illustration shows a set of concentric ellipses clipped to the interior of a string of text. + + ![Restricted Drawing Surface](./media/aboutgdip02-art31.gif "AboutGdip02_Art31") + + To draw with clipping, create a object, set its property, and then call the drawing methods of that same object: + + [!code-csharp[LinesCurvesAndShapes#91](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#91)] + [!code-vb[LinesCurvesAndShapes#91](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#91)] + +## See also + +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [Using Regions](using-regions.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/structure-of-the-graphics-interface.md b/dotnet-desktop-guide/framework/winforms/advanced/structure-of-the-graphics-interface.md new file mode 100644 index 0000000000..3a7a35601e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/structure-of-the-graphics-interface.md @@ -0,0 +1,23 @@ +--- +title: "Structure of the Graphics Interface" +ms.date: "03/30/2017" +helpviewer_keywords: + - "GDI+, using managed interface" + - "graphics [Windows Forms], class structure" +ms.assetid: 010a1e46-656b-40a1-8d5d-87aa05ee1243 +--- +# Structure of the Graphics Interface +The managed class interface to GDI+ contains about 60 classes, 50 enumerations, and 8 structures. The class is at the core of GDI+ functionality; it is the class that actually draws lines, curves, figures, images, and text. + +## Important Classes + Many classes work together with the class. For example, the method receives a object, which holds attributes (color, width, dash style, and the like) of the line to be drawn. The method can receive a pointer to a object, which works with the object to fill a rectangle with a gradually changing color. and objects influence the way a object draws text. A object stores and manipulates the world transformation of a object, which is used to rotate, scale, and flip images. + + GDI+ provides several structures (for example, , , and ) for organizing graphics data. Also, certain classes serve primarily as structured data types. For example, the class is a helper for the class, and the class is a helper for the class. + + GDI+ defines several enumerations, which are collections of related constants. For example, the enumeration contains the elements , , and , which specify styles that can be used to join two lines. + +## See also + +- [Graphics Overview](graphics-overview-windows-forms.md) +- [About GDI+ Managed Code](about-gdi-managed-code.md) +- [Using Managed Graphics Classes](using-managed-graphics-classes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/system-information-and-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/system-information-and-windows-forms.md new file mode 100644 index 0000000000..c0bcfad43c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/system-information-and-windows-forms.md @@ -0,0 +1,42 @@ +--- +title: System Information +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "domain names [Windows Forms], retrieving" + - "SystemInformation class [Windows Forms]" + - "user names [Windows Forms], retrieving" + - "system information [Windows Forms]" +ms.assetid: 30cf43a3-8cb2-4ff3-862b-6c34576616a8 +--- +# System Information and Windows Forms +Sometimes it is necessary to gather information about the computer that your application is running on in order to make decisions in your code. For example, you might have a function that is only applicable when connected to a particular network domain; in this case you would need a way to determine the domain and disable the function if the domain is not present. + + Windows Forms applications can use the class to determine a number of things about a computer at run time. The following example demonstrates using the class to retrieve the and : + +```vb +Dim User As String = Windows.Forms.SystemInformation.UserName +Dim Domain As String = Windows.Forms.SystemInformation.UserDomainName + +MessageBox.Show("Good morning " & User & ". You are connected to " _ +& Domain) +``` + +```csharp +string User = SystemInformation.UserName; +string Domain = SystemInformation.UserDomainName; + +MessageBox.Show("Good morning " + User + ". You are connected to " ++ Domain); +``` + + All members of the class are read-only; you cannot modify a user's settings. There are over 100 members of the class, returning information on everything from the number of monitors attached to the computer () to the spacing of icons in Windows Explorer ( and ). + + Some of the more useful members of the class include , , , and . + +## See also + +- +- [Power Management in Windows Forms](power-management-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/three-categories-of-graphics-services.md b/dotnet-desktop-guide/framework/winforms/advanced/three-categories-of-graphics-services.md new file mode 100644 index 0000000000..1193236c88 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/three-categories-of-graphics-services.md @@ -0,0 +1,40 @@ +--- +title: "Three Categories of Graphics Services" +ms.date: "03/30/2017" +helpviewer_keywords: + - "imaging" + - "graphics [Windows Forms], categories" + - "2D vector graphics" + - "vector graphics" + - "typography" +ms.assetid: 068c0ef3-f6ee-4d58-a7b6-eb2531ead408 +--- +# Three Categories of Graphics Services +The graphics offerings in Windows Forms fall into the following three broad categories: + +- Two-dimensional (2-D) vector graphics + +- Imaging + +- Typography + +## 2D Vector Graphics + Two-dimensional vector graphics, such as lines, curves, and figures, are primitives that are specified by sets of points on a coordinate system. For example, a straight line is specified by its two endpoints, and a rectangle is specified by a point giving the location of its upper-left corner and a pair of numbers giving its width and height. A simple path is specified by an array of points that are connected by straight lines. A Bézier spline is a sophisticated curve specified by four control points. + + GDI+ provides classes and structures that store information about the primitives themselves, classes that store information about how the primitives will be drawn, and classes that actually do the drawing. For example, the structure stores the location and size of a rectangle; the class stores information about line color, line width, and line style; and the class has methods for drawing lines, rectangles, paths, and other figures. There are also several classes that store information about how closed figures and paths will be filled with colors or patterns. + + You can record a vector image, which is a sequence of graphics commands, in a metafile. GDI+ provides the class for recording, displaying, and saving metafiles. With the and classes, you can inspect the data stored in a metafile header. + +## Imaging + Certain kinds of pictures are difficult or impossible to display with the techniques of vector graphics. For example, the pictures on toolbar buttons and the pictures that appear as icons are difficult to specify as collections of lines and curves. A high-resolution digital photograph of a crowded baseball stadium is even more difficult to create with vector techniques. Images of this type are stored as bitmaps, which are arrays of numbers that represent the colors of individual dots on the screen. GDI+ provides the class for displaying, manipulating, and saving bitmaps. + +## Typography + Typography is the display of text in a variety of fonts, sizes, and styles. GDI+ provides extensive support for this complex task. One of the new features in GDI+ is subpixel antialiasing, which gives text rendered on an LCD screen a smoother appearance. + + In addition, Windows Forms offers the option to draw text with GDI capabilities in its class. + +## See also + +- [Graphics Overview](graphics-overview-windows-forms.md) +- [About GDI+ Managed Code](about-gdi-managed-code.md) +- [Using Managed Graphics Classes](using-managed-graphics-classes.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/toc.yml b/dotnet-desktop-guide/framework/winforms/advanced/toc.yml new file mode 100644 index 0000000000..7af8fd6818 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/toc.yml @@ -0,0 +1,413 @@ +- name: Enhancing Windows Forms Applications + href: index.md + items: + - name: Graphics and Drawing in Windows Forms + href: graphics-and-drawing-in-windows-forms.md + items: + - name: Graphics Overview + href: graphics-overview-windows-forms.md + items: + - name: Overview of Graphics + href: overview-of-graphics.md + - name: Three Categories of Graphics Services + href: three-categories-of-graphics-services.md + - name: Structure of the Graphics Interface + href: structure-of-the-graphics-interface.md + - name: About GDI+ Managed Code + href: about-gdi-managed-code.md + items: + - name: Lines, Curves, and Shapes + href: lines-curves-and-shapes.md + items: + - name: Vector Graphics Overview + href: vector-graphics-overview.md + - name: Pens, Lines, and Rectangles in GDI+ + href: pens-lines-and-rectangles-in-gdi.md + - name: Ellipses and Arcs in GDI+ + href: ellipses-and-arcs-in-gdi.md + - name: Polygons in GDI+ + href: polygons-in-gdi.md + - name: Cardinal Splines in GDI+ + href: cardinal-splines-in-gdi.md + - name: Bézier Splines in GDI+ + href: bezier-splines-in-gdi.md + - name: Graphics Paths in GDI+ + href: graphics-paths-in-gdi.md + - name: Brushes and Filled Shapes in GDI+ + href: brushes-and-filled-shapes-in-gdi.md + - name: Open and Closed Curves in GDI+ + href: open-and-closed-curves-in-gdi.md + - name: Regions in GDI+ + href: regions-in-gdi.md + - name: Restricting the Drawing Surface in GDI+ + href: restricting-the-drawing-surface-in-gdi.md + - name: Antialiasing with Lines and Curves + href: antialiasing-with-lines-and-curves.md + - name: Images, Bitmaps, and Metafiles + href: images-bitmaps-and-metafiles.md + items: + - name: Types of Bitmaps + href: types-of-bitmaps.md + - name: Metafiles in GDI+ + href: metafiles-in-gdi.md + - name: Drawing, Positioning, and Cloning Images in GDI+ + href: drawing-positioning-and-cloning-images-in-gdi.md + - name: Cropping and Scaling Images in GDI+ + href: cropping-and-scaling-images-in-gdi.md + - name: Coordinate Systems and Transformations + href: coordinate-systems-and-transformations.md + items: + - name: Types of Coordinate Systems + href: types-of-coordinate-systems.md + - name: Matrix Representation of Transformations + href: matrix-representation-of-transformations.md + - name: Global and Local Transformations + href: global-and-local-transformations.md + - name: Using Managed Graphics Classes + href: using-managed-graphics-classes.md + items: + - name: Getting Started with Graphics Programming + href: getting-started-with-graphics-programming.md + items: + - name: "How to: Create Graphics Objects for Drawing" + href: how-to-create-graphics-objects-for-drawing.md + - name: "How to: Create a Pen" + href: how-to-create-a-pen.md + - name: "How to: Set the Color of a Pen" + href: how-to-set-the-color-of-a-pen.md + - name: "How to: Create a Solid Brush" + href: how-to-create-a-solid-brush.md + - name: "How to: Draw a Line on a Windows Form" + href: how-to-draw-a-line-on-a-windows-form.md + - name: "How to: Draw an Outlined Shape" + href: how-to-draw-an-outlined-shape.md + - name: "How to: Draw a Filled Rectangle on a Windows Form" + href: how-to-draw-a-filled-rectangle-on-a-windows-form.md + - name: "How to: Draw a Filled Ellipse on a Windows Form" + href: how-to-draw-a-filled-ellipse-on-a-windows-form.md + - name: "How to: Draw Text on a Windows Form" + href: how-to-draw-text-on-a-windows-form.md + - name: "How to: Draw Vertical Text on a Windows Form" + href: how-to-draw-vertical-text-on-a-windows-form.md + - name: "How to: Render Images with GDI+" + href: how-to-render-images-with-gdi.md + - name: "How to: Create a Shaped Windows Form" + href: how-to-create-a-shaped-windows-form.md + - name: "How to: Copy Pixels for Reducing Flicker in Windows Forms" + href: how-to-copy-pixels-for-reducing-flicker-in-windows-forms.md + - name: Using a Pen to Draw Lines and Shapes + href: using-a-pen-to-draw-lines-and-shapes.md + items: + - name: "How to: Use a Pen to Draw Lines" + href: how-to-use-a-pen-to-draw-lines.md + - name: "How to: Use a Pen to Draw Rectangles" + href: how-to-use-a-pen-to-draw-rectangles.md + - name: "How to: Set Pen Width and Alignment" + href: how-to-set-pen-width-and-alignment.md + - name: "How to: Draw a Line with Line Caps" + href: how-to-draw-a-line-with-line-caps.md + - name: "How to: Join Lines" + href: how-to-join-lines.md + - name: "How to: Draw a Custom Dashed Line" + href: how-to-draw-a-custom-dashed-line.md + - name: "How to: Draw a Line Filled with a Texture" + href: how-to-draw-a-line-filled-with-a-texture.md + - name: Using a Brush to Fill Shapes + href: using-a-brush-to-fill-shapes.md + items: + - name: "How to: Fill a Shape with a Solid Color" + href: how-to-fill-a-shape-with-a-solid-color.md + - name: "How to: Fill a Shape with a Hatch Pattern" + href: how-to-fill-a-shape-with-a-hatch-pattern.md + - name: "How to: Fill a Shape with an Image Texture" + href: how-to-fill-a-shape-with-an-image-texture.md + - name: "How to: Tile a Shape with an Image" + href: how-to-tile-a-shape-with-an-image.md + - name: Using a Gradient Brush to Fill Shapes + href: using-a-gradient-brush-to-fill-shapes.md + items: + - name: "How to: Create a Linear Gradient" + href: how-to-create-a-linear-gradient.md + - name: "How to: Create a Path Gradient" + href: how-to-create-a-path-gradient.md + - name: "How to: Apply Gamma Correction to a Gradient" + href: how-to-apply-gamma-correction-to-a-gradient.md + - name: Working with Images, Bitmaps, Icons, and Metafiles + href: working-with-images-bitmaps-icons-and-metafiles.md + items: + - name: "How to: Draw an Existing Bitmap to the Screen" + href: how-to-draw-an-existing-bitmap-to-the-screen.md + - name: "How to: Load and Display Metafiles" + href: how-to-load-and-display-metafiles.md + - name: "How to: Crop and Scale Images" + href: how-to-crop-and-scale-images.md + - name: "How to: Rotate, Reflect, and Skew Images" + href: how-to-rotate-reflect-and-skew-images.md + - name: "How to: Use Interpolation Mode to Control Image Quality During Scaling" + href: how-to-use-interpolation-mode-to-control-image-quality-during-scaling.md + - name: "How to: Create Thumbnail Images" + href: how-to-create-thumbnail-images.md + - name: "How to: Improve Performance by Avoiding Automatic Scaling" + href: how-to-improve-performance-by-avoiding-automatic-scaling.md + - name: "How to: Read Image Metadata" + href: how-to-read-image-metadata.md + - name: "How to: Create a Bitmap at Run Time" + href: how-to-create-a-bitmap-at-run-time.md + - name: "How to: Extract the Icon Associated with a File in Windows Forms" + href: how-to-extract-the-icon-associated-with-a-file-in-windows-forms.md + - name: Alpha Blending Lines and Fills + href: alpha-blending-lines-and-fills.md + items: + - name: "How to: Draw Opaque and Semitransparent Lines" + href: how-to-draw-opaque-and-semitransparent-lines.md + - name: "How to: Draw with Opaque and Semitransparent Brushes" + href: how-to-draw-with-opaque-and-semitransparent-brushes.md + - name: "How to: Use Compositing Mode to Control Alpha Blending" + href: how-to-use-compositing-mode-to-control-alpha-blending.md + - name: "How to: Use a Color Matrix to Set Alpha Values in Images" + href: how-to-use-a-color-matrix-to-set-alpha-values-in-images.md + - name: Using Fonts and Text + href: using-fonts-and-text.md + items: + - name: "How to: Construct Font Families and Fonts" + href: how-to-construct-font-families-and-fonts.md + - name: "How to: Draw Text at a Specified Location" + href: how-to-draw-text-at-a-specified-location.md + - name: "How to: Draw Wrapped Text in a Rectangle" + href: how-to-draw-wrapped-text-in-a-rectangle.md + - name: "How to: Draw Text with GDI" + href: how-to-draw-text-with-gdi.md + - name: "How to: Align Drawn Text" + href: how-to-align-drawn-text.md + - name: "How to: Create Vertical Text" + href: how-to-create-vertical-text.md + - name: "How to: Set Tab Stops in Drawn Text" + href: how-to-set-tab-stops-in-drawn-text.md + - name: "How to: Enumerate Installed Fonts" + href: how-to-enumerate-installed-fonts.md + - name: "How to: Create a Private Font Collection" + href: how-to-create-a-private-font-collection.md + - name: "How to: Obtain Font Metrics" + href: how-to-obtain-font-metrics.md + - name: "How to: Use Antialiasing with Text" + href: how-to-use-antialiasing-with-text.md + - name: Constructing and Drawing Curves + href: constructing-and-drawing-curves.md + items: + - name: "How to: Draw Cardinal Splines" + href: how-to-draw-cardinal-splines.md + - name: "How to: Draw a Single Bézier Spline" + href: how-to-draw-a-single-bezier-spline.md + - name: "How to: Draw a Sequence of Bézier Splines" + href: how-to-draw-a-sequence-of-bezier-splines.md + - name: Constructing and Drawing Paths + href: constructing-and-drawing-paths.md + items: + - name: "How to: Create Figures from Lines, Curves, and Shapes" + href: how-to-create-figures-from-lines-curves-and-shapes.md + - name: "How to: Fill Open Figures" + href: how-to-fill-open-figures.md + - name: "How to: Flatten a Curved Path into a Line" + href: how-to-flatten-a-curved-path-into-a-line.md + - name: Using Transformations in Managed GDI+ + href: using-transformations-in-managed-gdi.md + items: + - name: Using the World Transformation + href: using-the-world-transformation.md + - name: Why Transformation Order Is Significant + href: why-transformation-order-is-significant.md + - name: Using Graphics Containers + href: using-graphics-containers.md + items: + - name: Managing the State of a Graphics Object + href: managing-the-state-of-a-graphics-object.md + - name: Using Nested Graphics Containers + href: using-nested-graphics-containers.md + - name: Using Regions + href: using-regions.md + items: + - name: "How to: Use Hit Testing with a Region" + href: how-to-use-hit-testing-with-a-region.md + - name: "How to: Use Clipping with a Region" + href: how-to-use-clipping-with-a-region.md + - name: Recoloring Images + href: recoloring-images.md + items: + - name: "How to: Use a Color Matrix to Transform a Single Color" + href: how-to-use-a-color-matrix-to-transform-a-single-color.md + - name: "How to: Translate Image Colors" + href: how-to-translate-image-colors.md + - name: Using Transformations to Scale Colors + href: using-transformations-to-scale-colors.md + - name: "How to: Rotate Colors" + href: how-to-rotate-colors.md + - name: "How to: Shear Colors" + href: how-to-shear-colors.md + - name: "How to: Use a Color Remap Table" + href: how-to-use-a-color-remap-table.md + - name: Using Image Encoders and Decoders in Managed GDI+ + href: using-image-encoders-and-decoders-in-managed-gdi.md + items: + - name: "How to: List Installed Encoders" + href: how-to-list-installed-encoders.md + - name: "How to: List Installed Decoders" + href: how-to-list-installed-decoders.md + - name: "How to: Determine the Parameters Supported by an Encoder" + href: how-to-determine-the-parameters-supported-by-an-encoder.md + - name: "How to: Convert a BMP image to a PNG image" + href: how-to-convert-a-bmp-image-to-a-png-image.md + - name: "How to: Set JPEG Compression Level" + href: how-to-set-jpeg-compression-level.md + - name: Using Double Buffering + href: using-double-buffering.md + items: + - name: Double Buffered Graphics + href: double-buffered-graphics.md + - name: "How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls" + href: how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md + - name: "How to: Manually Manage Buffered Graphics" + href: how-to-manually-manage-buffered-graphics.md + - name: "How to: Manually Render Buffered Graphics" + href: how-to-manually-render-buffered-graphics.md + - name: Application Settings for Windows Forms + href: application-settings-for-windows-forms.md + items: + - name: Application Settings Overview + href: application-settings-overview.md + - name: Application Settings Architecture + href: application-settings-architecture.md + - name: Application Settings Attributes + href: application-settings-attributes.md + - name: Application Settings for Custom Controls + href: application-settings-for-custom-controls.md + - name: Using Application Settings and User Settings + href: using-application-settings-and-user-settings.md + items: + - name: "How To: Create a New Setting at Design Time" + href: how-to-create-a-new-setting-at-design-time.md + - name: "How To: Change the Value of an Existing Setting at Design Time" + href: how-to-change-the-value-of-an-existing-setting-at-design-time.md + - name: "How To: Change the Value of a Setting Between Application Sessions" + href: how-to-change-the-value-of-a-setting-between-application-sessions.md + - name: "How To: Read Settings at Run Time With C#" + href: how-to-read-settings-at-run-time-with-csharp.md + - name: "How To: Write User Settings at Run Time with C#" + href: how-to-write-user-settings-at-run-time-with-csharp.md + - name: "How To: Add Multiple Sets of Settings To Your Application in C#" + href: how-to-add-multiple-sets-of-settings-to-your-application-in-csharp.md + - name: "How to: Create Application Settings" + href: how-to-create-application-settings.md + - name: "How to: Validate Application Settings" + href: how-to-validate-application-settings.md + - name: Windows Forms Print Support + href: windows-forms-print-support.md + items: + - name: "How to: Create Standard Windows Forms Print Jobs" + href: how-to-create-standard-windows-forms-print-jobs.md + - name: "How to: Capture User Input from a PrintDialog at Run Time" + href: how-to-capture-user-input-from-a-printdialog-at-run-time.md + - name: "How to: Choose the Printers Attached to a User's Computer in Windows Forms" + href: how-to-choose-the-printers-attached-to-user-computer-in-windows-forms.md + - name: "How to: Print Graphics in Windows Forms" + href: how-to-print-graphics-in-windows-forms.md + - name: "How to: Print a Multi-Page Text File in Windows Forms" + href: how-to-print-a-multi-page-text-file-in-windows-forms.md + - name: "How to: Complete Windows Forms Print Jobs" + href: how-to-complete-windows-forms-print-jobs.md + - name: "How to: Print a Windows Form" + href: how-to-print-a-windows-form.md + - name: "How to: Print in Windows Forms Using Print Preview" + href: how-to-print-in-windows-forms-using-print-preview.md + - name: Drag-and-Drop Operations and Clipboard Support + href: drag-and-drop-operations-and-clipboard-support.md + items: + - name: "Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms" + href: walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md + - name: "How to: Perform Drag-and-Drop Operations Between Applications" + href: how-to-perform-drag-and-drop-operations-between-applications.md + - name: "How to: Add Data to the Clipboard" + href: how-to-add-data-to-the-clipboard.md + - name: "How to: Retrieve Data from the Clipboard" + href: how-to-retrieve-data-from-the-clipboard.md + - name: Networking in Windows Forms Applications + href: networking-in-windows-forms-applications.md + - name: Globalizing Windows Forms + href: globalizing-windows-forms.md + items: + - name: International Fonts in Windows Forms and Controls + href: international-fonts-in-windows-forms-and-controls.md + - name: Bi-Directional Support for Windows Forms Applications + href: bi-directional-support-for-windows-forms-applications.md + - name: Display of Asian Characters with the ImeMode Property + href: display-of-asian-characters-with-the-imemode-property.md + - name: Windows Forms and Unmanaged Applications + href: windows-forms-and-unmanaged-applications.md + items: + - name: Windows Forms and Unmanaged Applications Overview + href: windows-forms-and-unmanaged-applications-overview.md + - name: "How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread" + href: how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md + - name: "How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method" + href: com-interop-by-displaying-a-windows-form-shadow.md + - name: System Information and Windows Forms + href: system-information-and-windows-forms.md + - name: Power Management in Windows Forms + href: power-management-in-windows-forms.md + - name: Help Systems in Windows Forms Applications + href: help-systems-in-windows-forms-applications.md + - name: Windows Forms Visual Inheritance + href: windows-forms-visual-inheritance.md + items: + - name: "How to: Inherit Windows Forms" + href: how-to-inherit-windows-forms.md + - name: "How to: Inherit Forms Using the Inheritance Picker Dialog Box" + href: how-to-inherit-forms-using-the-inheritance-picker-dialog-box.md + - name: Effects of Modifying a Base Form's Appearance + href: effects-of-modifying-base-form-appearance.md + - name: "Walkthrough: Demonstrating Visual Inheritance" + href: walkthrough-demonstrating-visual-inheritance.md + - name: "How to: Use the Modifiers and GenerateMember Properties" + href: how-to-use-the-modifiers-and-generatemember-properties.md + - name: Multiple-Document Interface (MDI) Applications + href: multiple-document-interface-mdi-applications.md + items: + - name: "How to: Create MDI Parent Forms" + href: how-to-create-mdi-parent-forms.md + - name: "How to: Create MDI Child Forms" + href: how-to-create-mdi-child-forms.md + - name: "How to: Determine the Active MDI Child" + href: how-to-determine-the-active-mdi-child.md + - name: "How to: Send Data to the Active MDI Child" + href: how-to-send-data-to-the-active-mdi-child.md + - name: "How to: Arrange MDI Child Forms" + href: how-to-arrange-mdi-child-forms.md + - name: Integrating User Help in Windows Forms + href: integrating-user-help-in-windows-forms.md + items: + - name: "How to: Provide Help in a Windows Application" + href: how-to-provide-help-in-a-windows-application.md + - name: "How to: Display Pop-up Help" + href: how-to-display-pop-up-help.md + - name: Control Help Using ToolTips + href: control-help-using-tooltips.md + - name: Windows Forms Accessibility + href: windows-forms-accessibility.md + items: + - name: "Walkthrough: Creating an Accessible Windows-based Application" + href: walkthrough-creating-an-accessible-windows-based-application.md + items: + - name: Properties on Windows Forms Controls That Support Accessibility Guidelines + href: properties-on-windows-forms-controls-that-support-accessibility-guidelines.md + - name: Using WPF Controls + href: using-wpf-controls.md + items: + - name: "How to: Copy and Paste an ElementHost Control at Design Time" + href: how-to-copy-and-paste-an-elementhost-control-at-design-time.md + - name: "Walkthrough: Arranging WPF Content on Windows Forms at Design Time" + href: walkthrough-arranging-wpf-content-on-windows-forms-at-design-time.md + - name: "Walkthrough: Creating New WPF Content on Windows Forms at Design Time" + href: walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md + - name: "Walkthrough: Assigning WPF Content on Windows Forms at Design Time" + href: walkthrough-assigning-wpf-content-on-windows-forms-at-design-time.md + - name: "Walkthrough: Styling WPF Content" + href: walkthrough-styling-wpf-content.md diff --git a/dotnet-desktop-guide/framework/winforms/advanced/types-of-bitmaps.md b/dotnet-desktop-guide/framework/winforms/advanced/types-of-bitmaps.md new file mode 100644 index 0000000000..db30a2c938 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/types-of-bitmaps.md @@ -0,0 +1,89 @@ +--- +title: "Types of Bitmaps" +description: Learn about bitmap types and the supported GDI+ graphics file formats, including BMP, JPG, GIF, PNG, and TIFF. +ms.date: "03/30/2017" +helpviewer_keywords: + - "jpeg files" + - "TIFF files" + - "gif files" + - "Graphics Interchange Format" + - "Joint Photographic Experts Group" + - ".jpeg files" + - ".gif files" + - "graphics [Windows Forms], file formats" + - "images [Windows Forms], file formats" + - "Portable Network Graphics" + - ".bmp files" + - "EXIF file format" + - "PNG files" + - "pictures [Windows Forms], file formats" + - "Tag Image File Format" + - "bitmaps [Windows Forms], file format" + - "Exchangeable Image File" +ms.assetid: 6be085a2-2c13-47c8-b80a-c18b32777d8d +--- +# Types of Bitmaps +A bitmap is an array of bits that specify the color of each pixel in a rectangular array of pixels. The number of bits devoted to an individual pixel determines the number of colors that can be assigned to that pixel. For example, if each pixel is represented by 4 bits, then a given pixel can be assigned one of 16 different colors (2^4 = 16). The following table shows a few examples of the number of colors that can be assigned to a pixel represented by a given number of bits. + +|Bits per pixel|Number of colors that can be assigned to a pixel| +|--------------------|------------------------------------------------------| +|1|2^1 = 2| +|2|2^2 = 4| +|4|2^4 = 16| +|8|2^8 = 256| +|16|2^16 = 65,536| +|24|2^24 = 16,777,216| + + Disk files that store bitmaps usually contain one or more information blocks that store information such as the number of bits per pixel, number of pixels in each row, and number of rows in the array. Such a file might also contain a color table (sometimes called a color palette). A color table maps numbers in the bitmap to specific colors. The following illustration shows an enlarged image along with its bitmap and color table. Each pixel is represented by a 4-bit number, so there are 2^4 = 16 colors in the color table. Each color in the table is represented by a 24-bit number: 8 bits for red, 8 bits for green, and 8 bits for blue. The numbers are shown in hexadecimal (base 16) form: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. + + ![Bitmap sample](./media/aboutgdip03-art01.gif "AboutGdip03_Art01") + + Look at the pixel in row 3, column 5 of the image. The corresponding number in the bitmap is 1. The color table tells us that 1 represents the color red so the pixel is red. All the entries in the top row of the bitmap are 3. The color table tells us that 3 represents blue, so all the pixels in the top row of the image are blue. + +> [!NOTE] +> Some bitmaps are stored in bottom-up format; the numbers in the first row of the bitmap correspond to the pixels in the bottom row of the image. + + A bitmap that stores indexes into a color table is called a palette-indexed bitmap. Some bitmaps have no need for a color table. For example, if a bitmap uses 24 bits per pixel, that bitmap can store the colors themselves rather than indexes into a color table. The following illustration shows a bitmap that stores colors directly (24 bits per pixel) rather than using a color table. The illustration also shows an enlarged view of the corresponding image. In the bitmap, FFFFFF represents white, FF0000 represents red, 00FF00 represents green, and 0000FF represents blue. + + ![Bitmap sample](./media/aboutgdip03-art02.gif "AboutGdip03_Art02") + +## Graphics File Formats + There are many standard formats for saving bitmaps in disk files. GDI+ supports the graphics file formats described in the following paragraphs. + +### BMP + BMP is a standard format used by Windows to store device-independent and application-independent images. The number of bits per pixel (1, 4, 8, 15, 24, 32, or 64) for a given BMP file is specified in a file header. BMP files with 24 bits per pixel are common. BMP files are usually not compressed and, therefore, are not well suited for transfer across the Internet. + +### Graphics Interchange Format (GIF) + GIF is a common format for images that appear on Web pages. GIFs work well for line drawings, pictures with blocks of solid color, and pictures with sharp boundaries between colors. GIFs are compressed, but no information is lost in the compression process; a decompressed image is exactly the same as the original. One color in a GIF can be designated as transparent, so that the image will have the background color of any Web page that displays it. A sequence of GIF images can be stored in a single file to form an animated GIF. GIFs store at most 8 bits per pixel, so they are limited to 256 colors. + +### Joint Photographic Experts Group (JPEG) + JPEG is a compression scheme that works well for natural scenes such as scanned photographs. Some information is lost in the compression process, but often the loss is imperceptible to the human eye. JPEGs store 24 bits per pixel, so they are capable of displaying more than 16 million colors. JPEGs do not support transparency or animation. + + The level of compression in JPEG images is configurable, but higher compression levels (smaller files) result in more loss of information. A 20:1 compression ratio often produces an image that the human eye finds difficult to distinguish from the original. The following illustration shows a BMP image and two JPEG images that were compressed from that BMP image. The first JPEG has a compression ratio of 4:1 and the second JPEG has a compression ratio of about 8:1. + + ![Filetype samples](./media/aboutgdip03-art03.gif "AboutGdip03_Art03") + + JPEG compression does not work well for line drawings, blocks of solid color, and sharp boundaries. The following illustration shows a BMP along with two JPEGs and a GIF. The JPEGs and the GIF were compressed from the BMP. The compression ratio is 4:1 for the GIF, 4:1 for the smaller JPEG, and 8:3 for the larger JPEG. Note that the GIF maintains the sharp boundaries along the lines, but the JPEGs tend to blur the boundaries. + + ![Filetypes](./media/aboutgdip03-art03a.gif "AboutGdip03_Art03A") + + JPEG is a compression scheme, not a file format. JPEG File Interchange Format (JFIF) is a file format commonly used for storing and transferring images that have been compressed according to the JPEG scheme. JFIF files displayed by Web browsers use the .jpg extension. + +### Exchangeable Image File (EXIF) + EXIF is a file format used for photographs captured by digital cameras. An EXIF file contains an image that is compressed according to the JPEG specification. An EXIF file also contains information about the photograph (date taken, shutter speed, exposure time, and so on) and information about the camera (manufacturer, model, and so on). + +### Portable Network Graphics (PNG) + The PNG format retains many of the advantages of the GIF format but also provides capabilities beyond those of GIF. Like GIF files, PNG files are compressed with no loss of information. PNG files can store colors with 8, 24, or 48 bits per pixel and grayscales with 1, 2, 4, 8, or 16 bits per pixel. In contrast, GIF files can use only 1, 2, 4, or 8 bits per pixel. A PNG file can also store an alpha value for each pixel, which specifies the degree to which the color of that pixel is blended with the background color. + + PNG improves on GIF in its ability to progressively display an image (that is, to display better and better approximations of the image as it arrives over a network connection). PNG files can contain gamma correction and color correction information so that the images can be accurately rendered on a variety of display devices. + +### Tag Image File Format (TIFF) + TIFF is a flexible and extendable format that is supported by a wide variety of platforms and image-processing applications. TIFF files can store images with an arbitrary number of bits per pixel and can employ a variety of compression algorithms. Several images can be stored in a single, multiple-page TIFF file. Information related to the image (scanner make, host computer, type of compression, orientation, samples per pixel, and so on) can be stored in the file and arranged through the use of tags. The TIFF format can be extended as needed by the approval and addition of new tags. + +## See also + +- +- +- +- [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) +- [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/types-of-coordinate-systems.md b/dotnet-desktop-guide/framework/winforms/advanced/types-of-coordinate-systems.md new file mode 100644 index 0000000000..b01141a7ad --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/types-of-coordinate-systems.md @@ -0,0 +1,94 @@ +--- +title: "Types of Coordinate Systems" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "transformations [Windows Forms], page" + - "unit of measure" + - "world coordinate system" + - "page coordinate system" + - "page transformation" + - "device coordinate system" + - "world transformation" + - "coordinate systems" + - "transformations [Windows Forms], world" +ms.assetid: c61ff50a-eb1d-4e6c-83cd-f7e9764cfa9f +--- +# Types of Coordinate Systems +GDI+ uses three coordinate spaces: world, page, and device. World coordinates are the coordinates used to model a particular graphic world and are the coordinates you pass to methods in the .NET Framework. Page coordinates refer to the coordinate system used by a drawing surface, such as a form or control. Device coordinates are the coordinates used by the physical device being drawn on, such as a screen or sheet of paper. When you make the call `myGraphics.DrawLine(myPen, 0, 0, 160, 80)`, the points that you pass to the method—`(0, 0)` and `(160, 80)`—are in the world coordinate space. Before GDI+ can draw the line on the screen, the coordinates pass through a sequence of transformations. One transformation, called the world transformation, converts world coordinates to page coordinates, and another transformation, called the page transformation, converts page coordinates to device coordinates. + +## Transforms and Coordinate Systems + Suppose you want to work with a coordinate system that has its origin in the body of the client area rather than the upper-left corner. Say, for example, that you want the origin to be 100 pixels from the left edge of the client area and 50 pixels from the top of the client area. The following illustration shows such a coordinate system. + + ![Coordinate System](./media/aboutgdip05-art01.gif "AboutGdip05_art01") + + When you make the call `myGraphics.DrawLine(myPen, 0, 0, 160, 80)`, you get the line shown in the following illustration. + + ![Coordinate System](./media/aboutgdip05-art02.gif "AboutGdip05_art02") + + The coordinates of the endpoints of your line in the three coordinate spaces are as follows: + +||| +|-|-| +|World|(0, 0) to (160, 80)| +|Page|(100, 50) to (260, 130)| +|Device|(100, 50) to (260, 130)| + + Note that the page coordinate space has its origin at the upper-left corner of the client area; this will always be the case. Also note that because the unit of measure is the pixel, the device coordinates are the same as the page coordinates. If you set the unit of measure to something other than pixels (for example, inches), then the device coordinates will be different from the page coordinates. + + The world transformation, which maps world coordinates to page coordinates, is held in the property of the class. In the preceding example, the world transformation is a translation 100 units in the x direction and 50 units in the y direction. The following example sets the world transformation of a object and then uses that object to draw the line shown in the preceding figure: + + [!code-csharp[System.Drawing.CoordinateSystems#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#31)] + [!code-vb[System.Drawing.CoordinateSystems#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#31)] + + The page transformation maps page coordinates to device coordinates. The class provides the and properties for manipulating the page transformation. The class also provides two read-only properties, and , for examining the horizontal and vertical dots per inch of the display device. + + You can use the property of the class to specify a unit of measure other than the pixel. + +> [!NOTE] +> You cannot set the property to , as this is not a physical unit and will cause an exception. + + The following example draws a line from (0, 0) to (2, 1), where the point (2, 1) is 2 inches to the right and 1 inch down from the point (0, 0): + + [!code-csharp[System.Drawing.CoordinateSystems#32](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#32)] + [!code-vb[System.Drawing.CoordinateSystems#32](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#32)] + +> [!NOTE] +> If you don't specify a pen width when you construct your pen, the preceding example will draw a line that is one inch wide. You can specify the pen width in the second argument to the constructor: + + [!code-csharp[System.Drawing.CoordinateSystems#33](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#33)] + [!code-vb[System.Drawing.CoordinateSystems#33](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#33)] + + If we assume that the display device has 96 dots per inch in the horizontal direction and 96 dots per inch in the vertical direction, the endpoints of the line in the preceding example have the following coordinates in the three coordinate spaces: + +||| +|-|-| +|World|(0, 0) to (2, 1)| +|Page|(0, 0) to (2, 1)| +|Device|(0, 0) to (192, 96)| + + Note that because the origin of the world coordinate space is at the upper-left corner of the client area, the page coordinates are the same as the world coordinates. + + You can combine the world and page transformations to achieve a variety of effects. For example, suppose you want to use inches as the unit of measure and you want the origin of your coordinate system to be 2 inches from the left edge of the client area and 1/2 inch from the top of the client area. The following example sets the world and page transformations of a object and then draws a line from (0, 0) to (2, 1): + + [!code-csharp[System.Drawing.CoordinateSystems#34](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs#34)] + [!code-vb[System.Drawing.CoordinateSystems#34](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb#34)] + + The following illustration shows the line and coordinate system. + + ![Coordinate System](./media/aboutgdip05-art03.gif "AboutGdip05_art03") + + If we assume that the display device has 96 dots per inch in the horizontal direction and 96 dots per inch in the vertical direction, the endpoints of the line in the preceding example have the following coordinates in the three coordinate spaces: + +||| +|-|-| +|World|(0, 0) to (2, 1)| +|Page|(2, 0.5) to (4, 1.5)| +|Device|(192, 48) to (384, 144)| + +## See also + +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) +- [Matrix Representation of Transformations](matrix-representation-of-transformations.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-a-brush-to-fill-shapes.md b/dotnet-desktop-guide/framework/winforms/advanced/using-a-brush-to-fill-shapes.md new file mode 100644 index 0000000000..853bb7db6c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-a-brush-to-fill-shapes.md @@ -0,0 +1,50 @@ +--- +title: "Using a Brush to Fill Shapes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "examples [Windows Forms], brushes" + - "shapes [Windows Forms], filling" + - "brushes" +ms.assetid: bf8f7fff-5a90-41e8-9051-494449fb2844 +--- +# Using a Brush to Fill Shapes +A GDI+ object is used to fill the interior of a closed shape. GDI+ defines several fill styles: solid color, hatch pattern, image texture, and color gradient. + +## In This Section + [How to: Fill a Shape with a Solid Color](how-to-fill-a-shape-with-a-solid-color.md) + Describes how to use a solid-color brush to fill shapes. + + [How to: Fill a Shape with a Hatch Pattern](how-to-fill-a-shape-with-a-hatch-pattern.md) + Shows how to use a hatch brush to fill shapes. + + [How to: Fill a Shape with an Image Texture](how-to-fill-a-shape-with-an-image-texture.md) + Explains how to use a texture brush to fill shapes. + + [How to: Tile a Shape with an Image](how-to-tile-a-shape-with-an-image.md) + Describes how to tile an image in a shape. + +## Reference + + Describes this class and contains links to all of its members + + + Describes this class and contains links to all of its members + + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. + +## Related Sections + [Using a Gradient Brush to Fill Shapes](using-a-gradient-brush-to-fill-shapes.md) + Contains a list of topics that show how to use a gradient brush. + + [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) + Provides a list of topics that demonstrate how to draw outlined shapes. + + [Using Managed Graphics Classes](using-managed-graphics-classes.md) + Contains a list of topics describing how to use managed graphics classes. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-a-gradient-brush-to-fill-shapes.md b/dotnet-desktop-guide/framework/winforms/advanced/using-a-gradient-brush-to-fill-shapes.md new file mode 100644 index 0000000000..90cb49c70c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-a-gradient-brush-to-fill-shapes.md @@ -0,0 +1,34 @@ +--- +title: "Using a Gradient Brush to Fill Shapes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "brushes [Windows Forms], gradient brushes" + - "gradient brushes" + - "examples [Windows Forms], gradient brushes" +ms.assetid: 2c6037b9-05bd-44c0-a22a-19584b722524 +--- +# Using a Gradient Brush to Fill Shapes +You can use a gradient brush to fill a shape with a gradually changing color. For example, you can use a horizontal gradient to fill a shape with color that changes gradually as you move from the left edge of the shape to the right edge. Imagine a rectangle with a left edge that is black (represented by red, green, and blue components 0, 0, 0) and a right edge that is red (represented by 255, 0, 0). If the rectangle is 256 pixels wide, the red component of a given pixel will be one greater than the red component of the pixel to its left. The leftmost pixel in a row has color components (0, 0, 0), the second pixel has (1, 0, 0), the third pixel has (2, 0, 0), and so on, until you get to the rightmost pixel, which has color components (255, 0, 0). These interpolated color values make up the color gradient. + + A linear gradient changes color as you move horizontally, vertically, or parallel to a specified slanted line. A path gradient changes color as you move about the interior and boundary of a path. You can customize path gradients to achieve a wide variety of effects. + + The following illustration shows a rectangle filled with a linear gradient brush and an ellipse filled with a path gradient brush: + + ![A rectangle filled with a gradient brush with an ellipse.](./media/using-a-gradient-brush-to-fill-shapes/rectangle-ellipse-gradient-brush.png) + +## In This Section + [How to: Create a Linear Gradient](how-to-create-a-linear-gradient.md) + Shows how to create a linear gradient using the class. + + [How to: Create a Path Gradient](how-to-create-a-path-gradient.md) + Describes how to create a path gradient using the class. + + [How to: Apply Gamma Correction to a Gradient](how-to-apply-gamma-correction-to-a-gradient.md) + Explains how to use gamma correction with a gradient brush. + +## Reference + + Contains a description of this class and has links to all of its members. + + + Contains a description of this class and has links to all of its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-a-pen-to-draw-lines-and-shapes.md b/dotnet-desktop-guide/framework/winforms/advanced/using-a-pen-to-draw-lines-and-shapes.md new file mode 100644 index 0000000000..36258662dd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-a-pen-to-draw-lines-and-shapes.md @@ -0,0 +1,38 @@ +--- +title: "Using a Pen to Draw Lines and Shapes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "pens" + - "examples [Windows Forms], drawing lines and shapes" + - "examples [Windows Forms], pens" + - "drawing" +ms.assetid: 8a7542ab-3e9e-443f-8405-2d6053528e20 +--- +# Using a Pen to Draw Lines and Shapes +Use GDI+ `Pen` objects to draw line segments, curves, and the outlines of shapes. In this section, *line* refers to any of these, unless specified to mean only a line segment. Set the properties of a pen to control the color, width, alignment, and style of lines drawn with that pen. + +## In This Section + [How to: Use a Pen to Draw Lines](how-to-use-a-pen-to-draw-lines.md) + Explains how to draw lines. + + [How to: Use a Pen to Draw Rectangles](how-to-use-a-pen-to-draw-rectangles.md) + Describes how to draw rectangles. + + [How to: Set Pen Width and Alignment](how-to-set-pen-width-and-alignment.md) + Explains how to change the width and alignment of a `Pen` object. + + [How to: Draw a Line with Line Caps](how-to-draw-a-line-with-line-caps.md) + Describes how to add end caps when drawing a line. + + [How to: Join Lines](how-to-join-lines.md) + Shows how to join two lines. + + [How to: Draw a Custom Dashed Line](how-to-draw-a-custom-dashed-line.md) + Describes how to draw a dashed line. + + [How to: Draw a Line Filled with a Texture](how-to-draw-a-line-filled-with-a-texture.md) + Explains how to draw a texture-filled line. + +## Reference + + Describes this class and has links to all its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-application-settings-and-user-settings.md b/dotnet-desktop-guide/framework/winforms/advanced/using-application-settings-and-user-settings.md new file mode 100644 index 0000000000..d8290b83f2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-application-settings-and-user-settings.md @@ -0,0 +1,42 @@ +--- +title: "Using Application Settings and User Settings" +ms.date: "03/30/2017" +description: Learn how to use application settings and user settings to create and access values that are persisted between application execution sessions. +helpviewer_keywords: + - "user settings [Windows Forms]" + - "application settings [Windows Forms], how-to topics" +ms.assetid: 54682d3b-1cbf-4683-9351-012b8b4286b5 +--- +# Using Application Settings and User Settings +Starting with the .NET Framework 2.0, you can create and access values that are persisted between application execution sessions. These values are called *settings*. Settings can represent user preferences, or valuable information the application needs to use. For example, you might create a series of settings that store user preferences for the color scheme of an application. Or you might store the connection string that specifies a database that your application uses. Settings allow you to both persist information that is critical to the application outside the code, and to create profiles that store the preferences of individual users. + + The topics in this section describe how to use settings at design time and run time. + +## In This Section + [How To: Create a New Setting at Design Time](how-to-create-a-new-setting-at-design-time.md) + + Explains how to use Visual Studio to create a new setting for an application. + + [How To: Change the Value of an Existing Setting at Design Time](how-to-change-the-value-of-an-existing-setting-at-design-time.md) + + Describes how to use Visual Studio to change the value of an existing setting. + + [How To: Change the Value of a Setting Between Application Sessions](how-to-change-the-value-of-a-setting-between-application-sessions.md) + + Details how to change the value of a setting in a compiled application between application sessions. + + [How To: Read Settings at Run Time With C#](how-to-read-settings-at-run-time-with-csharp.md) + + Describes how to use code to read settings with C#. + + [How To: Write User Settings at Run Time with C#](how-to-write-user-settings-at-run-time-with-csharp.md) + + Explains how to use code to write and save the values of user settings with C#. + + [How To: Add Multiple Sets of Settings To Your Application in C#](how-to-add-multiple-sets-of-settings-to-your-application-in-csharp.md) + + Details how to add multiple sets of settings to an application with C#. + +## See also + +- [Application Settings for Windows Forms](application-settings-for-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-double-buffering.md b/dotnet-desktop-guide/framework/winforms/advanced/using-double-buffering.md new file mode 100644 index 0000000000..cf2c62cf07 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-double-buffering.md @@ -0,0 +1,35 @@ +--- +title: "Using Double Buffering" +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [Windows Forms], double buffering" + - "double buffering" + - "flicker [Windows Forms], reducing in Windows Forms" + - "buffering [Windows Forms], double buffering" +ms.assetid: dc484e33-7101-4e4b-ada5-d3c96155fbcd +--- +# Using Double Buffering +You can use double-buffered graphics to reduce flicker in your applications that contain complex painting operations. The .NET Framework contains built-in support for double-buffering or you can manage and render graphics manually. + +## In This Section + [Double Buffered Graphics](double-buffered-graphics.md) + Introduces double buffering concept and outlines .NET Framework support. + + [How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls](how-to-reduce-graphics-flicker-with-double-buffering-for-forms-and-controls.md) + Demonstrates how to use the default double buffering support in the .NET Framework. + + [How to: Manually Manage Buffered Graphics](how-to-manually-manage-buffered-graphics.md) + Shows how to manage double buffering in applications. + + [How to: Manually Render Buffered Graphics](how-to-manually-render-buffered-graphics.md) + Demonstrates how to render double-buffered graphics. + +## Reference + + Control method that enables double buffering. + + + Provides methods for creating graphics buffers. + + + Provides access to the buffered graphics context for a application domain. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-fonts-and-text.md b/dotnet-desktop-guide/framework/winforms/advanced/using-fonts-and-text.md new file mode 100644 index 0000000000..c171595b09 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-fonts-and-text.md @@ -0,0 +1,63 @@ +--- +title: "Using Fonts and Text" +ms.date: "03/30/2017" +helpviewer_keywords: + - "GDI [Windows Forms], drawing text [Windows Forms]" + - "text [Windows Forms], drawing in Windows Forms" + - "examples [Windows Forms], fonts and text" + - "fonts [Windows Forms], using in Windows Forms" + - "strings [Windows Forms], drawing in Windows Forms" +ms.assetid: d43640f3-da94-4df2-a29d-a9d021a1c069 +--- +# Using Fonts and Text +There are several classes offered by GDI+ and GDI for drawing text on Windows Forms. The GDI+ class has several methods that allow you to specify various features of text, such as location, bounding rectangle, font, and format. In addition, you can draw and measure text with GDI using the static and methods offered by the `TextRenderer` class. The GDI methods also allow you to specify location, font, and format. You can choose either GDI or GDI+ for text rendering; however, GDI generally offers better performance and more accurate text measuring. Other classes that contribute to text rendering include `FontFamily`, `Font`, , and `TextFormatFlags`. + +## In This Section + [How to: Construct Font Families and Fonts](how-to-construct-font-families-and-fonts.md) + Shows how to create `Font` and `FontFamily` objects. + + [How to: Draw Text at a Specified Location](how-to-draw-text-at-a-specified-location.md) + Describes how to draw text in a certain location using GDI+ and GDI. + + [How to: Draw Wrapped Text in a Rectangle](how-to-draw-wrapped-text-in-a-rectangle.md) + Explains how to draw text in a rectangle using GDI+ and GDI. + + [How to: Draw Text with GDI](how-to-draw-text-with-gdi.md) + Demonstrates how to use GDI for drawing text. + + [How to: Align Drawn Text](how-to-align-drawn-text.md) + Shows how to format GDI+ and GDI text. + + [How to: Create Vertical Text](how-to-create-vertical-text.md) + Describes how to draw vertically aligned text with GDI+. + + [How to: Set Tab Stops in Drawn Text](how-to-set-tab-stops-in-drawn-text.md) + Shows how draw text with tab stops with GDI+. + + [How to: Enumerate Installed Fonts](how-to-enumerate-installed-fonts.md) + Explains how to list the names of installed fonts. + + [How to: Create a Private Font Collection](how-to-create-a-private-font-collection.md) + Describes how to create a object. + + [How to: Obtain Font Metrics](how-to-obtain-font-metrics.md) + Shows how to obtain font metrics such as cell ascent and descent. + + [How to: Use Antialiasing with Text](how-to-use-antialiasing-with-text.md) + Explains how to use antialiasing when drawing text. + +## Reference + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-graphics-containers.md b/dotnet-desktop-guide/framework/winforms/advanced/using-graphics-containers.md new file mode 100644 index 0000000000..e68cee31a0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-graphics-containers.md @@ -0,0 +1,22 @@ +--- +title: "Using Graphics Containers" +ms.date: "03/30/2017" +helpviewer_keywords: + - "graphics [Windows Forms], using containers" + - "graphics containers" + - "examples [Windows Forms], graphics containers" +ms.assetid: 74632f91-cefa-4f51-ab7c-f9ac91942caf +--- +# Using Graphics Containers +A object provides methods such as , , and for displaying vector images, raster images, and text. A object also has several properties that influence the quality and orientation of the items that are drawn. For example, the smoothing mode property determines whether antialiasing is applied to lines and curves, and the world transformation property influences the position and rotation of the items that are drawn. + + A object is associated with a particular display device. When you use a object to draw in a window, the object is also associated with that particular window. + + A object can be thought of as a container because it holds a set of properties that influence drawing and it is linked to device-specific information. You can create a secondary container within an existing object by calling the method of that object. + +## In This Section + [Managing the State of a Graphics Object](managing-the-state-of-a-graphics-object.md) + Describes how manage the quality settings, clipping area and transformations of a object. + + [Using Nested Graphics Containers](using-nested-graphics-containers.md) + Shows how to use containers to control the state of the object. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-image-encoders-and-decoders-in-managed-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/using-image-encoders-and-decoders-in-managed-gdi.md new file mode 100644 index 0000000000..a6885f5e75 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-image-encoders-and-decoders-in-managed-gdi.md @@ -0,0 +1,64 @@ +--- +title: "Using Image Encoders and Decoders in Managed GDI+" +ms.date: "03/30/2017" +helpviewer_keywords: + - "image encoders [Windows Forms], using" + - "image decoders [Windows Forms], using" +ms.assetid: 0e838ea1-4e7e-4334-b882-ab25df607b8b +--- +# Using Image Encoders and Decoders in Managed GDI+ +The namespace provides the and classes for storing and manipulating images. By using image encoders in GDI+, you can write images from memory to disk. By using image decoders in GDI+, you can load images from disk into memory. An encoder translates the data in an or object into a designated disk file format. A decoder translates the data in a disk file to the format required by the and objects. + + GDI+ has built-in encoders and decoders that support the following file types: + +- BMP + +- GIF + +- JPEG + +- PNG + +- TIFF + + GDI+ also has built-in decoders that support the following file types: + +- WMF + +- EMF + +- ICON + + The following topics discuss encoders and decoders in more detail: + +## In This Section + [How to: List Installed Encoders](how-to-list-installed-encoders.md) + Describes how to list the encoders available on a computer. + + [How to: List Installed Decoders](how-to-list-installed-decoders.md) + Describes how to list the decoders available on a computer. + + [How to: Determine the Parameters Supported by an Encoder](how-to-determine-the-parameters-supported-by-an-encoder.md) + Describes how to list the supported by an encoder. + + [How to: Convert a BMP image to a PNG image](how-to-convert-a-bmp-image-to-a-png-image.md) + Describes how to save a image in a different image format. + + [How to: Set JPEG Compression Level](how-to-set-jpeg-compression-level.md) + Describes how to change the quality level of an image. + +## Reference + + + + + + + + + + +## Related Sections + [About GDI+ Managed Code](about-gdi-managed-code.md) + + [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-managed-graphics-classes.md b/dotnet-desktop-guide/framework/winforms/advanced/using-managed-graphics-classes.md new file mode 100644 index 0000000000..d041593e52 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-managed-graphics-classes.md @@ -0,0 +1,57 @@ +--- +title: "Using Managed Graphics Classes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "GDI+, managed classes" + - "graphics [Windows Forms], using in Windows Forms" + - "graphics [Windows Forms], managed classes" +ms.assetid: e6d1a42d-2100-46aa-97e6-a5ddc0baaae5 +--- +# Using Managed Graphics Classes +The following topics describe how to use the GDI+ API in the managed class framework. + +## In This Section + [Getting Started with Graphics Programming](getting-started-with-graphics-programming.md) + Describes how to accomplish basic tasks with GDI+. + + [Using a Pen to Draw Lines and Shapes](using-a-pen-to-draw-lines-and-shapes.md) + Demonstrates how to construct a pen and use it to draw a variety of lines and shapes. + + [Using a Brush to Fill Shapes](using-a-brush-to-fill-shapes.md) + Demonstrates how to construct a brush and fill shapes with a variety of effects. + + [Using a Gradient Brush to Fill Shapes](using-a-gradient-brush-to-fill-shapes.md) + Shows how to create and use different types of gradient brushes. + + [Working with Images, Bitmaps, Icons, and Metafiles](working-with-images-bitmaps-icons-and-metafiles.md) + Demonstrates how to construct and manipulate images. + + [Alpha Blending Lines and Fills](alpha-blending-lines-and-fills.md) + Demonstrates how to achieve transparency for shapes and lines. + + [Using Fonts and Text](using-fonts-and-text.md) + Shows how to draw text and use fonts and font families. + + [Constructing and Drawing Curves](constructing-and-drawing-curves.md) + Shows how to draw Cardinal and Bezier splines. + + [Constructing and Drawing Paths](constructing-and-drawing-paths.md) + Shows how to create figures using paths. + + [Using Transformations in Managed GDI+](using-transformations-in-managed-gdi.md) + Demonstrates matrix transformations. + + [Using Graphics Containers](using-graphics-containers.md) + Shows how to manage graphics object state and nested graphics containers. + + [Using Regions](using-regions.md) + Demonstrates hit testing and clipping with regions. + + [Recoloring Images](recoloring-images.md) + Demonstrates various aspects of manipulating colors. + + [Using Image Encoders and Decoders in Managed GDI+](using-image-encoders-and-decoders-in-managed-gdi.md) + Show how to use image encoders and decoders to manipulate images. + + [Double Buffered Graphics](double-buffered-graphics.md) + Demonstrates how to reduce flicker with double buffering. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-nested-graphics-containers.md b/dotnet-desktop-guide/framework/winforms/advanced/using-nested-graphics-containers.md new file mode 100644 index 0000000000..2761cd0138 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-nested-graphics-containers.md @@ -0,0 +1,56 @@ +--- +title: "Using Nested Graphics Containers" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "graphics [Windows Forms], nested containers" + - "graphics [Windows Forms], clipping" + - "graphics [Windows Forms], transformations in nested objects" +ms.assetid: a0d9f178-43a4-4323-bb5a-d3e3f77ae6c1 +--- +# Using Nested Graphics Containers +GDI+ provides containers that you can use to temporarily replace or augment part of the state in a object. You create a container by calling the method of a object. You can call repeatedly to form nested containers. Each call to must be paired with a call to . + +## Transformations in Nested Containers + The following example creates a object and a container within that object. The world transformation of the object is a translation 100 units in the x direction and 80 units in the y direction. The world transformation of the container is a 30-degree rotation. The code makes the call `DrawRectangle(pen, -60, -30, 120, 60)` twice. The first call to is inside the container; that is, the call is in between the calls to and . The second call to is after the call to . + + [!code-csharp[System.Drawing.MiscLegacyTopics#61](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#61)] + [!code-vb[System.Drawing.MiscLegacyTopics#61](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#61)] + + In the preceding code, the rectangle drawn from inside the container is transformed first by the world transformation of the container (rotation) and then by the world transformation of the object (translation). The rectangle drawn from outside the container is transformed only by the world transformation of the object (translation). The following illustration shows the two rectangles: + + ![Illustration that shows nested containers.](./media/using-nested-graphics-containers/nested-containers-illustration.png) + +## Clipping in Nested Containers + The following example demonstrates how nested containers handle clipping regions. The code creates a object and a container within that object. The clipping region of the object is a rectangle, and the clipping region of the container is an ellipse. The code makes two calls to the method. The first call to is inside the container, and the second call to is outside the container (after the call to ). The first line is clipped by the intersection of the two clipping regions. The second line is clipped only by the rectangular clipping region of the object. + + [!code-csharp[System.Drawing.MiscLegacyTopics#62](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#62)] + [!code-vb[System.Drawing.MiscLegacyTopics#62](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#62)] + + The following illustration shows the two clipped lines: + + ![Illustration that shows a nested container with clipped lines.](./media/using-nested-graphics-containers/nested-container-clipped-lines.png) + + As the two preceding examples show, transformations and clipping regions are cumulative in nested containers. If you set the world transformations of the container and the object, both transformations will apply to items drawn from inside the container. The transformation of the container will be applied first, and the transformation of the object will be applied second. If you set the clipping regions of the container and the object, items drawn from inside the container will be clipped by the intersection of the two clipping regions. + +## Quality Settings in Nested Containers + Quality settings (, , and the like) in nested containers are not cumulative; rather, the quality settings of the container temporarily replace the quality settings of a object. When you create a new container, the quality settings for that container are set to default values. For example, suppose you have a object with a smoothing mode of . When you create a container, the smoothing mode inside the container is the default smoothing mode. You are free to set the smoothing mode of the container, and any items drawn from inside the container will be drawn according to the mode you set. Items drawn after the call to will be drawn according to the smoothing mode () that was in place before the call to . + +## Several Layers of Nested Containers + You are not limited to one container in a object. You can create a sequence of containers, each nested in the preceding, and you can specify the world transformation, clipping region, and quality settings of each of those nested containers. If you call a drawing method from inside the innermost container, the transformations will be applied in order, starting with the innermost container and ending with the outermost container. Items drawn from inside the innermost container will be clipped by the intersection of all the clipping regions. + + The following example creates a object and sets its text rendering hint to . The code creates two containers, one nested within the other. The text rendering hint of the outer container is set to , and the text rendering hint of the inner container is set to . The code draws three strings: one from the inner container, one from the outer container, and one from the object itself. + + [!code-csharp[System.Drawing.MiscLegacyTopics#63](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#63)] + [!code-vb[System.Drawing.MiscLegacyTopics#63](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#63)] + + The following illustration shows the three strings. The strings drawn from the inner container and from the object are smoothed by antialiasing. The string drawn from the outer container is not smoothed by antialiasing because the property is set to . + + ![Illustration that shows the strings drawn from nested containers.](./media/using-nested-graphics-containers/nested-containers-three-strings.png) + +## See also + +- +- [Managing the State of a Graphics Object](managing-the-state-of-a-graphics-object.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-regions.md b/dotnet-desktop-guide/framework/winforms/advanced/using-regions.md new file mode 100644 index 0000000000..a526f124c9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-regions.md @@ -0,0 +1,26 @@ +--- +title: "Using Regions" +ms.date: "03/30/2017" +helpviewer_keywords: + - "examples [Windows Forms], regions" + - "regions [Windows Forms], using" +ms.assetid: 7809295b-870f-4107-a8b5-8386c298acd5 +--- +# Using Regions +The GDI+ class allows you to define a custom shape. The shape can be made up of lines, polygons, and curves. + + Two common uses for regions are hit testing and clipping. Hit testing is determining whether the mouse was clicked in a certain region of the screen. Clipping is restricting drawing to a certain region. + +## In This Section + [How to: Use Hit Testing with a Region](how-to-use-hit-testing-with-a-region.md) + Shows how to use a to perform a hit test. + + [How to: Use Clipping with a Region](how-to-use-clipping-with-a-region.md) + Explains how to set the clipping region for a object. + +## Reference + + Describes this class and contains links to all of its members. + + + Describes this class and contains links to all of its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-the-world-transformation.md b/dotnet-desktop-guide/framework/winforms/advanced/using-the-world-transformation.md new file mode 100644 index 0000000000..f9dae8e891 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-the-world-transformation.md @@ -0,0 +1,42 @@ +--- +title: "Using the World Transformation" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "graphics [Windows Forms], world transformation" + - "world transformation [Windows Forms], examples" +ms.assetid: 1e717711-1361-448e-aa49-0f3ec43110c9 +--- +# Using the World Transformation +The world transformation is a property of the class. The numbers that specify the world transformation are stored in a object, which represents a 3×3 matrix. The and classes have several methods for setting the numbers in the world transformation matrix. + +## Different Types of Transformations + In the following example, the code first creates a 50×50 rectangle and locates it at the origin (0, 0). The origin is at the upper-left corner of the client area. + + [!code-csharp[System.Drawing.MiscLegacyTopics#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#11)] + [!code-vb[System.Drawing.MiscLegacyTopics#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#11)] + + The following code applies a scaling transformation that expands the rectangle by a factor of 1.75 in the x direction and shrinks the rectangle by a factor of 0.5 in the y direction: + + [!code-csharp[System.Drawing.MiscLegacyTopics#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#12)] + [!code-vb[System.Drawing.MiscLegacyTopics#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#12)] + + The result is a rectangle that is longer in the x direction and shorter in the y direction than the original. + + To rotate the rectangle instead of scaling it, use the following code: + + [!code-csharp[System.Drawing.MiscLegacyTopics#13](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#13)] + [!code-vb[System.Drawing.MiscLegacyTopics#13](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#13)] + + To translate the rectangle, use the following code: + + [!code-csharp[System.Drawing.MiscLegacyTopics#14](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#14)] + [!code-vb[System.Drawing.MiscLegacyTopics#14](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#14)] + +## See also + +- +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) +- [Using Transformations in Managed GDI+](using-transformations-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-transformations-in-managed-gdi.md b/dotnet-desktop-guide/framework/winforms/advanced/using-transformations-in-managed-gdi.md new file mode 100644 index 0000000000..42df61f3a9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-transformations-in-managed-gdi.md @@ -0,0 +1,21 @@ +--- +title: "Using Transformations in Managed GDI+" +ms.date: "03/30/2017" +helpviewer_keywords: + - "transformations" + - "examples [Windows Forms], transformations" +ms.assetid: 1f8e18d3-d2f5-460e-a8e3-2da891c301de +--- +# Using Transformations in Managed GDI+ +Affine transformations include rotating, scaling, reflecting, shearing, and translating. In GDI+, the class provides the foundation for performing affine transformations on vector drawings, images, and text. + +## In This Section + [Using the World Transformation](using-the-world-transformation.md) + Describes how to scale and rotate graphics using a world transformation matrix. + + [Why Transformation Order Is Significant](why-transformation-order-is-significant.md) + Demonstrates why the order of transform operations is important. + +## Reference + + Describes this class and contains links to all of its members. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-transformations-to-scale-colors.md b/dotnet-desktop-guide/framework/winforms/advanced/using-transformations-to-scale-colors.md new file mode 100644 index 0000000000..9f073e2a5a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-transformations-to-scale-colors.md @@ -0,0 +1,65 @@ +--- +title: "Using Transformations to Scale Colors" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "transformations [Windows Forms], for scaling colors" + - "colors [Windows Forms], scaling" +ms.assetid: df23c887-7fd6-4b15-ad94-e30b5bd4b849 +--- +# Using Transformations to Scale Colors +A scaling transformation multiplies one or more of the four color components by a number. The color matrix entries that represent scaling are given in the following table. + +|Component to be scaled|Matrix entry| +|----------------------------|------------------| +|Red|[0][0]| +|Green|[1][1]| +|Blue|[2][2]| +|Alpha|[3][3]| + +## Scaling One Color + The following example constructs an object from the file ColorBars2.bmp. Then the code scales the blue component of each pixel in the image by a factor of 2. The original image is drawn alongside the transformed image. + + [!code-csharp[System.Drawing.RecoloringImages#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs#41)] + [!code-vb[System.Drawing.RecoloringImages#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb#41)] + + The following illustration shows the original image on the left and the scaled image on the right: + + ![Screenshot that compares the original and scaled colors.](./media/using-transformations-to-scale-colors/four-bar-scale-one-color.png) + + The following table lists the color vectors for the four bars before and after the blue scaling. Note that the blue component in the fourth color bar went from 0.8 to 0.6. That is because GDI+ retains only the fractional part of the result. For example, (2)(0.8) = 1.6, and the fractional part of 1.6 is 0.6. Retaining only the fractional part ensures that the result is always in the interval [0, 1]. + +|Original|Scaled| +|--------------|------------| +|(0.4, 0.4, 0.4, 1)|(0.4, 0.4, 0.8, 1)| +|(0.4, 0.2, 0.2, 1)|(0.4, 0.2, 0.4, 1)| +|(0.2, 0.4, 0.2, 1)|(0.2, 0.4, 0.4, 1)| +|(0.4, 0.4, 0.8, 1)|(0.4, 0.4, 0.6, 1)| + +## Scaling Multiple Colors + The following example constructs an object from the file ColorBars2.bmp. Then the code scales the red, green, and blue components of each pixel in the image. The red components are scaled down 25 percent, the green components are scaled down 35 percent, and the blue components are scaled down 50 percent. + + [!code-csharp[System.Drawing.RecoloringImages#42](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs#42)] + [!code-vb[System.Drawing.RecoloringImages#42](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb#42)] + + The following illustration shows the original image on the left and the scaled image on the right: + + ![Screenshot that compares the original and scaled colors.](./media/using-transformations-to-scale-colors/four-bar-scale-multiple-colors.png) + + The following table lists the color vectors for the four bars before and after the red, green and blue scaling. + +|Original|Scaled| +|--------------|------------| +|(0.6, 0.6, 0.6, 1)|(0.45, 0.39, 0.3, 1)| +|(0, 1, 1, 1)|(0, 0.65, 0.5, 1)| +|(1, 1, 0, 1)|(0.75, 0.65, 0, 1)| +|(1, 0, 1, 1)|(0.75, 0, 0.5, 1)| + +## See also + +- +- +- [Graphics and Drawing in Windows Forms](graphics-and-drawing-in-windows-forms.md) +- [Recoloring Images](recoloring-images.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/using-wpf-controls.md b/dotnet-desktop-guide/framework/winforms/advanced/using-wpf-controls.md new file mode 100644 index 0000000000..6e61f8f430 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/using-wpf-controls.md @@ -0,0 +1,22 @@ +--- +title: "Using WPF Controls" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms Designer [Windows Forms], interoperability with WPF" + - "interoperability [WPF]" +ms.assetid: 03c85dce-26ad-44cd-bc1d-8e0cb56de096 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Use WPF controls in Windows Forms apps + +You can use Windows Presentation Foundation (WPF) controls in Windows Forms-based applications. Although these are two different view technologies, they interoperate smoothly. + +The Windows Forms Designer in Visual Studio provides a visual design environment for hosting Windows Presentation Foundation controls. A WPF control is hosted by a special Windows Forms control that's named . This control enables the WPF control to participate in the form's layout and to receive keyboard and mouse messages. At design time, you can arrange the control just as you would any Windows Forms control. + +You can also use Windows Forms controls in WPF-based applications. For more information, see [Design XAML in Visual Studio](/visualstudio/xaml-tools/designing-xaml-in-visual-studio). + +## See also + +- [WPF and Windows Forms interoperation](https://docs.microsoft.com/dotnet/framework/wpf/advanced/wpf-and-windows-forms-interoperation) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/vector-graphics-overview.md b/dotnet-desktop-guide/framework/winforms/advanced/vector-graphics-overview.md new file mode 100644 index 0000000000..69791b8efa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/vector-graphics-overview.md @@ -0,0 +1,58 @@ +--- +title: "Vector Graphics Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "inclusive-inclusive endpoints" + - "coordinate systems" + - "graphics [Windows Forms], vector graphics" +ms.assetid: 0195df81-66be-452d-bb53-5a582ebfdc09 +--- +# Vector Graphics Overview +GDI+ draws lines, rectangles, and other shapes on a coordinate system. You can choose from a variety of coordinate systems, but the default coordinate system has the origin in the upper-left corner with the x-axis pointing to the right and the y-axis pointing down. The unit of measure in the default coordinate system is the pixel. + +## The Building Blocks of GDI+ + ![Vector graphic](./media/aboutgdip02-art01.gif "AboutGdip02_Art01") + + A computer monitor creates its display on a rectangular array of dots called picture elements or pixels. The number of pixels that appear on the screen varies from one monitor to the next, and the number of pixels that appear on an individual monitor can usually be configured to some extent by the user. + + ![Vector graphic](./media/aboutgdip02-art02.gif "AboutGdip02_Art02") + + When you use GDI+ to draw a line, rectangle, or curve, you provide certain key information about the item to be drawn. For example, you can specify a line by providing two points, and you can specify a rectangle by providing a point, a height, and a width. GDI+ works in conjunction with the display driver software to determine which pixels must be turned on to show the line, rectangle, or curve. The following illustration shows the pixels that are turned on to display a line from the point (4, 2) to the point (12, 8). + + ![Vector graphic](./media/aboutgdip02-art03.gif "AboutGdip02_Art03") + + Over time, certain basic building blocks have proven to be the most useful for creating two-dimensional pictures. These building blocks, which are all supported by GDI+, are given in the following list: + +- Lines + +- Rectangles + +- Ellipses + +- Arcs + +- Polygons + +- Cardinal splines + +- Bezier splines + +## Methods For Drawing with a Graphics Object + The class in GDI+ provides the following methods for drawing the items in the previous list: , , , , , (for cardinal splines), and . Each of these methods is overloaded; that is, each method supports several different parameter lists. For example, one variation of the method receives a object and four integers, while another variation of the method receives a object and two objects. + + The methods for drawing lines, rectangles, and Bézier splines have plural companion methods that draw several items in a single call: , , and . Also, the method has a companion method, , that closes a curve by connecting the ending point of the curve to the starting point. + + All of the drawing methods of the class work in conjunction with a object. To draw anything, you must create at least two objects: a object and a object. The object stores attributes, such as line width and color, of the item to be drawn. The object is passed as one of the arguments to the drawing method. For example, one variation of the method receives a object and four integers as shown in the following example, which draws a rectangle with a width of 100, a height of 50 and an upper-left corner of (20, 10): + + [!code-csharp[LinesCurvesAndShapes#11](~/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs#11)] + [!code-vb[LinesCurvesAndShapes#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb#11)] + +## See also + +- +- +- [Lines, Curves, and Shapes](lines-curves-and-shapes.md) +- [How to: Create Graphics Objects for Drawing](how-to-create-graphics-objects-for-drawing.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-arranging-wpf-content-on-windows-forms-at-design-time.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-arranging-wpf-content-on-windows-forms-at-design-time.md new file mode 100644 index 0000000000..2b57c4c5e5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-arranging-wpf-content-on-windows-forms-at-design-time.md @@ -0,0 +1,135 @@ +--- +title: Arrange WPF content on Windows Forms at design time +titleSuffix: "" +ms.date: "03/30/2017" +helpviewer_keywords: + - "WPF user control [Windows Forms], hosting in a layout panel" + - "WPF content [Windows Forms], arranging at design time" + - "Windows Forms, arranging WPF content at design time" + - "WPF content [Windows Forms], hosting in Windows Forms" + - "Windows Forms, anchoring and docking WPF content" + - "interoperability [WPF]" +ms.assetid: 5efb1c53-1484-43d6-aa8a-f4861b99bb8a +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Arrange WPF content on Windows Forms at design time + +This article shows you how to use the Windows Forms layout features, such as anchoring and snaplines, to arrange Windows Presentation Foundation (WPF) controls. + +## Prerequisites + +You need Visual Studio to complete this walkthrough. + +## Create the project + +Open Visual Studio and create a new Windows Forms Application project in Visual Basic or Visual C# named `ArrangeElementHost`. + +> [!NOTE] +> When hosting WPF content, only C# and Visual Basic projects are supported. + +## Create the WPF control + +After you add a WPF control to the project, you can arrange it on the form. + +1. Add a new WPF to the project. Use the default name for the control type, `UserControl1.xaml`. For more information, see [Walkthrough: Creating New WPF Content on Windows Forms at Design Time](walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md). + +2. In Design view, make sure that `UserControl1` is selected. + +3. In the **Properties** window, set the value of the and properties to **200**. + +4. Set the value of the property to **Blue**. + +5. Build the project. + +## Host WPF controls in a layout panel + +You can use WPF controls in layout panels in the same way you use other Windows Forms controls. + +1. Open `Form1` in the Windows Forms Designer. + +2. In the **Toolbox**, drag a control onto the form. + +3. On the control's smart tag panel, select **Remove Last Row**. + +4. Resize the control to a larger width and height. + +5. In the **Toolbox**, double-click `UserControl1` to create an instance of `UserControl1` in the first cell of the control. + + The instance of `UserControl1` is hosted in a new control named `elementHost1`. + +6. In the **Toolbox**, double-click `UserControl1` to create another instance in the second cell of the control. + +7. In the **Document Outline** window, select `tableLayoutPanel1`. + +8. In the **Properties** window, set the value of the property to **10, 10, 10, 10**. + + Both controls are resized to fit into the new layout. + +## Use snaplines to align WPF controls + +Snaplines enable easy alignment of controls on a form. You can use snaplines to align your WPF controls as well. For more information, see [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](../controls/walkthrough-arranging-controls-on-windows-forms-using-snaplines.md). + +1. From the **Toolbox**, drag an instance of `UserControl1` onto the form, and place it in the space beneath the control. + + The instance of `UserControl1` is hosted in a new control named `elementHost3`. + +2. Using snaplines, align the left edge of `elementHost3` with the left edge of control. + +3. Using snaplines, size `elementHost3` to the same width as the control. + +4. Move `elementHost3` toward the control until a center snapline appears between the controls. + +5. In the **Properties** window, set the value of the Margin property to **20, 20, 20, 20**. + +6. Move the `elementHost3` away from the control until the center snapline appears again. The center snapline now indicates a margin of 20. + +7. Move `elementHost3` to the right until its left edge aligns with the left edge of `elementHost1`. + +8. Change the width of `elementHost3` until its right edge aligns with the right edge of `elementHost2`. + +## Anchor and dock WPF controls + +A WPF control hosted on a form has the same anchoring and docking behavior as other Windows Forms controls. + +1. Select `elementHost1`. + +2. In the **Properties** window, set the property to **Top, Bottom, Left, Right**. + +3. Resize the control to a larger size. + + The `elementHost1` control resizes to fill the cell. + +4. Select `elementHost2`. + +5. In the **Properties** window, set the value of the property to . + + The `elementHost2` control resizes to fill the cell. + +6. Select the control. + +7. Set the value of its property to . + +8. Select `elementHost3`. + +9. Set the value of its property to . + + The `elementHost3` control resizes to fill the remaining space on the form. + +10. Resize the form. + + All three controls resize appropriately. + + For more information, see [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](../controls/how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md). + +## See also + +- +- +- [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](../controls/how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) +- [How to: Align a Control to the Edges of Forms at Design Time](../controls/how-to-align-a-control-to-the-edges-of-forms-at-design-time.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](../controls/walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) +- [Migration and Interoperability](https://docs.microsoft.com/dotnet/framework/wpf/advanced/migration-and-interoperability) +- [Using WPF Controls](using-wpf-controls.md) +- [Design XAML in Visual Studio](/visualstudio/xaml-tools/designing-xaml-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-assigning-wpf-content-on-windows-forms-at-design-time.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-assigning-wpf-content-on-windows-forms-at-design-time.md new file mode 100644 index 0000000000..599c379fda --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-assigning-wpf-content-on-windows-forms-at-design-time.md @@ -0,0 +1,88 @@ +--- +title: Select WPF controls for Windows Forms +titleSuffix: "" +ms.date: "03/30/2017" +helpviewer_keywords: + - "WPF content [Windows Forms], assigning at design time" + - "ElementHost control [Windows Forms], assigning WPF content at design time" + - "interoperability [WPF]" + - "Windows Forms, content assignments" + - "WPF user control [Windows Forms], hosting in Windows Forms" +ms.assetid: b3e9ef93-7e0f-4a2f-8f1e-3437609a1eb7 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Assign WPF content on Windows Forms at design time + +This article show you how to select the Windows Presentation Foundation (WPF) control types you want to display on your form. You can select any WPF control types that are included in your project. + +## Prerequisites + +You need Visual Studio to complete this walkthrough. + +## Create the project + +Open Visual Studio and create a new Windows Forms Application project in Visual Basic or Visual C# named `SelectingWpfContent`. + +> [!NOTE] +> When hosting WPF content, only C# and Visual Basic projects are supported. + +## Create the WPF control types + +After you add WPF control types to the project, you can host them in different controls. + +1. Add a new WPF project to the solution. Use the default name for the control type, `UserControl1.xaml`. For more information, see [Walkthrough: Creating New WPF Content on Windows Forms at Design Time](walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md). + +2. In Design view, make sure that `UserControl1` is selected. + +3. In the **Properties** window, set the value of the and properties to **200**. + +4. Add a control to the and set the value of the property to **Hosted Content**. + +5. Add a second WPF to the project. Use the default name for the control type, `UserControl2.xaml`. + +6. In the **Properties** window, set the value of the and properties to **200**. + +7. Add a control to the and set the value of the property to **Hosted Content 2**. + + > [!NOTE] + > In general, you should host more sophisticated WPF content. The control is used here for illustrative purposes only. + +8. Build the project. + +## Select WPF controls + +You can assign different WPF content to an control, which is already hosting content. + +1. Open `Form1` in the Windows Forms Designer. + +2. In the **Toolbox**, double-click `UserControl1` to create an instance of `UserControl1` on the form. + + An instance of `UserControl1` is hosted in a new control named `elementHost1`. + +3. In the smart tag panel for `elementHost1`, open the **Select Hosted Content** drop-down list. + +4. Select **UserControl2** from the drop-down list box. + + The `elementHost1` control now hosts an instance of the `UserControl2` type. + +5. In the **Properties** window, confirm that the property is set to **UserControl2**. + +6. From the **Toolbox**, in the **WPF Interoperability** group, drag an control onto the form. + + The default name for the new control is `elementHost2`. + +7. In the smart tag panel for `elementHost2`, open the **Select Hosted Content** drop-down list. + +8. Select **UserControl1** from the drop-down list. + +9. The `elementHost2` control now hosts an instance of the `UserControl1` type. + +## See also + +- +- +- [Migration and Interoperability](https://docs.microsoft.com/dotnet/framework/wpf/advanced/migration-and-interoperability) +- [Using WPF Controls](using-wpf-controls.md) +- [Design XAML in Visual Studio](/visualstudio/xaml-tools/designing-xaml-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-creating-an-accessible-windows-based-application.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-creating-an-accessible-windows-based-application.md new file mode 100644 index 0000000000..d373721908 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-creating-an-accessible-windows-based-application.md @@ -0,0 +1,316 @@ +--- +title: "Walkthrough: Creating an Accessible Windows-based Application" +ms.date: "03/30/2017" +helpviewer_keywords: + - "accessibility [Windows Forms], Windows applications" + - "Windows applications [Windows Forms], accessibility" + - "applications [Windows Forms], accessibility" +dev_langs: + - csharp + - vb +ms.assetid: 654c7f2f-1586-480b-9f12-9d9b8f5cc32b +--- +# Walkthrough: Creating an Accessible Windows-based Application + +Creating an accessible application has important business implications. Many governments have accessibility regulations for software purchase. The Certified for Windows logo includes accessibility requirements. An estimated 30 million residents of the U.S. alone, many of them potential customers, are affected by the accessibility of software. + +This walkthrough will address the five accessibility requirements for the Certified for Windows logo. According to these requirements, an accessible application will: + +- Support Control Panel size, color, font, and input settings. The menu bar, title bar, borders, and status bar will all resize themselves when the user changes the control panel settings. No additional changes to the controls or code are required in this application. + +- Support High Contrast mode. + +- Provide documented keyboard access to all features. + +- Expose location of the keyboard focus visually and programmatically. + +- Avoid conveying important information by sound alone. + +For more information, see [Resources for Designing Accessible Applications](/visualstudio/ide/reference/resources-for-designing-accessible-applications). + +For information on supporting varying keyboard layouts, see [Best Practices for Developing World-Ready Applications](https://docs.microsoft.com/dotnet/standard/globalization-localization/best-practices-for-developing-world-ready-apps). + +## Creating the Project + +This walkthrough creates the user interface for an application that takes pizza orders. It consists of a for the customer's name, a group to select the pizza size, a for selecting the toppings, two Button controls labeled Order and Cancel, and a Menu with an Exit command. + +The user enters the customer's name, the size of the pizza, and the toppings desired. When the user clicks the Order button, a summary of the order and its cost are displayed in a message box and the controls are cleared and ready for the next order. When the user clicks the Cancel button, the controls are cleared and ready for the next order. When the user clicks the Exit menu item, the program closes. + +The emphasis of this walkthrough is not the code for a retail order system, but the accessibility of the user interface. The walkthrough demonstrates the accessibility features of several frequently used controls, including buttons, radio buttons, text boxes, and labels. + +#### To begin making the application + +- Create a new Windows Application in Visual Basic or Visual C#. Name the project **PizzaOrder**. For details, see [Creating New Solutions and Projects](/visualstudio/ide/creating-solutions-and-projects). + +## Adding the Controls to the Form + +When adding the controls to a form, keep in mind the following guidelines to make an accessible application: + +- Set the and properties. In this example, the Default setting for the is sufficient. For more information on the accessibility properties, see [Providing Accessibility Information for Controls on a Windows Form](../controls/providing-accessibility-information-for-controls-on-a-windows-form.md). + +- Set the font size to 10 points or larger. + + > [!NOTE] + > If you set the font size of the form to 10 when you start, then all controls subsequently added to the form will have a font size of 10. + +- Make sure any Label control that describes a TextBox control immediately precedes the TextBox control in the tab order. + +- Add an access key, using the "&" character, to the property of any control the user may want to navigate to. + +- Add an access key, using the "&" character, to the property of the label that precedes a control that the user may want to navigate to. Set the labels' property to `true`, so that the focus is set to the next control in the tab order when the user presses the access key. + +- Add access keys to all menu items. + +#### To make your Windows Application accessible + +- Add the controls to the form and set the properties as described below. See the picture at the end of the table for a model of how to arrange the controls on the form. + + |Object|Property|Value| + |------------|--------------|-----------| + |Form1|AccessibleDescription|Order form| + ||AccessibleName|Order form| + ||Font Size|10| + ||Text|Pizza Order Form| + |PictureBox|Name|logo| + ||AccessibleDescription|A slice of pizza| + ||AccessibleName|Company logo| + ||Image|Any icon or bitmap| + |Label|Name|companyLabel| + ||Text|Good Pizza| + ||TabIndex|1| + ||AccessibleDescription|Company name| + ||AccessibleName|Company name| + ||Backcolor|Blue| + ||Forecolor|Yellow| + ||Font size|18| + |Label|Name|customerLabel| + ||Text|&Name| + ||TabIndex|2| + ||AccessibleDescription|Customer name label| + ||AccessibleName|Customer name label| + ||UseMnemonic|True| + |TextBox|Name|customerName| + ||Text|(none)| + ||TabIndex|3| + ||AccessibleDescription|Customer name| + ||AccessibleName|Customer name| + |GroupBox|Name|sizeOptions| + ||AccessibleDescription|Pizza size options| + ||AccessibleName|Pizza size options| + ||Text|Pizza size| + ||TabIndex|4| + |RadioButton|Name|smallPizza| + ||Text|&Small $6.00| + ||Checked|True| + ||TabIndex|0| + ||AccessibleDescription|Small pizza| + ||AccessibleName|Small pizza| + |RadioButton|Name|largePizza| + ||Text|&Large $10.00| + ||TabIndex|1| + ||AccessibleDescription|Large pizza| + ||AccessibleName|Large pizza| + |Label|Name|toppingsLabel| + ||Text|&Toppings ($0.75 each)| + ||TabIndex|5| + ||AccessibleDescription|Toppings label| + ||AccessibleName|Toppings label| + ||UseMnemonic|True| + |CheckedListBox|Name|toppings| + ||TabIndex|6| + ||AccessibleDescription|Available toppings| + ||AccessibleName|Available toppings| + ||Items|Pepperoni, Sausage, Mushrooms| + |Button|Name|order| + ||Text|&Order| + ||TabIndex|7| + ||AccessibleDescription|Total the order| + ||AccessibleName|Total order| + |Button|Name|cancel| + ||Text|&Cancel| + ||TabIndex|8| + ||AccessibleDescription|Cancel the order| + ||AccessibleName|Cancel order| + |MainMenu|Name|theMainMenu| + |MenuItem|Name|fileCommands| + ||Text|&File| + |MenuItem|Name|exitApp| + ||Text|E&xit| + + Your form will look something like the following image: + + ![The pizza order form with a name textbox, and size and toppings selection.](./media/walkthrough-creating-an-accessible-windows-based-application/visual-basic-pizza-order-form.gif) + +## Supporting High Contrast Mode + +High Contrast mode is a Windows system setting that improves readability by using contrasting colors and font sizes that are beneficial for visually impaired users. The property is provided to determine whether the High Contrast mode is set. + +If SystemInformation.HighContrast is `true`, the application should: + +- Display all user interface elements using the system color scheme + +- Convey by visual cues or sound any information that is conveyed through color. For example, if particular list items are highlighted by using a red font, you could also add bold to the font, so that the user has a non-color cue that the items are highlighted. + +- Omit any images or patterns behind text + +The application should check the setting of when the application starts and respond to the system event . The event is raised whenever the value of changes. + +In our application, the only element that is not using the system settings for color is `lblCompanyName`. The class is used to change the color settings of the label to the user-selected system colors. + +#### To enable High Contrast mode in an effective way + +1. Create a method to set the colors of the label to the system colors. + + ```vb + Private Sub SetColorScheme() + If SystemInformation.HighContrast Then + companyLabel.BackColor = SystemColors.Window + companyLabel.ForeColor = SystemColors.WindowText + Else + companyLabel.BackColor = Color.Blue + companyLabel.ForeColor = Color.Yellow + End If + End Sub + ``` + + ```csharp + private void SetColorScheme() + { + if (SystemInformation.HighContrast) + { + companyLabel.BackColor = SystemColors.Window; + companyLabel.ForeColor = SystemColors.WindowText; + } + else + { + companyLabel.BackColor = Color.Blue; + companyLabel.ForeColor = Color.Yellow; + } + } + ``` + +2. Call the `SetColorScheme` procedure in the form constructor (`Public Sub New()` in Visual Basic and `public Form1()` in Visual C#). To access the constructor in Visual Basic, you will need to expand the region labeled **Windows Form Designer generated code**. + + ```vb + Public Sub New() + MyBase.New() + InitializeComponent() + SetColorScheme() + End Sub + ``` + + ```csharp + public Form1() + { + InitializeComponent(); + SetColorScheme(); + } + ``` + +3. Create an event procedure, with the appropriate signature, to respond to the event. + + ```vb + Protected Sub UserPreferenceChanged(sender As Object, _ + e As Microsoft.Win32.UserPreferenceChangedEventArgs) + SetColorScheme() + End Sub + ``` + + ```csharp + public void UserPreferenceChanged(object sender, + Microsoft.Win32.UserPreferenceChangedEventArgs e) + { + SetColorScheme(); + } + ``` + +4. Add code to the form constructor, after the call to `InitializeComponents`, to hook up the event procedure to the system event. This method calls the `SetColorScheme` procedure. + + ```vb + Public Sub New() + MyBase.New() + InitializeComponent() + SetColorScheme() + AddHandler Microsoft.Win32.SystemEvents.UserPreferenceChanged, _ + AddressOf Me.UserPreferenceChanged + End Sub + ``` + + ```csharp + public Form1() + { + InitializeComponent(); + SetColorScheme(); + Microsoft.Win32.SystemEvents.UserPreferenceChanged + += new Microsoft.Win32.UserPreferenceChangedEventHandler( + this.UserPreferenceChanged); + } + ``` + +5. Add code to the form method, before the call to the method of the base class, to release the event when the application closes. To access the method in Visual Basic, you will need to expand the region labeled Windows Form Designer generated code. + + > [!NOTE] + > The system event code runs a thread separate from the main application. If you do not release the event, the code that you hook up to the event will run even after the program is closed. + + ```vb + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + RemoveHandler Microsoft.Win32.SystemEvents.UserPreferenceChanged, _ + AddressOf Me.UserPreferenceChanged + MyBase.Dispose(disposing) + End Sub + ``` + + ```csharp + protected override void Dispose(bool disposing) + { + if(disposing && components != null) + { + components.Dispose(); + } + Microsoft.Win32.SystemEvents.UserPreferenceChanged + -= new Microsoft.Win32.UserPreferenceChangedEventHandler( + this.UserPreferenceChanged); + base.Dispose( disposing ); + } + ``` + +6. Press F5 to run the application. + +## Conveying Important Information by Means Other Than Sound + +In this application, no information is conveyed by sound alone. If you use sound in your application, then you should supply the information by some other means as well. + +#### To supply information by some other means than sound + +1. Make the title bar flash by using the Windows API function FlashWindow. For an example of how to call Windows API functions, see [Walkthrough: Calling Windows APIs](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/com-interop/walkthrough-calling-windows-apis). + + > [!NOTE] + > The user may have the Windows SoundSentry service enabled, which will also cause the window to flash when the system sounds are played through the computer's built-in speaker. + +2. Display the important information in a non-modal window so that the user may respond to it. + +3. Display a message box that acquires the keyboard focus. Avoid this method when the user may be typing. + +4. Display a status indicator in the status notification area of the taskbar. For details, see [Adding Application Icons to the TaskBar with the Windows Forms NotifyIcon Component](../controls/app-icons-to-the-taskbar-with-wf-notifyicon.md). + +## Testing the Application + +Before deploying the application, you should test the accessibility features that you have implemented. + +#### To test accessibility features + +1. To test keyboard access, unplug the mouse and navigate the user interface for each feature using only the keyboard. Ensure that all tasks may be performed using the keyboard only. + +2. To test support of High Contrast, choose the Accessibility Options icon in Control Panel. Click the Display tab and select the Use High Contrast check box. Navigate through all user interface elements to ensure that the color and font changes are reflected. Also, ensure that images or patterns drawn behind text are omitted. + + > [!NOTE] + > Windows NT 4 does not have an Accessibility Options icon in Control Panel. Thus, this procedure for changing the SystemInformation.HighContrast setting does not work in Windows NT 4. + +3. Other tools are readily available for testing the accessibility of an application. + +4. To test exposing the keyboard focus, run Magnifier. (To open it, click the **Start** menu, point to **Programs**, point to **Accessories**, point to **Accessibility**, and then click **Magnifier**). Navigate the user interface using both keyboard tabbing and the mouse. Ensure that all navigation is tracked properly in **Magnifier**. + +5. To test exposing screen elements, run Inspect, and use both the mouse and the TAB key to reach each element. Ensure that the information presented in the Name, State, Role, Location, and Value fields of the Inspect window is meaningful to the user for each object in the UI. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md new file mode 100644 index 0000000000..38f6d2a9bb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md @@ -0,0 +1,105 @@ +--- +title: Create new WPF Content on Windows Forms +titleSuffix: "" +ms.date: 08/18/2018 +helpviewer_keywords: + - "interoperability [Windows Forms], WPF and Windows Forms" + - "WPF content [Windows Forms], hosting in Windows Forms" + - "hosting WPF content in Windows Forms" + - "ElementHost control" + - "WPF user control [Windows Forms], hosting in Windows Forms" +ms.assetid: 2e92d8e8-f0e4-4df7-9f07-2acf35cd798c +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Create new WPF content on Windows Forms at design time + +This article shows you how to create a Windows Presentation Foundation (WPF) control for use in your Windows Forms-based applications. + +## Prerequisites + +You need Visual Studio to complete this walkthrough. + +## Create the project + +Open Visual Studio and create a new **Windows Forms App (.NET Framework)** project in Visual Basic or Visual C# named `HostingWpf`. + +> [!NOTE] +> When hosting WPF content, only C# and Visual Basic projects are supported. + +## Create a new WPF control + +Creating a new WPF control and adding it to your project is as easy as adding any other item to your project. The Windows Forms Designer works with a particular kind of control named *composite control*, or *user control*. For more information about WPF user controls, see . + +> [!NOTE] +> The type for WPF is distinct from the user control type provided by Windows Forms, which is also named . + +To create a new WPF control: + +1. In **Solution Explorer**, add a new **WPF User Control Library (.NET Framework)** project to the solution. Use the default name for the control library, `WpfControlLibrary1`. The default control name is `UserControl1.xaml`. + + Adding the new control has the following effects: + + - File UserControl1.xaml is added. + + - File UserControl1.xaml.cs (or UserControl1.xaml.vb) is added. This file contains the code-behind for event handlers and other implementation. + + - References to WPF assemblies are added. + + - File UserControl1.xaml opens in the WPF Designer for Visual Studio. + +2. In Design view, make sure that `UserControl1` is selected. + +3. In the **Properties** window, set the value of the and properties to **200**. + +4. From the **Toolbox**, drag a control onto the design surface. + +5. In the **Properties** window, set the value of the property to **Hosted Content**. + + > [!NOTE] + > In general, you should host more sophisticated WPF content. The control is used here for illustrative purposes only. + +6. Build the project. + +## Add a WPF control to a Windows Form + +Your new WPF control is ready for use on the form. Windows Forms uses the control to host WPF content. + +To add a WPF control to a Windows Form: + +1. Open `Form1` in the Windows Forms Designer. + +2. In the **Toolbox**, find the tab labeled **WPFUserControlLibrary WPF User Controls**. + +3. Drag an instance of `UserControl1` onto the form. + + - An control is created automatically on the form to host the WPF control. + + - The control is named `elementHost1` and in the **Properties** window, you can see its property is set to **UserControl1**. + + - References to WPF assemblies are added to the project. + + - The `elementHost1` control has a smart tag panel that shows the available hosting options. + +4. In the **ElementHost Tasks** smart tag panel, select **Dock in parent container**. + +5. Press **F5** to build and run the application. + +## Next steps + +Windows Forms and WPF are different technologies, but they are designed to interoperate closely. To provide richer appearance and behavior in your applications, try the following: + +- Host a Windows Forms control in a WPF page. For more information, see [Walkthrough: Hosting a Windows Forms Control in WPF](https://docs.microsoft.com/dotnet/framework/wpf/advanced/walkthrough-hosting-a-windows-forms-control-in-wpf). + +- Apply Windows Forms visual styles to your WPF content. For more information, see [How to: Enable Visual Styles in a Hybrid Application](https://docs.microsoft.com/dotnet/framework/wpf/advanced/how-to-enable-visual-styles-in-a-hybrid-application). + +- Change the style of your WPF content. For more information, see [Walkthrough: Styling WPF Content](walkthrough-styling-wpf-content.md). + +## See also + +- +- +- [Migration and Interoperability](https://docs.microsoft.com/dotnet/framework/wpf/advanced/migration-and-interoperability) +- [Using WPF Controls](using-wpf-controls.md) +- [Design XAML in Visual Studio](/visualstudio/xaml-tools/designing-xaml-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-demonstrating-visual-inheritance.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-demonstrating-visual-inheritance.md new file mode 100644 index 0000000000..b4ad6a0930 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-demonstrating-visual-inheritance.md @@ -0,0 +1,160 @@ +--- +title: "Walkthrough: Demonstrating Visual Inheritance" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "form inheritance [Windows Forms], walkthroughs" + - "visual inheritance" + - "inheritance [Windows Forms], walkthroughs" + - "walkthroughs [Windows Forms], visual inheritance" + - "Windows Forms, inheritance" +ms.assetid: 01966086-3142-450e-8210-3fd4cb33f591 +--- +# Walkthrough: Demonstrating Visual Inheritance + +Visual inheritance enables you to see the controls on the base form and to add new controls. In this walkthrough you will create a base form and compile it into a class library. You will import this class library into another project and create a new form that inherits from the base form. During this walkthrough, you will learn how to: + +- Create a class library project containing a base form. + +- Add a button with properties that derived classes of the base form can modify. + +- Add a button that cannot be modified by inheritors of the base form. + +- Create a project containing a form that inherits from `BaseForm`. + +Ultimately, this walkthrough will demonstrate the difference between private and protected controls on an inherited form. + +> [!CAUTION] +> Not all controls support visual inheritance from a base form. The following controls do not support the scenario described in this walkthrough: +> +> - +> +> - +> +> - +> +> - +> +> - +> +> - +> +> These controls in the inherited form are always read-only regardless of the modifiers you use (`private`, `protected`, or `public`). + +## Create a class library project containing a base form + +1. In Visual Studio, from the **File** menu, choose **New** > **Project** to open the **New Project** dialog box. + +2. Create a Windows Forms application named `BaseFormLibrary`. + +3. To create a class library instead of a standard Windows Forms application, in **Solution Explorer**, right-click the **BaseFormLibrary** project node and then select **Properties**. + +4. In the properties for the project, change the **Output type** from **Windows Application** to **Class Library**. + +5. From the **File** menu, choose **Save All** to save the project and files to the default location. + +The next two procedures add buttons to the base form. To demonstrate visual inheritance, you will give the buttons different access levels by setting their `Modifiers` properties. + +## Add a button that inheritors of the base form can modify + +1. Open **Form1** in the designer. + +2. On the **All Windows Forms** tab of the **Toolbox**, double-click **Button** to add a button to the form. Use the mouse to position and resize the button. + +3. In the Properties window, set the following properties of the button: + + - Set the **Text** property to **Say Hello**. + + - Set the **(Name)** property to **btnProtected**. + + - Set the **Modifiers** property to **Protected**. This makes it possible for forms that inherit from **Form1** to modify the properties of **btnProtected**. + +4. Double-click the **Say Hello** button to add an event handler for the **Click** event. + +5. Add the following line of code to the event handler: + + ```vb + MessageBox.Show("Hello, World!") + ``` + + ```csharp + MessageBox.Show("Hello, World!"); + ``` + +## Add a button that cannot be modified by inheritors of the base form + +1. Switch to design view by clicking the **Form1.vb [Design], Form1.cs [Design], or Form1.jsl [Design]** tab above the code editor, or by pressing F7. + +2. Add a second button and set its properties as follows: + + - Set the **Text** property to **Say Goodbye**. + + - Set the **(Name)** property to **btnPrivate**. + + - Set the **Modifiers** property to **Private**. This makes it impossible for forms that inherit from **Form1** to modify the properties of **btnPrivate**. + +3. Double-click the **Say Goodbye** button to add an event handler for the **Click** event. Place the following line of code in the event procedure: + + ```vb + MessageBox.Show("Goodbye!") + ``` + + ```csharp + MessageBox.Show("Goodbye!"); + ``` + +4. From the **Build** menu, choose **Build BaseForm Library** to build the class library. + + Once the library is built, you can create a new project that inherits from the form you just created. + +## Create a project containing a form that inherits from the base form + +1. From the **File** menu, choose **Add** and then **New Project** to open the **Add New Project** dialog box. + +2. Create a Windows Forms application named `InheritanceTest`. + +## Add an inherited form + +1. In **Solution Explorer**, right-click the **InheritanceTest** project, select **Add**, and then select **New Item**. + +2. In the **Add New Item** dialog box, select the **Windows Forms** category (if you have a list of categories) and then select the **Inherited Form** template. + +3. Leave the default name of `Form2` and then click **Add**. + +4. In the **Inheritance Picker** dialog box, select **Form1** from the **BaseFormLibrary** project as the form to inherit from and click **OK**. + + This creates a form in the **InheritanceTest** project that derives from the form in **BaseFormLibrary**. + +5. Open the inherited form (**Form2**) in the designer by double-clicking it, if it is not already open. + + In the designer, the inherited buttons have a symbol (![Screenshot of the Visual Basic inheritance symbol.](./media/walkthrough-demonstrating-visual-inheritance/visual-basic-inheritance-glyph.gif)) in their upper corner, indicating they are inherited. + +6. Select the **Say Hello** button and observe the resize handles. Because this button is protected, the inheritors can move it, resize it, change its caption, and make other modifications. + +7. Select the private **Say Goodbye** button, and notice that it does not have resize handles. Additionally, in the **Properties** window, the properties of this button are grayed to indicate they cannot be modified. + +8. If you are using Visual C#: + + 1. In **Solution Explorer**, right-click **Form1** in the **InheritanceTest** project and then choose **Delete**. In the message box that appears, click **OK** to confirm the deletion. + + 2. Open the Program.cs file and change the line `Application.Run(new Form1());` to `Application.Run(new Form2());`. + +9. In **Solution Explorer**, right-click the **InheritanceTest** project and select **Set As Startup Project**. + +10. In **Solution Explorer**, right-click the **InheritanceTest** project and select **Properties**. + +11. In the **InheritanceTest** property pages, set the **Startup object** to be the inherited form (**Form2**). + +12. Press **F5** to run the application, and observe the behavior of the inherited form. + +## Next steps + +Inheritance for user controls works in much the same way. Open a new class library project and add a user control. Place constituent controls on it and compile the project. Open another new class library project and add a reference to the compiled class library. Also, try adding an inherited control (through the **Add New Items** dialog box) to the project and using the **Inheritance Picker**. Add a user control, and change the `Inherits` (`:` in Visual C#) statement. For more information, see [How to: Inherit Windows Forms](how-to-inherit-windows-forms.md). + +## See also + +- [How to: Inherit Windows Forms](how-to-inherit-windows-forms.md) +- [Windows Forms Visual Inheritance](windows-forms-visual-inheritance.md) +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md new file mode 100644 index 0000000000..5b29354556 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md @@ -0,0 +1,108 @@ +--- +title: "Walkthrough: Perform a drag-and-drop operation" +description: Learn how to perform a drag-and-drop operation in Windows Forms by handling a series of events, most notably the DragEnter, DragLeave, and DragDrop events. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, drag and drop operations" + - "drag and drop [Windows Forms], Windows Forms" +ms.assetid: eb66f6bf-4a7d-4c2d-b276-40fefb2d3b6c +--- +# Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms +To perform drag-and-drop operations within Windows-based applications you must handle a series of events, most notably the , , and events. By working with the information available in the event arguments of these events, you can easily facilitate drag-and-drop operations. + +## Dragging Data + All drag-and-drop operations begin with dragging. The functionality to enable data to be collected when dragging begins is implemented in the method. + + In the following example, the event is used to start the drag operation because it is the most intuitive (most drag-and-drop actions begin with the mouse button being depressed). However, remember that any event could be used to initiate a drag-and-drop procedure. + +> [!NOTE] +> Certain controls have custom drag-specific events. The and controls, for example, have an event. + +#### To start a drag operation + +1. In the event for the control where the drag will begin, use the `DoDragDrop` method to set the data to be dragged and the allowed effect dragging will have. For more information, see and . + + The following example shows how to initiate a drag operation. The control where the drag begins is a control, the data being dragged is the string representing the property of the control, and the allowed effects are either copying or moving. + + ```vb + Private Sub Button1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown + Button1.DoDragDrop(Button1.Text, DragDropEffects.Copy Or DragDropEffects.Move) + End Sub + ``` + + ```csharp + private void button1_MouseDown(object sender, + System.Windows.Forms.MouseEventArgs e) + { + button1.DoDragDrop(button1.Text, DragDropEffects.Copy | + DragDropEffects.Move); + } + ``` + + > [!NOTE] + > Any data can be used as a parameter in the `DoDragDrop` method; in the example above, the property of the control was used (rather than hard-coding a value or retrieving data from a dataset) because the property was related to the location being dragged from (the control). Keep this in mind as you incorporate drag-and-drop operations into your Windows-based applications. + + While a drag operation is in effect, you can handle the event, which "asks permission" of the system to continue the drag operation. When handling this method, it is also the appropriate point for you to call methods that will have an effect on the drag operation, such as expanding a in a control when the cursor hovers over it. + +## Dropping Data + Once you have begun dragging data from a location on a Windows Form or control, you will naturally want to drop it somewhere. The cursor will change when it crosses an area of a form or control that is correctly configured for dropping data. Any area within a Windows Form or control can be made to accept dropped data by setting the property and handling the and events. + +#### To perform a drop + +1. Set the property to true. + +2. In the `DragEnter` event for the control where the drop will occur, ensure that the data being dragged is of an acceptable type (in this case, ). The code then sets the effect that will happen when the drop occurs to a value in the enumeration. For more information, see . + + ```vb + Private Sub TextBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox1.DragEnter + If (e.Data.GetDataPresent(DataFormats.Text)) Then + e.Effect = DragDropEffects.Copy + Else + e.Effect = DragDropEffects.None + End If + End Sub + ``` + + ```csharp + private void textBox1_DragEnter(object sender, + System.Windows.Forms.DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.Text)) + e.Effect = DragDropEffects.Copy; + else + e.Effect = DragDropEffects.None; + } + ``` + + > [!NOTE] + > You can define your own by specifying your own object as the parameter of the method. Be sure, when doing this, that the object specified is serializable. For more information, see . + +3. In the event for the control where the drop will occur, use the method to retrieve the data being dragged. For more information, see . + + In the example below, a control is the control being dragged to (where the drop will occur). The code sets the property of the control equal to the data being dragged. + + ```vb + Private Sub TextBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox1.DragDrop + TextBox1.Text = e.Data.GetData(DataFormats.Text).ToString + End Sub + ``` + + ```csharp + private void textBox1_DragDrop(object sender, + System.Windows.Forms.DragEventArgs e) + { + textBox1.Text = e.Data.GetData(DataFormats.Text).ToString(); + } + ``` + + > [!NOTE] + > Additionally, you can work with the property, so that, depending on keys depressed during the drag-and-drop operation, certain effects occur (for example, it is standard to copy the dragged data when the CTRL key is pressed). + +## See also + +- [How to: Add Data to the Clipboard](how-to-add-data-to-the-clipboard.md) +- [How to: Retrieve Data from the Clipboard](how-to-retrieve-data-from-the-clipboard.md) +- [Drag-and-Drop Operations and Clipboard Support](drag-and-drop-operations-and-clipboard-support.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-styling-wpf-content.md b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-styling-wpf-content.md new file mode 100644 index 0000000000..f25c56f697 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/walkthrough-styling-wpf-content.md @@ -0,0 +1,139 @@ +--- +title: "Walkthrough: Style WPF content" +ms.date: "03/30/2017" +helpviewer_keywords: + - "WPF Designer [Windows Forms], styling WPF content" + - "interoperability [WDF]" + - "styles [Windows Forms], WPF content" +ms.assetid: e574aac7-7ea4-4cdb-8034-bab541f000df +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Style WPF content + +This article show you how to apply styling to a Windows Presentation Foundation (WPF) control hosted on a Windows Form. + +## Prerequisites + +You need Visual Studio to complete this walkthrough. + +## Create the project + +Open Visual Studio and create a new Windows Forms Application project in Visual Basic or Visual C# named `StylingWpfContent`. + +> [!NOTE] +> When hosting WPF content, only C# and Visual Basic projects are supported. + +## Create the WPF control types + +After you add a WPF control type to the project, you can host it in an control. + +1. Add a new WPF project to the solution. Use the default name for the control type, `UserControl1.xaml`. For more information, see [Walkthrough: Creating New WPF Content on Windows Forms at Design Time](walkthrough-creating-new-wpf-content-on-windows-forms-at-design-time.md). + +2. In Design view, make sure that `UserControl1` is selected. + +3. In the **Properties** window, set the value of the and properties to **200**. + +4. Add a control to the and set the value of the property to **Cancel**. + +5. Add a second control to the and set the value of the property to **OK**. + +6. Build the project. + +## Apply a Style to a WPF Control + +You can apply different styling to a WPF control to change its appearance and behavior. + +1. Open `Form1` in the Windows Forms Designer. + +1. In the **Toolbox**, double-click `UserControl1` to create an instance of `UserControl1` on the form. + + An instance of `UserControl1` is hosted in a new control named `elementHost1`. + +1. In the smart tag panel for `elementHost1`, click **Edit Hosted Content** from the drop-down list. + + `UserControl1` opens in the WPF Designer. + +1. In XAML view, insert the following XAML after the `` opening tag. This XAML creates a gradient with a contrasting gradient border. When the control is clicked, the gradients are changed to generate a pressed button look. For more information, see [Styling and Templating](https://docs.microsoft.com/dotnet/desktop-wpf/fundamentals/styles-templates-overview). + + ```xaml + + + + + + + + + + + + + + + + + + + + + + + + + + + ``` + +1. Apply the `SimpleButton` style defined in the previous step to the Cancel button by inserting the following XAML in the ` + ``` + +1. Build the project. + +1. Open `Form1` in the Windows Forms Designer. + +1. The new style is applied to the button control. + +1. From the **Debug** menu, select **Start Debugging** to run the application. + +1. Click the **OK** and **Cancel** buttons and view the differences. + +## See also + +- +- +- [Migration and Interoperability](https://docs.microsoft.com/dotnet/framework/wpf/advanced/migration-and-interoperability) +- [Using WPF Controls](using-wpf-controls.md) +- [Design XAML in Visual Studio](/visualstudio/xaml-tools/designing-xaml-in-visual-studio) +- [XAML Overview (WPF)](https://docs.microsoft.com/dotnet/desktop-wpf/fundamentals/xaml) +- [Styling and Templating](https://docs.microsoft.com/dotnet/desktop-wpf/fundamentals/styles-templates-overview) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/why-transformation-order-is-significant.md b/dotnet-desktop-guide/framework/winforms/advanced/why-transformation-order-is-significant.md new file mode 100644 index 0000000000..9a4816dfc6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/why-transformation-order-is-significant.md @@ -0,0 +1,41 @@ +--- +title: "Why Transformation Order Is Significant" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "transformations [Windows Forms], order significance" +ms.assetid: 37d5f9dc-a5cf-4475-aa5d-34d714e808a9 +--- + +# Why Transformation Order Is Significant +A single object can store a single transformation or a sequence of transformations. The latter is called a composite transformation. The matrix of a composite transformation is obtained by multiplying the matrices of individual transformations. + +## Composite Transform Examples + In a composite transformation, the order of individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale. In GDI+, composite transformations are built from left to right. If S, R, and T are scale, rotation, and translation matrices respectively, then the product SRT (in that order) is the matrix of the composite transformation that first scales, then rotates, then translates. The matrix produced by the product SRT is different from the matrix produced by the product TRS. + + One reason order is significant is that transformations like rotation and scaling are done with respect to the origin of the coordinate system. Scaling an object that is centered at the origin produces a different result than scaling an object that has been moved away from the origin. Similarly, rotating an object that is centered at the origin produces a different result than rotating an object that has been moved away from the origin. + + The following example combines scaling, rotation and translation (in that order) to form a composite transformation. The argument passed to the method indicates that the rotation will follow the scaling. Likewise, the argument passed to the method indicates that the translation will follow the rotation. and are members of the enumeration. + + [!code-csharp[System.Drawing.MiscLegacyTopics#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#21)] + [!code-vb[System.Drawing.MiscLegacyTopics#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#21)] + + The following example makes the same method calls as the preceding example, but the order of the calls is reversed. The resulting order of operations is first translate, then rotate, then scale, which produces a very different result than first scale, then rotate, then translate. + + [!code-csharp[System.Drawing.MiscLegacyTopics#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#22)] + [!code-vb[System.Drawing.MiscLegacyTopics#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#22)] + + One way to reverse the order of individual transformations in a composite transformation is to reverse the order of a sequence of method calls. A second way to control the order of operations is to change the matrix order argument. The following example is the same as the preceding example, except that has been changed to . The matrix multiplication is done in the order SRT, where S, R, and T are the matrices for scale, rotate, and translate, respectively. The order of the composite transformation is first scale, then rotate, then translate. + + [!code-csharp[System.Drawing.MiscLegacyTopics#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs#23)] + [!code-vb[System.Drawing.MiscLegacyTopics#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb#23)] + + The result of the immediately preceding example is the same as the result of the first example in this topic. This is because we reversed both the order of the method calls and the order of the matrix multiplication. + +## See also + +- +- [Coordinate Systems and Transformations](coordinate-systems-and-transformations.md) +- [Using Transformations in Managed GDI+](using-transformations-in-managed-gdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-accessibility.md b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-accessibility.md new file mode 100644 index 0000000000..d25f0de3e6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-accessibility.md @@ -0,0 +1,28 @@ +--- +title: Accessibility +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, accessibility" + - "accessibility [Windows Forms], Windows Forms controls" +ms.assetid: 23a3f168-ebc0-4f23-9efc-799109aa4a2d +--- +# Windows Forms Accessibility +The accessibility functionality of Windows Forms allows you to make your application available to a wide variety of users. + +## In This Section + [Walkthrough: Creating an Accessible Windows-based Application](walkthrough-creating-an-accessible-windows-based-application.md) + Describes all of the features you should support to increase accessibility. + +## Reference + + A namespace containing a number of classes related to accessibility. + + + Provides information that accessibility applications use to adjust an application's user interface (UI) for users with impairments. + +## Related Sections + [Providing Accessibility Information for Controls on a Windows Form](../controls/providing-accessibility-information-for-controls-on-a-windows-form.md) + Describes how to supply information that Windows Forms controls can use to assist users with impairments. + + [Automatic Scaling in Windows Forms](../automatic-scaling-in-windows-forms.md) + Describes how to make your Windows Forms application react to changes in the system font size. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-and-unmanaged-applications-overview.md b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-and-unmanaged-applications-overview.md new file mode 100644 index 0000000000..462c2fe10c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-and-unmanaged-applications-overview.md @@ -0,0 +1,63 @@ +--- +title: Unmanaged apps overview +ms.date: "03/30/2017" +helpviewer_keywords: + - "COM [Windows Forms]" + - "Windows Forms, unmanaged" + - "COM interop" + - "ActiveX controls [Windows Forms], about ActiveX controls" + - "Windows Forms, interop" +ms.assetid: 0a26d99d-8135-4895-8760-c9a2b5f67f14 +--- +# Windows Forms and Unmanaged Applications Overview +Windows Forms applications and controls can interoperate with unmanaged applications, with some caveats. The following sections describe the scenarios and configurations that Windows Forms applications and controls support and those that they do not support. + +## Windows Forms Controls and ActiveX Applications + With the exception of Microsoft Internet Explorer and Microsoft Foundation Classes (MFC), Windows Forms controls are not supported in applications designed to host ActiveX controls. Other applications and development tools that are capable of hosting ActiveX controls, including the ActiveX test containers from versions of Visual Studio that are earlier than Visual Studio .NET 2003, are not supported hosts for Windows Forms controls. + + These constraints also apply to the use of Windows Forms controls through Component Object Model COM interop. The use of a Windows Forms control through a COM callable wrapper (CCW) is supported only in Internet Explorer. For more information about COM interop, see + + [COM Interop](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/com-interop/index). + + The following table shows the available ActiveX hosting support for Windows Forms controls. + +|Windows Forms version|Support| +|---------------------------|-------------| +|.NET Framework version 1.0|Internet Explorer 5.01 and later versions| +|.NET Framework version 1.1 and later|Internet Explorer 5.01 and later versions

Microsoft Foundation Classes (MFC) 7.0 and later| + +## Hosting Windows Forms components as ActiveX controls + In the .NET Framework 1.1, support was extended to include MFC 7.0 and later versions. This support includes any container that is fully compatible with the MFC 7.0 and later ActiveX control container. + + However, registration of Windows Forms controls as ActiveX controls is not supported. Also, calling the `com.ms.win32.Ole32.CoCreateInstance` method for Windows Forms controls is not supported. Only managed activation of Windows Forms controls is supported. Once you create a Windows Forms control, you can host it in an MFC application just as with an ActiveX control. + + To use Windows Forms controls in your unmanaged application, you must either host the CLR using the unmanaged CLR hosting APIs or use the C++ interop features. Using the C++ interop features is the recommended solution. + +## Windows Forms in COM client applications + When you open a Windows Form from a COM client application, such as a Visual Basic 6.0 application or an MFC application, the form may behave unexpectedly. For example, when you press the TAB key, the focus does not change from one control to another control. When you press the ENTER key while a command button has focus, the button's event is not raised. You may also experience unexpected behavior for keystrokes or mouse activity. + + This behavior occurs because the unmanaged application does not implement the message loop support that Windows Forms requires to work correctly. The message loop provided by the COM client application is fundamentally different from the Windows Forms message loop. + + An application's message loop is an internal program loop that retrieves messages from a thread's message queue, translates them, and then sends them to the application to be handled. The message loop for a Windows Form does not have the same architecture as message loops that earlier applications, such as Visual Basic 6.0 applications and MFC applications, provide. The window messages that are posted to the message loop may be handled differently than the Windows Form expects. Therefore, unexpected behavior may occur. Some keystroke combinations may not work, some mouse activity may not work, or some events may not be raised as expected. + +## Resolving Interoperability Issues + You can resolve these problems by displaying the form on a .NET Framework message loop, which is created by using the method. + + To make a Windows Form work correctly from a COM client application, you must run it on a Windows Forms message loop. To do this, use one of the following approaches: + +- Use the method to display the Windows Form. For more information, see [How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method](com-interop-by-displaying-a-windows-form-shadow.md). + +- Display each Windows Form on a new thread. For more information, see [How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread](how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md). + +## See also + +- [Windows Forms and Unmanaged Applications](windows-forms-and-unmanaged-applications.md) +- [COM Interop](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/com-interop/index) +- [COM Interoperability in .NET Framework Applications](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/com-interop/com-interoperability-in-net-framework-applications) +- [COM Interoperability Samples](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/cxcz83xf(v=vs.90)) +- [Aximp.exe (Windows Forms ActiveX Control Importer)](https://docs.microsoft.com/dotnet/framework/tools/aximp-exe-windows-forms-activex-control-importer) +- [Exposing .NET Framework Components to COM](https://docs.microsoft.com/dotnet/framework/interop/exposing-dotnet-components-to-co) +- [Packaging an Assembly for COM](https://docs.microsoft.com/dotnet/framework/interop/packaging-an-assembly-for-co) +- [Registering Assemblies with COM](https://docs.microsoft.com/dotnet/framework/interop/registering-assemblies-with-co) +- [How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method](com-interop-by-displaying-a-windows-form-shadow.md) +- [How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread](how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md) diff --git a/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-and-unmanaged-applications.md b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-and-unmanaged-applications.md new file mode 100644 index 0000000000..583e34fe98 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-and-unmanaged-applications.md @@ -0,0 +1,39 @@ +--- +title: Unmanaged apps +ms.date: "03/30/2017" +helpviewer_keywords: + - "ActiveX controls [Windows Forms]" + - "COM interop [Windows Forms], Windows Forms" + - "COM [Windows Forms]" + - "Windows Forms, unmanaged" + - "Windows Forms, interop" +ms.assetid: 81bc100c-fa49-4614-85a6-0f7ab59eac8a +--- +# Windows Forms and Unmanaged Applications +Windows Forms applications and controls can interoperate with unmanaged applications, with some caveats. The following sections describe the scenarios and configurations that Windows Forms applications and controls support and those that they do not support. + +## In This Section + [Windows Forms and Unmanaged Applications Overview](windows-forms-and-unmanaged-applications-overview.md) + Offers general information about how to use and implement Windows Forms controls that work with unmanaged applications. + + [How to: Support COM Interop by Displaying a Windows Form with the ShowDialog Method](com-interop-by-displaying-a-windows-form-shadow.md) + Provides a code example that shows how to use the method to run a Windows Form in an unmanaged application. + + [How to: Support COM Interop by Displaying Each Windows Form on Its Own Thread](how-to-support-com-interop-by-displaying-each-windows-form-on-its-own-thread.md) + Provides a code example that shows how to run a Windows Form on its own thread. + + Also see [Walkthrough: Supporting COM Interop by Displaying Each Windows Form on Its Own Thread](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233639(v=vs.100)). + +## Reference + + Used to create a separate thread for a Windows Form. + + + Starts a message loop for a thread. + + + Marshals calls from an unmanaged application to a form. + +## Related Sections + [Exposing .NET Framework Components to COM](https://docs.microsoft.com/dotnet/framework/interop/exposing-dotnet-components-to-co) + Offers general information about how to use .NET Framework types in unmanaged applications. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-print-support.md b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-print-support.md new file mode 100644 index 0000000000..beebc70c6b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-print-support.md @@ -0,0 +1,58 @@ +--- +title: Print Support +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, printing" + - "printing [Windows Forms]" + - "forms [Windows Forms], printing (using designer)" + - "printing [Windows Forms], Windows Forms, support" + - "printing [Windows Forms], print support" +ms.assetid: a4a2960c-eb70-48e2-b641-cfb222704e46 +--- +# Windows Forms Print Support +Printing in Windows Forms consists primarily of using the [PrintDocument Component](../controls/printdocument-component-windows-forms.md) component to enable the user to print, and the [PrintPreviewDialog Control](../controls/printpreviewdialog-control-windows-forms.md) control, [PrintDialog Component](../controls/printdialog-component-windows-forms.md) and [PageSetupDialog Component](../controls/pagesetupdialog-component-windows-forms.md) components to provide a familiar graphical interface to users accustomed to the Windows operating system. + + Typically, you create a new instance of the component, set the properties that describe what to print using the and classes, and call the method to actually print the document. + + During the course of printing from a Windows-based application, the component will show an abort print dialog box to alert users to the fact that printing is occurring and to allow the print job to be canceled. + +## In This Section + [How to: Create Standard Windows Forms Print Jobs](how-to-create-standard-windows-forms-print-jobs.md) + Explains how to use the component to print from a Windows Form. + + [How to: Capture User Input from a PrintDialog at Run Time](how-to-capture-user-input-from-a-printdialog-at-run-time.md) + Explains how to modify selected print options programmatically using the component. + + [How to: Choose the Printers Attached to a User's Computer in Windows Forms](how-to-choose-the-printers-attached-to-user-computer-in-windows-forms.md) + Describes changing the printer to print to using the component at run time. + + [How to: Print Graphics in Windows Forms](how-to-print-graphics-in-windows-forms.md) + Describes sending graphics to the printer. + + [How to: Print a Multi-Page Text File in Windows Forms](how-to-print-a-multi-page-text-file-in-windows-forms.md) + Describes sending text to the printer. + + [How to: Complete Windows Forms Print Jobs](how-to-complete-windows-forms-print-jobs.md) + Explains how to alert users to the completion of a print job. + + [How to: Print a Windows Form](how-to-print-a-windows-form.md) + Shows how to print a copy of the current form. + + [How to: Print in Windows Forms Using Print Preview](how-to-print-in-windows-forms-using-print-preview.md) + Shows how to use a for printing a document. + +## Related Sections + [PrintDocument Component](../controls/printdocument-component-windows-forms.md) + Explains usage of the component. + + [PrintDialog Component](../controls/printdialog-component-windows-forms.md) + Explains usage of the component. + + [PrintPreviewDialog Control](../controls/printpreviewdialog-control-windows-forms.md) + Explains usage of the control. + + [PageSetupDialog Component](../controls/pagesetupdialog-component-windows-forms.md) + Explains usage of the component. + + + Describes the classes in the namespace. diff --git a/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-visual-inheritance.md b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-visual-inheritance.md new file mode 100644 index 0000000000..0cb8779ba8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/windows-forms-visual-inheritance.md @@ -0,0 +1,43 @@ +--- +title: Visual Inheritance +ms.date: "03/30/2017" +helpviewer_keywords: + - "base forms" + - "inheritance [Windows Forms], forms" + - "inherited forms [Windows Forms], Windows Forms" + - "inheritance" + - "inherited forms" + - "form inheritance" + - "Windows Forms, inheritance" +ms.assetid: 857eb737-3602-4d49-bd8b-f70d33ace345 +--- +# Windows Forms Visual Inheritance +Occasionally, you may decide that a project calls for a form similar to one that you have created in a previous project. Or, you may want to create a basic form with settings such as a watermark or certain control layout that you will then use again within a project, with each iteration containing modifications to the original form template. Form inheritance enables you to create a base form and then inherit from it and make modifications while preserving whatever original settings you need. + + You can create derived-class forms programmatically or by using the Visual Inheritance picker. + +## In This Section + [How to: Inherit Windows Forms](how-to-inherit-windows-forms.md) + Gives directions for creating inherited forms in code. + + [How to: Inherit Forms Using the Inheritance Picker Dialog Box](how-to-inherit-forms-using-the-inheritance-picker-dialog-box.md) + Gives directions for creating inherited forms with the Inheritance Picker. + + [Effects of Modifying a Base Form's Appearance](effects-of-modifying-base-form-appearance.md) + Gives directions for changing a base form's controls and their properties. + + [Walkthrough: Demonstrating Visual Inheritance](walkthrough-demonstrating-visual-inheritance.md) + Describes how to create a base Windows Form and compile it into a class library. You will import this class library into another project, and create a new form that inherits from the base form. + + [How to: Use the Modifiers and GenerateMember Properties](how-to-use-the-modifiers-and-generatemember-properties.md) + Gives directions for using the `GenerateMember` and `Modifiers` properties, which are relevant when the Windows Forms Designer generates a member variable for a component. + +## Related Sections + [Inheritance basics (Visual Basic)](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/inheritance-basics) + Describes how to define Visual Basic classes that serve as the basis for other classes. + + [class](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/class) + Describes the C# approach of classes, in which single inheritance is allowed. + + [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers) + Lists common issues that arise with event handlers in inherited components diff --git a/dotnet-desktop-guide/framework/winforms/advanced/working-with-images-bitmaps-icons-and-metafiles.md b/dotnet-desktop-guide/framework/winforms/advanced/working-with-images-bitmaps-icons-and-metafiles.md new file mode 100644 index 0000000000..7fecd471c5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/advanced/working-with-images-bitmaps-icons-and-metafiles.md @@ -0,0 +1,59 @@ +--- +title: "Working with Images, Bitmaps, Icons, and Metafiles" +ms.date: "03/30/2017" +helpviewer_keywords: + - "metafiles [Windows Forms], working with" + - "examples [Windows Forms], bitmaps" + - "examples [Windows Forms], images" + - "bitmaps [Windows Forms], working with" + - "images [Windows Forms], working with" + - "examples [Windows Forms], metafiles" +ms.assetid: a626d701-bd99-4fd8-b92f-7b8f794e042b +--- +# Working with Images, Bitmaps, Icons, and Metafiles +GDI+ provides the `Bitmap` class for working with raster images and the `Metafile` class for working with vector images. The `Bitmap` and the `Metafile` classes both inherit from the `Image` class. + +## In This Section + [How to: Draw an Existing Bitmap to the Screen](how-to-draw-an-existing-bitmap-to-the-screen.md) + Describes how to load and draw bitmaps. + + [How to: Load and Display Metafiles](how-to-load-and-display-metafiles.md) + Shows how to load and draw metafiles. + + [Cropping and Scaling Images in GDI+](cropping-and-scaling-images-in-gdi.md) + Explains how to crop and scale vector and raster images. + + [How to: Rotate, Reflect, and Skew Images](how-to-rotate-reflect-and-skew-images.md) + Describes how to draw rotated, reflected and skewed images. + + [How to: Use Interpolation Mode to Control Image Quality During Scaling](how-to-use-interpolation-mode-to-control-image-quality-during-scaling.md) + Shows how to use the enumeration to change image quality. + + [How to: Create Thumbnail Images](how-to-create-thumbnail-images.md) + Describes how to create thumbnail images. + + [How to: Improve Performance by Avoiding Automatic Scaling](how-to-improve-performance-by-avoiding-automatic-scaling.md) + Explains how to draw an image without automatic scaling. + + [How to: Read Image Metadata](how-to-read-image-metadata.md) + Describes how to read metadata from an image. + + [How to: Create a Bitmap at Run Time](how-to-create-a-bitmap-at-run-time.md) + Shows how to draw a bitmap at runtime. + + [How to: Extract the Icon Associated with a File in Windows Forms](how-to-extract-the-icon-associated-with-a-file-in-windows-forms.md) + Describes how to extract an icon that is an embedded resource of a file. + +## Reference + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + +## Related Sections + [Images, Bitmaps, and Metafiles](images-bitmaps-and-metafiles.md) + Contains links to topics that discuss different types of bitmaps and manipulating them in your applications. diff --git a/dotnet-desktop-guide/framework/winforms/automatic-scaling-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/automatic-scaling-in-windows-forms.md new file mode 100644 index 0000000000..d2d2780d39 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/automatic-scaling-in-windows-forms.md @@ -0,0 +1,103 @@ +--- +title: "Automatic Scaling" +description: Learn about how automatic scaling enables a form and its controls, designed on one machine, to be displayed appropriately on another machine. +ms.date: "06/15/2017" +helpviewer_keywords: + - "scalability [Windows Forms], automatic in Windows Forms" + - "Windows Forms, automatic scaling" +ms.assetid: 68fad25b-afbc-44bd-8e1b-966fc43507a4 +--- +# Automatic scaling in Windows Forms + +Automatic scaling enables a form and its controls, designed on one machine with a certain display resolution or system font, to be displayed appropriately on another machine with a different display resolution or system 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. The support of the .NET Framework for automatic scaling and visual styles enables .NET Framework 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 .NET Framework version 2.0 and later. However, font scheme changes can be problematic. For an example of how to resolve this, see [How to: Respond to Font Scheme Changes in a Windows Forms Application](how-to-respond-to-font-scheme-changes-in-a-windows-forms-application.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 ameliorate 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, the .NET Framework supports automatic scaling either according to the default system font or the display resolution. Optionally, automatic scaling can be disabled in an application. + +## Original support for automatic scaling + +Versions 1.0 and 1.1 of the .NET Framework supported automatic scaling in a straightforward manner that was dependent on the Windows default font used for the UI, represented by the Win32 SDK value **DEFAULT_GUI_FONT**. This font is typically only changed when the display resolution changes. The following mechanism was used to implement automatic scaling: + +1. At design time, the property (which is now deprecated) was set to the height and width of the default system font on the developer's machine. + +2. At runtime, the default system font of the user's machine was used to initialize the property of the class. + +3. Before displaying the form, the method was called to scale the form. This method calculated the relative scale sizes from and then called the method to actually scale the form and its children. + +4. The value of was updated so that subsequent calls to did not progressively resize the form. + +While this mechanism was sufficient for most purposes, it suffered from the following limitations: + +- Since the property represents the baseline font size as integer values, rounding errors occur that become evident when a form is cycled through multiple resolutions. + +- Automatic scaling was implemented in only the class, not in the class. As a result, user controls would scale correctly only when the user control was designed at the same resolution as the form, and it was placed in the form at design time. + +- Forms and their child controls could only be concurrently designed by multiple developers if their machine resolutions were the same. Likewise it also made inheritance of a form dependent on the resolution associated with the parent form. + +- It is not compatible with the newer layout managers introduced with the .NET Framework version 2.0, such as and . + +- It did not support scaling based directly on the display resolution that is required for compatibility to the .NET Compact Framework. + +Although this mechanism is preserved in the .NET Framework version 2.0 to maintain backward compatibility, it has been superseded by the more robust scaling mechanism described next. As a consequence, the , , , and certain overloads are marked as obsolete. + +> [!NOTE] +> You can safely delete references to these members when you upgrade your legacy code to the .NET Framework version 2.0. + +## Current support for automatic scaling + +The .NET Framework version 2.0 surmounts previous limitations by introducing the following changes to the automatic scaling of Windows Forms: + +- Base support for scaling has been moved to the class so that forms, native composite controls and user controls all receive uniform scaling support. The new members , , and have been added. + +- The class also has several new members that allow it to participate in scaling and to support mixed scaling on the same form. Specifically the , , and members support scaling. + +- Support for scaling based upon the screen resolution has been added to complement system font support, as defined by the enumeration. This mode is compatible with automatic scaling supported by the .NET Compact Framework enabling easier application migration. + +- Compatibility with layout managers such as and has been added to the implementation of automatic scaling. + +- Scaling factors are now represented as floating point values, typically using the structure, so that rounding errors have been practically eliminated. + +> [!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 now uses the following logic to automatically scale forms and their contents: + +1. At design time, each records the scaling mode and it current resolution in the and , respectively. + +2. 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. + +3. 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. + +4. 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. + +5. 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 + +- +- +- +- +- [Rendering Controls with Visual Styles](./controls/rendering-controls-with-visual-styles.md) +- [How to: Improve Performance by Avoiding Automatic Scaling](./advanced/how-to-improve-performance-by-avoiding-automatic-scaling.md) diff --git a/dotnet-desktop-guide/framework/winforms/change-notification-in-windows-forms-data-binding.md b/dotnet-desktop-guide/framework/winforms/change-notification-in-windows-forms-data-binding.md new file mode 100644 index 0000000000..66a4fdf156 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/change-notification-in-windows-forms-data-binding.md @@ -0,0 +1,36 @@ +--- +title: Change Notification in Data Binding +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, data binding" + - "Windows Forms, adding change notification for data binding" +ms.assetid: b5b10f90-0585-41d9-a377-409835262a92 +--- +# Change Notification in Windows Forms Data Binding +One of the most important concepts of Windows Forms data binding is *change notification*. To ensure that your data source and bound controls always have the most recent data, you must add change notification for data binding. Specifically, you want to ensure that bound controls are notified of changes that were made to their data source, and the data source is notified of changes that were made to the bound properties of a control. + + There are different kinds of change notification, depending on the kind of data binding: + +- Simple binding, in which a single control property is bound to a single instance of an object. + +- List-based binding, which can include a single control property bound to the property of an item in a list or a control property bound to a list of objects. + + Additionally, if you are creating Windows Forms controls that you want to use for data binding, you must apply the *PropertyName*Changed pattern to the controls, so that changes to the bound property of a control are propagated to the data source. + +## Change Notification for Simple Binding + For simple binding, business objects must provide change notification when the value of a bound property changes. You can do this by exposing an *PropertyName*Changed event for each property of your business object and binding the business object to controls with the or the preferred method in which your business object implements the interface and raises a event when the value of a property changes. For more information, see [How to: Implement the INotifyPropertyChanged Interface](how-to-implement-the-inotifypropertychanged-interface.md). When you use objects that implement the interface, you do not have to use the to bind the object to a control, but using the is recommended. + +## Change Notification for List-Based Binding + Windows Forms depends on a bound list to provide property change (a list item property value changes) and list changed (an item is deleted or added to the list) information to bound controls. Therefore, lists used for data binding must implement the , which provides both types of change notification. The is a generic implementation of and is designed for use with Windows Forms data binding. You can create a that contains a business object type that implements and the list will automatically convert the events to events. If the bound list is not an , you must bind the list of objects to Windows Forms controls by using the component. The component will provide property-to-list conversion similar to that of the . For more information, see [How to: Raise Change Notifications Using a BindingSource and the INotifyPropertyChanged Interface](./controls/raise-change-notifications--bindingsource.md). + +## Change Notification for Custom Controls + Finally, from the control side you must expose a *PropertyName*Changed event for each property designed to be bound to data. The changes to the control property are then propagated to the bound data source. For more information, see [How to: Apply the PropertyNameChanged Pattern](how-to-apply-the-propertynamechanged-pattern.md) + +## See also + +- +- +- +- [Windows Forms Data Binding](windows-forms-data-binding.md) +- [Data Sources Supported by Windows Forms](data-sources-supported-by-windows-forms.md) +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/changing-the-appearance-of-windows-forms.md b/dotnet-desktop-guide/framework/winforms/changing-the-appearance-of-windows-forms.md new file mode 100644 index 0000000000..843ba00dda --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/changing-the-appearance-of-windows-forms.md @@ -0,0 +1,43 @@ +--- +title: Customize appearance +description: Learn how to customize the look of your Windows Forms applications by changing the border, opacity, shape, style, or setting a background image. +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, changing the appearance of" +ms.assetid: 12f35d5b-1587-49cc-ada3-47eec1ff1738 +--- +# Changing the Appearance of Windows Forms +You can customize the look of your Windows Forms applications in many different ways, such as changing the border, opacity, shape, style, or setting a background image for your Windows Forms application. + +## In This Section + [How to: Change the Borders of Windows Forms](how-to-change-the-borders-of-windows-forms.md) + Shows how to change the border style of a form. + +## Reference + + Describes this class and has links to all of its members. + + + Describes this enumeration and contains descriptions of all of its members. + + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + +## Related Sections + [Adjusting the Size and Scale of Windows Forms](adjusting-the-size-and-scale-of-windows-forms.md) + Contains links to topics that show how to change the size and scale of a form. + + [Graphics and Drawing in Windows Forms](./advanced/graphics-and-drawing-in-windows-forms.md) + Contains links to topics that describe how to perform custom drawing on Windows Forms. + + [Controls with Built-In Owner-Drawing Support](./controls/controls-with-built-in-owner-drawing-support.md) + List owner-draw support in Windows Forms controls. diff --git a/dotnet-desktop-guide/framework/winforms/clickonce-deployment-for-windows-forms.md b/dotnet-desktop-guide/framework/winforms/clickonce-deployment-for-windows-forms.md new file mode 100644 index 0000000000..7b4921e029 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/clickonce-deployment-for-windows-forms.md @@ -0,0 +1,66 @@ +--- +title: "ClickOnce Deployment" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ClickOnce deployment [Windows Forms]" + - "Windows Forms, ClickOnce deployment" + - "walkthroughs [Windows Forms], ClickOnce deployment" +ms.assetid: 1451fce9-1965-4a03-b4d3-831b5fe4ad66 +--- +# ClickOnce Deployment for Windows Forms +The following topics describe ClickOnce, a technology used for easily deploying Windows Forms applications to client computers. + +## Related Sections + [Choosing a ClickOnce Deployment Strategy](/visualstudio/deployment/choosing-a-clickonce-deployment-strategy) + Presents several options for deploying ClickOnce applications. + + [Choosing a ClickOnce Update Strategy](/visualstudio/deployment/choosing-a-clickonce-update-strategy) + Presents several options for updating ClickOnce applications. + + [Securing ClickOnce Applications](/visualstudio/deployment/securing-clickonce-applications) + Explains the security implications of ClickOnce deployment. + + [Troubleshooting ClickOnce Deployments](/visualstudio/deployment/troubleshooting-clickonce-deployments) + Describes various problems that can occur when deploying ClickOnce applications, and documents the top-level error messages that ClickOnce might generate. + + [ClickOnce and Application Settings](/visualstudio/deployment/clickonce-and-application-settings) + Describes how ClickOnce deployment works with application settings, which stores application and user settings for future retrieval. + + [Trusted Application Deployment Overview](/visualstudio/deployment/trusted-application-deployment-overview) + Describes a ClickOnce feature that allows trusted applications to run with a higher level of permission on client computers. + + [ClickOnce and Authenticode](/visualstudio/deployment/clickonce-and-authenticode) + Describes how Authenticode technology is used in trusted application deployment. + + [Walkthrough: Manually Deploying a ClickOnce Application](/visualstudio/deployment/walkthrough-manually-deploying-a-clickonce-application) + Demonstrates using command-line and SDK tools to deploy a ClickOnce application without using Visual Studio. + + [How to: Add a Trusted Publisher to a Client Computer for ClickOnce Applications](/visualstudio/deployment/how-to-add-a-trusted-publisher-to-a-client-computer-for-clickonce-applications) + Demonstrates the one-time configuration of client computers required for trusted application deployment. + + [How to: Specify an Alternate Location for Deployment Updates](/visualstudio/deployment/how-to-specify-an-alternate-location-for-deployment-updates) + Demonstrates configuring a ClickOnce application, using SDK tools, to check a different location for new versions of an application. + + [Walkthrough: Downloading Assemblies on Demand with the ClickOnce Deployment API](/visualstudio/deployment/walkthrough-downloading-assemblies-on-demand-with-the-clickonce-deployment-api) + Demonstrates using API calls to retrieve an assembly the first time your application attempts to load it. + + [How to: Retrieve Query String Information in an Online ClickOnce Application](/visualstudio/deployment/how-to-retrieve-query-string-information-in-an-online-clickonce-application) + Demonstrates retrieving parameters from the URL used to run a ClickOnce application. + + [ClickOnce Cache Overview](/visualstudio/deployment/clickonce-cache-overview) + Describes the cache used to store ClickOnce applications on the local computer. + + [Accessing Local and Remote Data in ClickOnce Applications](/visualstudio/deployment/accessing-local-and-remote-data-in-clickonce-applications) + Describes how to access local data files and remote data sources from a ClickOnce application. + + [How to: Include a Data File in a ClickOnce Application](/visualstudio/deployment/how-to-include-a-data-file-in-a-clickonce-application) + Demonstrates how to mark a file so that it is available in the ClickOnce data directory. + +## See also + +- [Application Settings Overview](./advanced/application-settings-overview.md) +- [Publishing ClickOnce Applications](/visualstudio/deployment/publishing-clickonce-applications) +- [Building ClickOnce Applications from the Command Line](/visualstudio/deployment/building-clickonce-applications-from-the-command-line) +- [Debugging ClickOnce Applications That Use System.Deployment.Application](/visualstudio/deployment/debugging-clickonce-applications-that-use-system-deployment-application) +- [Deploying COM Components with ClickOnce](/visualstudio/deployment/deploying-com-components-with-clickonce) +- [How to: Publish a ClickOnce Application using the Publish Wizard](/visualstudio/deployment/how-to-publish-a-clickonce-application-using-the-publish-wizard) diff --git a/dotnet-desktop-guide/framework/winforms/controls/access-objects-in-a-wf-datagridviewcomboboxcell-drop-down-list.md b/dotnet-desktop-guide/framework/winforms/controls/access-objects-in-a-wf-datagridviewcomboboxcell-drop-down-list.md new file mode 100644 index 0000000000..1de6b02eb2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/access-objects-in-a-wf-datagridviewcomboboxcell-drop-down-list.md @@ -0,0 +1,78 @@ +--- +title: Access Objects in DataGridViewComboBoxCell Drop-Down List +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], accessing objects in combo box cells" + - "combo boxes [Windows Forms], in DataGridView control" + - "combo boxes [Windows Forms], accessing objects in DataGridViewComboBoxCell drop-down lists" +ms.assetid: bcbe794a-d1fa-47f8-b5a3-5f085b32097d +--- +# How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List +Like the control, the and types enable you to add arbitrary objects to their drop-down lists. With this feature, you can represent complex states in a drop-down list without having to store corresponding objects in a separate collection. + + Unlike the control, the types do not have a property for retrieving the currently selected object. Instead, you must set the or property to the name of a property on your business object. When the user makes a selection, the indicated property of the business object sets the cell property. + + To retrieve the business object through the cell value, the `ValueMember` property must indicate a property that returns a reference to the business object itself. Therefore, if the type of the business object is not under your control, you must add such a property by extending the type through inheritance. + + The following procedures demonstrate how to populate a drop-down list with business objects and retrieve the objects through the cell property. + +### To add business objects to the drop-down list + +1. Create a new and populate its collection. Alternatively, you can set the column property to the collection of business objects. In that case, however, you cannot add "unassigned" to the drop-down list without creating a corresponding business object in your collection. + + [!code-csharp[System.Windows.Forms.DataGridViewComboBoxObjectBinding#110](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs#110)] + [!code-vb[System.Windows.Forms.DataGridViewComboBoxObjectBinding#110](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb#110)] + +2. Set the and properties. indicates the property of the business object to display in the drop-down list. indicates the property that returns a reference to the business object. + + [!code-csharp[System.Windows.Forms.DataGridViewComboBoxObjectBinding#115](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs#115)] + [!code-vb[System.Windows.Forms.DataGridViewComboBoxObjectBinding#115](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb#115)] + +3. Make sure that your business object type contains a property that returns a reference to the current instance. This property must be named with the value assigned to in the previous step. + + [!code-csharp[System.Windows.Forms.DataGridViewComboBoxObjectBinding#310](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs#310)] + [!code-vb[System.Windows.Forms.DataGridViewComboBoxObjectBinding#310](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb#310)] + +### To retrieve the currently selected business object + +- Get the cell property and cast it to the business object type. + + [!code-csharp[System.Windows.Forms.DataGridViewComboBoxObjectBinding#120](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs#120)] + [!code-vb[System.Windows.Forms.DataGridViewComboBoxObjectBinding#120](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb#120)] + +## Example + The complete example demonstrates the use of business objects in a drop-down list. In the example, a control is bound to a collection of `Task` objects. Each `Task` object has an `AssignedTo` property that indicates the `Employee` object currently assigned to that task. The `Assigned To` column displays the `Name` property value for each assigned employee, or "unassigned" if the `Task.AssignedTo` property value is `null`. + + To view the behavior of this example, perform the following steps: + +1. Change assignments in the `Assigned To` column by selecting different values from the drop-down lists or pressing CTRL+0 in a combo-box cell. + +2. Click `Generate Report` to display the current assignments. This demonstrates that a change in the `Assigned To` column automatically updates the `tasks` collection. + +3. Click a `Request Status` button to call the `RequestStatus` method of the current `Employee` object for that row. This demonstrates that the selected object has been successfully retrieved. + + [!code-csharp[System.Windows.Forms.DataGridViewComboBoxObjectBinding#000](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs#000)] + [!code-vb[System.Windows.Forms.DataGridViewComboBoxObjectBinding#000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb#000)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/access-specific-items-in-a-wf-combobox-listbox-or-checkedlistbox.md b/dotnet-desktop-guide/framework/winforms/controls/access-specific-items-in-a-wf-combobox-listbox-or-checkedlistbox.md new file mode 100644 index 0000000000..069c79c4d9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/access-specific-items-in-a-wf-combobox-listbox-or-checkedlistbox.md @@ -0,0 +1,53 @@ +--- +title: Access Specific Items in ComboBox, ListBox, or CheckedListBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ComboBox control [Windows Forms], accessing items" + - "ListBox control [Windows Forms], returning item information" + - "list boxes [Windows Forms], accessing items" + - "ListBox control [Windows Forms], accessing items" + - "combo boxes [Windows Forms], accessing items" + - "CheckedListBox control [Windows Forms], accessing items" +ms.assetid: 1216742f-bcf9-4ff8-8a62-d7c9053c2b96 +--- +# How to: Access Specific Items in a Windows Forms ComboBox, ListBox, or CheckedListBox Control +Accessing specific items in a Windows Forms combo box, list box, or checked list box is an essential task. It enables you to programmatically determine what is in a list, at any given position. + +### To access a specific item + +1. Query the `Items` collection using the index of the specific item: + + ```vb + Private Function GetItemText(i As Integer) As String + ' Return the text of the item using the index: + Return ComboBox1.Items(i).ToString + End Function + ``` + + ```csharp + private string GetItemText(int i) + { + // Return the text of the item using the index: + return (comboBox1.Items[i].ToString()); + } + ``` + + ```cpp + private: + String^ GetItemText(int i) + { + // Return the text of the item using the index: + return (comboBox1->Items->Item[i]->ToString()); + } + ``` + +## See also + +- +- +- +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/accessing-frames-in-the-managed-html-document-object-model.md b/dotnet-desktop-guide/framework/winforms/controls/accessing-frames-in-the-managed-html-document-object-model.md new file mode 100644 index 0000000000..7269670500 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/accessing-frames-in-the-managed-html-document-object-model.md @@ -0,0 +1,38 @@ +--- +title: "Accessing Frames in the Managed HTML Document Object Model" +ms.date: "03/30/2017" +helpviewer_keywords: + - "HTML [Windows Forms], dOM" + - "managed HTML DOM" + - "HTML [Windows Forms], managed" + - "HTML DOM [Windows Forms], managed" + - "frames [Windows Forms], accessing" + - "DOM [Windows Forms], accessing frames in managed HTML" +ms.assetid: cdeeaa22-0be4-4bbf-9a75-4ddc79199f8d +--- +# Accessing Frames in the Managed HTML Document Object Model +Some HTML documents are composed out of *frames*, or windows that can hold their own distinct HTML documents. Using frames makes it easy to create HTML pages in which one or more pieces of the page remain static, such as a navigation bar, while other frames constantly change their content. + + HTML authors can create frames in one of two ways: + +- Using the `FRAMESET` and `FRAME` tags, which create fixed windows. + + -or- + +- Using the `IFRAME` tag, which creates a floating window that can be repositioned at run time. + +1. Because frames contain HTML documents, they are represented in the Document Object Model (DOM) as both window elements and frame elements. + +2. When you access a `FRAME` or `IFRAME` tag by using the Frames collection of , you are retrieving the window element corresponding to the frame. This represents all of the frame's dynamic properties, such as its current URL, document, and size. + +3. When you access a `FRAME` or `IFRAME` tag by using the property of , the collection, or methods such as or , you are retrieving the frame element. This represents the static properties of the frame, including the URL specified in the original HTML file. + +## Frames and Security + Access to frames is complicated by the fact that the managed HTML DOM implements a security measure known as *cross-frame scripting security*. If a document contains a `FRAMESET` with two or more `FRAME`s in different domains, these `FRAME`s cannot interact with one another. In other words, a `FRAME` that displays content from your Web site cannot access information in a `FRAME` that hosts a third-party site such as `http://www.adatum.com/`. This security is implemented at the level of the class. You can obtain general information about a `FRAME` hosting another Web site, such as its URL, but you will be unable to access its or change the size or location of its hosting `FRAME` or `IFRAME`. + + This rule also applies to windows that you open using the and methods. If the window you open is in a different domain from the page hosted in the control, you will not be able to move that window or examine its contents. These restrictions are also enforced if you use the control to display a Web site that is different from the Web site used to deploy your Windows Forms-based application. If you use ClickOnce deployment technology to install your application from Web site A, and you use the to display Web site B, you will not be able to access Web site B's data. + +## See also + +- [\ element](https://developer.mozilla.org/docs/Web/HTML/Element/frame) +- [Using the Managed HTML Document Object Model](using-the-managed-html-document-object-model.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/accessing-unexposed-members-on-the-managed-html-document-object-model.md b/dotnet-desktop-guide/framework/winforms/controls/accessing-unexposed-members-on-the-managed-html-document-object-model.md new file mode 100644 index 0000000000..ac71bc39e9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/accessing-unexposed-members-on-the-managed-html-document-object-model.md @@ -0,0 +1,70 @@ +--- +title: "Accessing Unexposed Members on the Managed HTML Document Object Model" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "unexposed members" + - "managed HTML DOM [Windows Forms], accessing unexposed members" +ms.assetid: 762295bd-2355-4aa7-b43c-5bff997a33e6 +--- +# Accessing Unexposed Members on the Managed HTML Document Object Model +The managed HTML Document Object Model (DOM) contains a class called that exposes the properties, methods, and events that all HTML elements have in common. Sometimes, however, you will need to access members that the managed interface does not directly expose. This topic examines two ways for accessing unexposed members, including JScript and VBScript functions defined inside of a Web page. + +## Accessing Unexposed Members through Managed Interfaces + and provide four methods that enable access to unexposed members. The following table shows the types and their corresponding methods. + +|Member Type|Method(s)| +|-----------------|-----------------| +|Properties ()|

| +|Methods|| +|Events ()|

| +|Events ()|

| +|Events ()|

| + + When you use these methods, it is assumed that you have an element of the correct underlying type. Suppose that you want to listen to the `Submit` event of a `FORM` element on an HTML page, so that you can perform some pre-processing on the `FORM`'s values before the user submits them to the server. Ideally, if you have control over the HTML, you would define the `FORM` to have a unique `ID` attribute. + +```html + + + + Form Page + + + +
+ ... form fields defined here ... +
+ + + +``` + + After you load this page into the control, you can use the method to retrieve the `FORM` at run time using `form1` as the argument. + + [!code-csharp[System.Windows.Forms.HtmlElement#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.cs#10)] + [!code-vb[System.Windows.Forms.HtmlElement#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.vb#10)] + +## Accessing Unmanaged Interfaces + You can also access unexposed members on the managed HTML DOM by using the unmanaged Component Object Model (COM) interfaces exposed by each DOM class. This is recommended if you have to make several calls against unexposed members, or if the unexposed members return other unmanaged interfaces not wrapped by the managed HTML DOM. + + The following table shows all of the unmanaged interfaces exposed through the managed HTML DOM. Click on each link for an explanation of its usage and for example code. + +|Type|Unmanaged Interface| +|----------|-------------------------| +||| +||| +||| +||| + + The easiest way to use the COM interfaces is to add a reference to the unmanaged HTML DOM library (MSHTML.dll) from your application, although this is unsupported. For more information, see [Knowledge Base Article 934368](https://support.microsoft.com/kb/934368). + +## Accessing Script Functions + An HTML page can define one or more functions by using a scripting language such as JScript or VBScript. These functions are placed inside of a `SCRIPT` page in the page, and can be run on demand or in response to an event on the DOM. + + You can call any script functions you define in an HTML page using the method. If the script method returns an HTML element, you can use a cast to convert this return result to an . For details and example code, see . + +## See also + +- [Using the Managed HTML Document Object Model](using-the-managed-html-document-object-model.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-columns-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-columns-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..02d36131c4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-columns-in-the-datagrid-using-the-designer.md @@ -0,0 +1,39 @@ +--- +title: Add and Remove Columns in DataGridView Control Using the Designer +ms.date: "03/30/2017" +f1_keywords: + - "vs.DataGridViewAddColumnDialog" +helpviewer_keywords: + - "DataGridView control [Windows Forms], adding columns" + - "DataGridView control [Windows Forms], removing columns" +ms.assetid: 9e709f35-0a8c-4e7e-b4c4-bacb7a834077 +--- +# How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer +The Windows Forms control must contain columns in order to display data. If you plan to populate the control manually, you must add the columns yourself. Alternately, you can bind the control to a data source, which generates and populates the columns automatically. If the data source contains more columns than you want to display, you can remove the unwanted columns. + + The following procedures require a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To add a column using the designer + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Add Column**. + +2. In the **Add Column** dialog box, choose the **Databound Column** option and select a column from the data source, or choose the **Unbound Column** option and define the column using the fields provided. + +3. Click the **Add** button to add the column, causing it to appear in the designer if the existing columns do not already fill the control display area. + + > [!NOTE] + > You can modify column properties in the **Edit Columns** dialog box, which you can access from the control's smart tag. + +## To remove a column using the designer + +1. Choose **Edit Columns** from the control's smart tag. + +2. Select a column from the **Selected Columns** list. + +3. Click the **Remove** button to delete the column, causing it to disappear from the designer. + +## See also + +- +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-items-from-a-wf-combobox.md b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-items-from-a-wf-combobox.md new file mode 100644 index 0000000000..d4817f5e64 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-items-from-a-wf-combobox.md @@ -0,0 +1,141 @@ +--- +title: Add and Remove Items from ComboBox, ListBox, or CheckedListBox Control +ms.date: "03/30/2017" +description: Learn how to add and remove a Windows Forms ComboBox, ListBox, and CheckedListBox controls simply and with no data binding. +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "combo boxes [Windows Forms], adding items" + - "list boxes [Windows Forms], removing items" + - "ComboBox control [Windows Forms], adding and removing items" + - "ListBox control [Windows Forms], adding and removing items" + - "list boxes [Windows Forms], adding items" + - "combo boxes [Windows Forms], removing items" + - "CheckedListBox control [Windows Forms], adding and removing items" +ms.assetid: 7224c8d2-4118-443e-ae1e-d7c17d1e69ee +--- +# How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control +Items can be added to a Windows Forms combo box, list box, or checked list box in a variety of ways, because these controls can be bound to a variety of data sources. However, this topic demonstrates the simplest method and requires no data binding. The items displayed are usually strings; however, any object can be used. The text that is displayed in the control is the value returned by the object's `ToString` method. + +### To add items + +1. Add the string or object to the list by using the `Add` method of the `ObjectCollection` class. The collection is referenced using the `Items` property: + + ```vb + ComboBox1.Items.Add("Tokyo") + ``` + + ```csharp + comboBox1.Items.Add("Tokyo"); + ``` + + ```cpp + comboBox1->Items->Add("Tokyo"); + ``` + + - or - + +2. Insert the string or object at the desired point in the list with the `Insert` method: + + ```vb + CheckedListBox1.Items.Insert(0, "Copenhagen") + ``` + + ```csharp + checkedListBox1.Items.Insert(0, "Copenhagen"); + ``` + + ```cpp + checkedListBox1->Items->Insert(0, "Copenhagen"); + ``` + + - or - + +3. Assign an entire array to the `Items` collection: + + ```vb + Dim ItemObject(9) As System.Object + Dim i As Integer + For i = 0 To 9 + ItemObject(i) = "Item" & i + Next i + ListBox1.Items.AddRange(ItemObject) + ``` + + ```csharp + System.Object[] ItemObject = new System.Object[10]; + for (int i = 0; i <= 9; i++) + { + ItemObject[i] = "Item" + i; + } + listBox1.Items.AddRange(ItemObject); + ``` + + ```cpp + Array^ ItemObject = gcnew Array(10); + for (int i = 0; i <= 9; i++) + { + ItemObject[i] = String::Concat("Item", i.ToString()); + } + listBox1->Items->AddRange(ItemObject); + ``` + +### To remove an item + +1. Call the `Remove` or `RemoveAt` method to delete items. + + `Remove` has one argument that specifies the item to remove.`RemoveAt` removes the item with the specified index number. + + ```vb + ' To remove item with index 0: + ComboBox1.Items.RemoveAt(0) + ' To remove currently selected item: + ComboBox1.Items.Remove(ComboBox1.SelectedItem) + ' To remove "Tokyo" item: + ComboBox1.Items.Remove("Tokyo") + ``` + + ```csharp + // To remove item with index 0: + comboBox1.Items.RemoveAt(0); + // To remove currently selected item: + comboBox1.Items.Remove(comboBox1.SelectedItem); + // To remove "Tokyo" item: + comboBox1.Items.Remove("Tokyo"); + ``` + + ```cpp + // To remove item with index 0: + comboBox1->Items->RemoveAt(0); + // To remove currently selected item: + comboBox1->Items->Remove(comboBox1->SelectedItem); + // To remove "Tokyo" item: + comboBox1->Items->Remove("Tokyo"); + ``` + +### To remove all items + +1. Call the `Clear` method to remove all items from the collection: + + ```vb + ListBox1.Items.Clear() + ``` + + ```csharp + listBox1.Items.Clear(); + ``` + + ```cpp + listBox1->Items->Clear(); + ``` + +## See also + +- +- +- +- [How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control](sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md) +- [When to Use a Windows Forms ComboBox Instead of a ListBox](when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-items-with-wf-listview-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-items-with-wf-listview-control-using-the-designer.md new file mode 100644 index 0000000000..782e2e69d9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-items-with-wf-listview-control-using-the-designer.md @@ -0,0 +1,34 @@ +--- +title: Add and Remove Items with ListView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "ListView control [Windows Forms], populating" + - "ListView control [Windows Forms], adding list items" +ms.assetid: 217611ee-fd11-4d39-9a54-a37c3e781be1 +--- +# How to: Add and Remove Items with the Windows Forms ListView Control Using the Designer + +The process of adding an item to a Windows Forms control consists primarily of specifying the item and assigning properties to it. Adding or removing list items can be done at any time. + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To add or remove items using the designer + +1. Select the control. + +2. In the **Properties** window, click the **Ellipsis** (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button next to the property. + + The **ListViewItem Collection Editor** appears. + +3. To add an item, click the **Add** button. You can then set properties of the new item, such as the and properties. + +4. To remove an item, select it and click the **Remove** button. + +## See also + +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md) +- [How to: Display Subitems in Columns with the Windows Forms ListView Control](how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md) +- [How to: Display Icons for the Windows Forms ListView Control](how-to-display-icons-for-the-windows-forms-listview-control.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) +- [How to: Group Items in a Windows Forms ListView Control](how-to-group-items-in-a-windows-forms-listview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-menu-items-with-wf-contextmenu-component.md b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-menu-items-with-wf-contextmenu-component.md new file mode 100644 index 0000000000..1150d43bdf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-menu-items-with-wf-contextmenu-component.md @@ -0,0 +1,75 @@ +--- +title: Add and Remove Menu Items with ContextMenu Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "context menus [Windows Forms], removing items" + - "ContextMenu component [Windows Forms], adding items" + - "shortcut menus [Windows Forms], removing items" + - "shortcut menus [Windows Forms], examples" + - "context menus [Windows Forms], adding items" + - "shortcut menus [Windows Forms], adding items" + - "ContextMenu component [Windows Forms], removing items" + - "context menus [Windows Forms], examples" + - "examples [Windows Forms], context menus" +ms.assetid: 426d1eaf-7fb8-4b0b-8a33-5e8721786ea4 +--- +# How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component +Explains how to add and remove shortcut menu items in Windows Forms. + + The Windows Forms component provides a menu of frequently used commands that are relevant to the selected object. You can add items to the shortcut menu by adding objects to the collection. + + You can remove items from a shortcut menu permanently; however, at run time it may be more appropriate to hide or disable the items instead. + +> [!IMPORTANT] +> Although and replace and add functionality to the and controls of previous versions, and are retained for both backward compatibility and future use if you choose. + +### To remove items from a shortcut menu + +1. Use the or method of the collection of the component to remove a particular menu item. + + ```vb + ' Removes the first item in the shortcut menu. + ContextMenu1.MenuItems.RemoveAt(0) + ' Removes a particular object from the shortcut menu. + ContextMenu1.MenuItems.Remove(mnuItemNew) + ``` + + ```csharp + // Removes the first item in the shortcut menu. + contextMenu1.MenuItems.RemoveAt(0); + // Removes a particular object from the shortcut menu. + contextMenu1.MenuItems.Remove(mnuItemNew); + ``` + + ```cpp + // Removes the first item in the shortcut menu. + contextMenu1->MenuItems->RemoveAt(0); + // Removes a particular object from the shortcut menu. + contextMenu1->MenuItems->Remove(mnuItemNew); + ``` + + -or- + +2. Use the `Clear` method of the `MenuItems` collection of the component to remove all items from the menu. + + ```vb + ContextMenu1.MenuItems.Clear() + ``` + + ```csharp + contextMenu1.MenuItems.Clear(); + ``` + + ```cpp + contextMenu1->MenuItems->Clear(); + ``` + +## See also + +- +- [ContextMenu Component](contextmenu-component-windows-forms.md) +- [ContextMenu Component Overview](contextmenu-component-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-nodes-with-wf-treeview-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-nodes-with-wf-treeview-control-using-the-designer.md new file mode 100644 index 0000000000..6a0a2fe182 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-nodes-with-wf-treeview-control-using-the-designer.md @@ -0,0 +1,36 @@ +--- +title: Add and Remove Nodes with TreeView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "examples [Windows Forms], TreeView control" + - "TreeView control [Windows Forms], removing nodes" + - "tree nodes in TreeView control" + - "TreeView control [Windows Forms], adding nodes" +ms.assetid: 35bf1750-045e-4ec5-97cb-b47b0dbdaa2c +--- +# How to: Add and Remove Nodes with the Windows Forms TreeView Control Using the Designer + +Because the Windows Forms control displays nodes in a hierarchical manner, when adding a node you must pay attention to what its parent node is. + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To add or remove nodes in the designer + +1. Select the control. + +2. In the **Properties** window, click the **Ellipsis** (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button next to the property. + + The **TreeNode Editor** appears. + +3. To add nodes, a root node must exist; if one does not exist, you must first add a root by clicking the **Add Root** button. You can then add child nodes by selecting the root or any other node and clicking the **Add Child** button. + +4. To delete nodes, select the node to delete and then click the **Delete** button. + +## See also + +- [TreeView Control](treeview-control-windows-forms.md) +- [TreeView Control Overview](treeview-control-overview-windows-forms.md) +- [How to: Set Icons for the Windows Forms TreeView Control](how-to-set-icons-for-the-windows-forms-treeview-control.md) +- [How to: Iterate Through All Nodes of a Windows Forms TreeView Control](how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md) +- [How to: Determine Which TreeView Node Was Clicked](how-to-determine-which-treeview-node-was-clicked-windows-forms.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-tabs-with-wf-tabcontrol-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-tabs-with-wf-tabcontrol-using-the-designer.md new file mode 100644 index 0000000000..220eb3285e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-and-remove-tabs-with-wf-tabcontrol-using-the-designer.md @@ -0,0 +1,32 @@ +--- +title: Add and Remove Tabs with TabControl Using the Designer +description: Learn how to add and remove tabs with the Windows Forms TabControl control by using the designer. +ms.date: "03/30/2017" +helpviewer_keywords: + - "tabs [Windows Forms], removing from pages" + - "TabPage control" + - "TabPage control [Windows Forms], adding and removing tabs" + - "tabs [Windows Forms], adding to pages" + - "tab pages" +ms.assetid: 480633db-413a-45d2-9c8f-0427cc13adbe +--- +# How to: Add and Remove Tabs with the Windows Forms TabControl Using the Designer +When you place a control on your form, it contains two tabs by default. You can add or remove tabs using the designer. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To add or remove a tab using the designer + +- On the control's smart tag, click **Add Tab** or **Remove Tab** + + -or- + + In the **Properties** window, click the **Ellipsis** button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property to open the **TabPage Collection Editor**. Click the **Add** or **Remove** button. + +## See also + +- [TabControl Control](tabcontrol-control-windows-forms.md) +- [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) +- [How to: Add a Control to a Tab Page](how-to-add-a-control-to-a-tab-page.md) +- [How to: Disable Tab Pages](how-to-disable-tab-pages.md) +- [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-custom-information-to-a-treeview-or-listview-control-wf.md b/dotnet-desktop-guide/framework/winforms/controls/add-custom-information-to-a-treeview-or-listview-control-wf.md new file mode 100644 index 0000000000..43fc096969 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-custom-information-to-a-treeview-or-listview-control-wf.md @@ -0,0 +1,130 @@ +--- +title: "How to: Add Custom Information to a TreeView or ListView Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "ListItem" +helpviewer_keywords: + - "examples [Windows Forms], TreeView control" + - "examples [Windows Forms], ListView control" + - "ListView control [Windows Forms], adding custom information" + - "TreeView control [Windows Forms], adding custom information" +ms.assetid: 68be11de-1d5b-430e-901f-cfbe48d14b19 +--- +# How to: Add Custom Information to a TreeView or ListView Control (Windows Forms) +You can create a derived node in a Windows Forms control or a derived item in a control. Derivation allows you to add any fields you require, as well as custom methods and constructors for handling them. One use of this feature is to attach a Customer object to each tree node or list item. The examples here are for a control, but the same approach can be used for a control. + +### To derive a tree node + +- Create a new node class, derived from the class, which has a custom field to record a file path. + + ```vb + Class myTreeNode + Inherits TreeNode + + Public FilePath As String + + Sub New(ByVal fp As String) + MyBase.New() + FilePath = fp + Me.Text = fp.Substring(fp.LastIndexOf("\")) + End Sub + End Class + ``` + + ```csharp + class myTreeNode : TreeNode + { + public string FilePath; + + public myTreeNode(string fp) + { + FilePath = fp; + this.Text = fp.Substring(fp.LastIndexOf("\\")); + } + } + ``` + + ```cpp + ref class myTreeNode : public TreeNode + { + public: + System::String ^ FilePath; + + myTreeNode(System::String ^ fp) + { + FilePath = fp; + this->Text = fp->Substring(fp->LastIndexOf("\\")); + } + }; + ``` + +### To use a derived tree node + +1. You can use the new derived tree node as a parameter to function calls. + + In the example below, the path set for the location of the text file is the My Documents folder. This is done because you can assume that most computers running the Windows operating system will include this directory. This also allows users with minimal system access levels to safely run the application. + + ```vb + ' You should replace the bold text file + ' in the sample below with a text file of your own choosing. + TreeView1.Nodes.Add(New myTreeNode (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\ TextFile.txt ") ) + ``` + + ```csharp + // You should replace the bold text file + // in the sample below with a text file of your own choosing. + // Note the escape character used (@) when specifying the path. + treeView1.Nodes.Add(new myTreeNode(System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\TextFile.txt") ); + ``` + + ```cpp + // You should replace the bold text file + // in the sample below with a text file of your own choosing. + treeView1->Nodes->Add(new myTreeNode(String::Concat( + System::Environment::GetFolderPath + (System::Environment::SpecialFolder::Personal), + "\\TextFile.txt"))); + ``` + +2. If you are passed the tree node and it is typed as a class, then you will need to cast to your derived class. Casting is an explicit conversion from one type of object to another. For more information on casting, see [Implicit and Explicit Conversions](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/data-types/implicit-and-explicit-conversions) (Visual Basic), [Casting and type conversions](https://docs.microsoft.com/dotnet/csharp/programming-guide/types/casting-and-type-conversions) (Visual C#), or [Cast Operator: ()](/cpp/cpp/cast-operator-parens) (Visual C++). + + ```vb + Public Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect + Dim mynode As myTreeNode + mynode = CType(e.node, myTreeNode) + MessageBox.Show("Node selected is " & mynode.filepath) + End Sub + ``` + + ```csharp + protected void treeView1_AfterSelect (object sender, + System.Windows.Forms.TreeViewEventArgs e) + { + myTreeNode myNode = (myTreeNode)e.Node; + MessageBox.Show("Node selected is " + myNode.FilePath); + } + ``` + + ```cpp + private: + System::Void treeView1_AfterSelect(System::Object ^ sender, + System::Windows::Forms::TreeViewEventArgs ^ e) + { + myTreeNode ^ myNode = safe_cast(e->Node); + MessageBox::Show(String::Concat("Node selected is ", + myNode->FilePath)); + } + ``` + +## See also + +- [TreeView Control](treeview-control-windows-forms.md) +- [ListView Control](listview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-tables-and-columns-to-wf-datagrid-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/add-tables-and-columns-to-wf-datagrid-control-using-the-designer.md new file mode 100644 index 0000000000..ce85eb7827 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-tables-and-columns-to-wf-datagrid-control-using-the-designer.md @@ -0,0 +1,54 @@ +--- +title: Add Tables and Columns to DataGrid Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "columns [Windows Forms], adding to DataGrid control" + - "tables [Windows Forms], adding to DataGrid control" + - "DataGrid control [Windows Forms], adding tables and columns" +ms.assetid: 4a6d1b34-b696-476b-bf8a-57c6230aa9e1 +--- +# How to: Add Tables and Columns to the Windows Forms DataGrid Control Using the Designer + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + +You can display data in the Windows Forms control in tables and columns by creating objects and adding them to the object, which is accessed through the control's property. Each table style displays the contents of whatever data table is specified in the property of the . By default, a table style without column styles specified will display all the columns within that data table. You can restrict which columns from the table appear by adding objects to the , which is accessed through the property of each . + +The following procedures require a **Windows Application** project with a form that contains a control. For information about how to set up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). By default in Visual Studio 2005, the control is not in the **Toolbox**. For information about adding it, see [How to: Add Items to the Toolbox](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms165355(v=vs.100)). + +### To add a table to the DataGrid control in the designer + +1. In order to display data in the table, you must first bind the control to a dataset. For more information, see [How to: Bind the Windows Forms DataGrid Control to a Data Source Using the Designer](bind-wf-datagrid-control-to-a-data-source-using-the-designer.md). + +2. Select the control's property in the Properties window, and then click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property to display the **DataGridTableStyle Collection Editor**. + +3. In the collection editor, click **Add** to insert a table style. + +4. Click **OK** to close the collection editor, and then reopen it by clicking the ellipsis button next to the property. + + When you reopen the collection editor, any data tables bound to the control will appear in the drop-down list for the property of the table style. + +5. In the **Members** box of the collection editor, click the table style. + +6. In the **Properties** box of the collection editor, select the value for the table you want to display. + +### To add a column to the DataGrid control in the designer + +1. In the **Members** box of the **DataGridTableStyle Collection Editor**, select the appropriate table style. In the **Properties** box of the collection editor, select the collection, and then click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property to display the **DataGridColumnStyle Collection Editor**. + +2. In the collection editor, click **Add** to insert a column style or click the down arrow next to **Add** to specify a column type. + + In the drop-down box, you can select either the or type. + +3. Click OK to close the **DataGridColumnStyle Collection Editor**, and then reopen it by clicking the ellipsis button next to the property. + + When you reopen the collection editor, any data columns in the bound data table will appear in the drop-down list for the property of the column style. + +4. In the **Members** box of the collection editor, click the column style. + +5. In the **Properties** box of the collection editor, select the value for the column you want to display. + +## See also + +- [DataGrid Control](datagrid-control-windows-forms.md) +- [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/add-tooltips-to-individual-cells-in-a-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/add-tooltips-to-individual-cells-in-a-wf-datagridview-control.md new file mode 100644 index 0000000000..358a5c94c5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/add-tooltips-to-individual-cells-in-a-wf-datagridview-control.md @@ -0,0 +1,45 @@ +--- +title: Add ToolTips to Individual Cells in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "tooltips [Windows Forms], adding to data grids" + - "DataGridView control [Windows Forms], adding tooltips" + - "data grids [Windows Forms], adding tooltips" +ms.assetid: 2a81f9de-d58b-4ea8-bc0b-8d93c2f4cf78 +--- +# How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control +By default, ToolTips are used to display the values of cells that are too small to show their entire contents. You can override this behavior, however, to set ToolTip-text values for individual cells. This is useful to display to users additional information about a cell or to provide to users an alternate description of the cell contents. For example, if you have a row that displays status icons, you may want to provide text explanations using ToolTips. + + You can also disable the display of cell-level ToolTips by setting the property to `false`. + +### To add a ToolTip to a cell + +- Set the property. + + [!code-cpp[System.Windows.Forms.DataGridViewCell.ToolTipText#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/cpp/datagridviewcell.tooltiptext.cpp#1)] + [!code-csharp[System.Windows.Forms.DataGridViewCell.ToolTipText#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/CS/datagridviewcell.tooltiptext.cs#1)] + [!code-vb[System.Windows.Forms.DataGridViewCell.ToolTipText#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/VB/datagridviewcell.tooltiptext.vb#1)] + +## Compiling the Code + +- This example requires: + +- A control named `dataGridView1` that contains a column named `Rating` for displaying string values of one through four asterisk ("*") symbols. The event of the control must be associated with the event handler method shown in the example. + +- References to the and assemblies. + +## Robust Programming + When you bind the control to an external data source or provide your own data source by implementing virtual mode, you might encounter performance issues. To avoid a performance penalty when working with large amounts of data, handle the event rather than setting the property of multiple cells. When you handle this event, getting the value of a cell property raises the event and returns the value of the property as specified in the event handler. + +## See also + +- +- +- +- +- +- [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/app-icons-to-the-taskbar-with-wf-notifyicon.md b/dotnet-desktop-guide/framework/winforms/controls/app-icons-to-the-taskbar-with-wf-notifyicon.md new file mode 100644 index 0000000000..1eaa112174 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/app-icons-to-the-taskbar-with-wf-notifyicon.md @@ -0,0 +1,75 @@ +--- +title: Add Application Icons to the TaskBar with NotifyIcon Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "TrayIcon" +helpviewer_keywords: + - "status area icons" + - "icons [Windows Forms], adding to taskbar" + - "NotifyIcon component" + - "taskbar [Windows Forms], adding icons" +ms.assetid: d28c0fe6-aaf2-4df7-ad74-928d861a8510 +--- +# How to: Add Application Icons to the TaskBar with the Windows Forms NotifyIcon Component + +The Windows Forms component displays a single icon in the status notification area of the taskbar. To display multiple icons in the status area, you must have multiple components on your form. To set the icon displayed for a control, use the property. You can also write code in the event handler so that something happens when the user double-clicks the icon. For example, you could make a dialog box appear for the user to configure the background process represented by the icon. + +> [!NOTE] +> The component is used for notification purposes only, to alert users that an action or event has occurred or there has been a change in status of some sort. You should use menus, toolbars, and other user-interface elements for standard interaction with applications. + +### To set the icon + +1. Assign a value to the property. The value must be of type `System.Drawing.Icon` and can be loaded from an .ico file. You can specify the icon file in code or by clicking the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property in the **Properties** window, and then selecting the file in the **Open** dialog box that appears. + +2. Set the property to `true`. + +3. Set the property to an appropriate ToolTip string. + + In the following code example, the path set for the location of the icon is the **My Documents** folder. This location is used because you can assume that most computers running the Windows operating system will include this folder. Choosing this location also enables users with minimal system access levels to safely run the application. The following example requires a form with a control already added. It also requires an icon file named `Icon.ico`. + + ```vb + ' You should replace the bold icon in the sample below + ' with an icon of your own choosing. + NotifyIcon1.Icon = New _ + System.Drawing.Icon(System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Icon.ico") + NotifyIcon1.Visible = True + NotifyIcon1.Text = "Antivirus program" + ``` + + ```csharp + // You should replace the bold icon in the sample below + // with an icon of your own choosing. + // Note the escape character used (@) when specifying the path. + notifyIcon1.Icon = + new System.Drawing.Icon (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Icon.ico"); + notifyIcon1.Visible = true; + notifyIcon1.Text = "Antivirus program"; + ``` + + ```cpp + // You should replace the bold icon in the sample below + // with an icon of your own choosing. + notifyIcon1->Icon = gcnew + System::Drawing::Icon(String::Concat + (System::Environment::GetFolderPath + (System::Environment::SpecialFolder::Personal), + "\\Icon.ico")); + notifyIcon1->Visible = true; + notifyIcon1->Text = "Antivirus program"; + ``` + +## See also + +- +- +- [How to: Associate a Shortcut Menu with a Windows Forms NotifyIcon Component](how-to-associate-a-shortcut-menu-with-a-windows-forms-notifyicon-component.md) +- [NotifyIcon Component](notifyicon-component-windows-forms.md) +- [NotifyIcon Component Overview](notifyicon-component-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/attributes-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/attributes-in-windows-forms-controls.md new file mode 100644 index 0000000000..2ec1357057 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/attributes-in-windows-forms-controls.md @@ -0,0 +1,62 @@ +--- +title: Attributes in Controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "attributes [Windows Forms]" + - "attributes [Windows Forms], data binding properties" + - "attributes [Windows Forms], control properties" + - "attributes [Windows Forms], classes" +ms.assetid: 2c5640e9-6c6c-49d7-a5e4-a768f6be7853 +--- +# Attributes in Windows Forms Controls +The .NET Framework provides a variety of attributes you can apply to the members of your custom controls and components. Some of these attributes affect the run-time behavior of a class, and others affect the design-time behavior. + +## Attributes for Control and Component Properties + The following table shows the attributes you can apply to properties or other members of your custom controls and components. For an example that uses many of these attributes, see [How to: Apply Attributes in Windows Forms Controls](how-to-apply-attributes-in-windows-forms-controls.md). + +|Attribute|Description| +|---------------|-----------------| +||Specifies the value to pass to a property to cause the property to get its value from another source. This is known as *ambience*.| +||Specifies whether a property or event should be displayed in a **Properties** window.| +||Specifies the name of the category in which to group the property or event when displayed in a control set to mode.| +||Specifies the default value for a property.| +||Specifies a description for a property or event.| +||Specifies the display name for a property, event, or `public void` method that takes no arguments.| +||Specifies the editor to use to change a property.| +||Specifies that a property or method is viewable in an editor.| +||Specifies the context keyword for a class or member.| +||Specifies whether a property should be localized.| +||Indicates that an object's text representation is obscured by characters such as asterisks.| +||Specifies whether the property this attribute is bound to is read-only or read/write at design time.| +||Indicates that the property grid should refresh when the associated property value changes.| +||Specifies what type to use as a converter for the object this attribute is bound to.| + +## Attributes for Data Binding Properties + The following table shows the attributes you can apply to specify how your custom controls and components interact with data binding. + +|Attribute|Description| +|---------------|-----------------| +||Specifies whether a property is typically used for binding.| +||Specifies the data source and data member properties for a component.| +||Specifies the default binding property for a component.| +||Specifies the data source and data member properties for a component.| +||Enables attribute redirection.| + +## Attributes for Classes + The following table shows the attributes you can apply to specify the behavior of your custom controls and components at design time. + +|Attribute|Description| +|---------------|-----------------| +||Specifies the default event for a component.| +||Specifies the default property for a component.| +||Specifies the class used to implement design-time services for a component.| +||Specifies that the designer for a class belongs to a certain category.| +||Represents an attribute of a toolbox item.| +||Specifies the filter string and filter type to use for a Toolbox item.| + +## See also + +- +- [How to: Apply Attributes in Windows Forms Controls](how-to-apply-attributes-in-windows-forms-controls.md) +- [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)) +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/autogenerate-columns-in-a-data-bound-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/autogenerate-columns-in-a-data-bound-wf-datagridview-control.md new file mode 100644 index 0000000000..c5c5fd1427 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/autogenerate-columns-in-a-data-bound-wf-datagridview-control.md @@ -0,0 +1,36 @@ +--- +title: Autogenerate Columns in Data-Bound DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], autogenerating columns" + - "columns [Windows Forms], autogenerating" + - "DataGridView control [Windows Forms], data-bound columns" +ms.assetid: 699f6f9e-6aa5-4811-902b-6a2c57dec7d6 +--- +# How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control +The following code example demonstrates how to display columns from a bound data source in a control. When the property value is `true` (the default), a is created for each column in the data source table. + + If the control already has columns when you set the property, the existing bound columns are compared to the columns in the data source and preserved whenever there is a match. Unbound columns are always preserved. Bound columns for which there is no match in the data source are removed. Columns in the data source for which there is no match in the control generate new objects, which are added to the end of the collection. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#020](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#020)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#020](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#020)] + +## Compiling the Code + This example requires: + +- A control named `customersDataGridView`. + +- A object named `customersDataSet` that has a table named `Customers`. + +- References to the , , , and assemblies. + +## See also + +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control](remove-autogenerated-columns-from-a-wf-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/automatically-resize-cells-when-content-changes-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/automatically-resize-cells-when-content-changes-in-the-datagrid.md new file mode 100644 index 0000000000..7c9ae2c077 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/automatically-resize-cells-when-content-changes-in-the-datagrid.md @@ -0,0 +1,49 @@ +--- +title: Automatically Resize Cells When Content Changes in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data grids [Windows Forms], resizing cells automatically" + - "cells [Windows Forms], resizing automatically" + - "DataGridView control [Windows Forms], resizing cells" +ms.assetid: 1d68934d-a04c-4b12-9e66-c856c6828131 +--- +# How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control +You can configure the control to resize its rows, columns, and headers automatically whenever content changes, so that cells are always large enough to display their values without clipping. + + You have many options to restrict which cells are used to determine the new sizes. For example, you can configure the control to automatically resize the width of its columns based only on the values in rows that are currently displayed. With this, you can avoid inefficiency when working with large numbers of rows, although in this case, you might want to use sizing methods such as to adjust sizes at times of your choosing. + + For more information about automatic resizing, see [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md). + + The following code example demonstrates the options available for automatic resizing. + +## Example + [!code-cpp[System.Windows.Forms.DataGridView.AutoSizing#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CPP/autosizing.cpp#0)] + [!code-csharp[System.Windows.Forms.DataGridView.AutoSizing#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CS/autosizing.cs#0)] + [!code-vb[System.Windows.Forms.DataGridView.AutoSizing#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/VB/autosizing.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- +- [Resizing Columns and Rows in the Windows Forms DataGridView Control](resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md) +- [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md) +- [How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control](programmatically-resize-cells-to-fit-content-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/autosize-behavior-in-the-tablelayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/autosize-behavior-in-the-tablelayoutpanel-control.md new file mode 100644 index 0000000000..c3ae561ed1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/autosize-behavior-in-the-tablelayoutpanel-control.md @@ -0,0 +1,34 @@ +--- +title: "AutoSize Behavior in the TableLayoutPanel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "AutoSize property [Windows Forms], tableLayoutPanel control" + - "controls [Windows Forms], sizing" + - "localizing forms" + - "layout [Windows Forms], AutoSize" + - "sizing [Windows Forms], automatic" + - "TableLayoutPanel control [Windows Forms], AutoSize behavior" + - "automatic sizing" + - "AutoSizeMode property" +ms.assetid: 9233e0c3-2fa6-405e-8701-959479b1250e +--- +# AutoSize Behavior in the TableLayoutPanel Control +## Distinct AutoSize Behaviors + The control supports automatic sizing behavior in the following ways: + +- Through the property; + +- Through the property on the control’s column and row styles. + +### The AutoSize Property with Row and Column Styles + The following table describes the interaction between the property and the control’s column and row styles. + +|AutoSize setting|Style interaction| +|----------------------|-----------------------| +|`false`|The control proceeds from left to right, and allocates space for the column or row or in the following order.

1. If the property is set to , the number of pixels specified by or is allocated.
2. If the property is set to , the number of pixels returned by the child control’s method is allocated.
3. After space for all and columns or rows is allocated, any columns or rows with set to are used to proportionally allocate the remaining free space| +|`true`|Similar to the previous interaction, with the exception that columns or rows acquire an automatic sizing aspect.

The control expands the column or row to create adequate free space, so that no column or row with styling clips its contents. The control allocates the new space proportionally according to the or property.| + +## See also + +- +- [TableLayoutPanel Control Overview](tablelayoutpanel-control-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/autosize-property-overview.md b/dotnet-desktop-guide/framework/winforms/controls/autosize-property-overview.md new file mode 100644 index 0000000000..31611ccb1b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/autosize-property-overview.md @@ -0,0 +1,67 @@ +--- +title: "AutoSize Property Overview" +ms.date: "03/30/2017" +helpviewer_keywords: + - "sizing [Windows Forms], automatic" + - "layout [Windows Forms], AutoSize" + - "automatic sizing" + - "AutoSizeMode property" +ms.assetid: 62fd82a2-9565-4f65-925b-9d1e66dc4e7d +--- +# AutoSize Property Overview +The property enables a control to change its size, if necessary, to attain the value specified by the property. You adjust the sizing behavior for specific controls by setting the `AutoSizeMode` property. + +## AutoSize Behavior + Only some controls support the property. In addition, some controls that support the property also support the `AutoSizeMode` property. + + The property produces somewhat different behavior, depending on the specific control type and the value of the `AutoSizeMode` property, if the property exists. The following table describes the behaviors that are always true and provides a brief description of each: + +|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.

**Note** 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 0,0. 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.| + +## AutoSizeMode Property + The `AutoSizeMode` property provides more fine-grained control over the default behavior. The `AutoSizeMode` property specifies how a control sizes itself to its content. The content, for example, could be the text for a control or the child controls for a container. + + The following table shows the settings and a description of the behavior each setting elicits. + +|AutoSizeMode setting|Behavior| +|--------------------------|--------------| +|GrowAndShrink|The control grows or shrinks to encompass its contents.

The and values are honored, but the current value of the property is ignored.

This is the same behavior as controls with the property and no `AutoSizeMode` property.| +|GrowOnly|The control grows as much as necessary to encompass its contents, but it will not shrink smaller than the value specified by its property.

This is the default value for `AutoSizeMode`.| + +## Controls That Support the AutoSize Property + The following table lists the controls that support the and `AutoSizeMode` properties. + +|AutoSize support|Control type| +|----------------------|------------------| +|- property supported.
- No `AutoSizeMode` property.|







( base)







| +|- property supported.
- `AutoSizeMode` property supported.|











| +|- No property.|































| + +## AutoSize in the Design Environment + The following table describes the sizing behavior of a control at design time, based on the value of its and `AutoSizeMode` properties. + + Override the property to determine whether a given control is in a user-resizable state. In the following table, "cannot" means only, "can" means and . + +|AutoSize settings|Design-time sizing gesture| +|-----------------------|---------------------------------| +|- = `true`
- No `AutoSizeMode` property.|The user cannot resize the control at design time, except for the following controls:

-
-
-
- | +|- = `true`
- `AutoSizeMode` = |The user cannot resize the control at design time.| +|- = `true`
- `AutoSizeMode` = |The user can resize the control at design time. When the property is set, the user can only increase the size of the control.| +|- = `false`, or property is hidden.|User can resize the control at design time.| + +> [!NOTE] +> To maximize productivity, the Windows Forms Designer in Visual Studio shadows the property for the class. At design time, the form behaves as though the property is set to `false`, regardless of its actual setting. At runtime, no special accommodation is made, and the property is applied as specified by the property setting. + +## See also + +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/backgroundworker-component-overview.md b/dotnet-desktop-guide/framework/winforms/controls/backgroundworker-component-overview.md new file mode 100644 index 0000000000..e9a72d637d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/backgroundworker-component-overview.md @@ -0,0 +1,61 @@ +--- +title: "BackgroundWorker Component Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "BackgroundWorker" +helpviewer_keywords: + - "BackgroundWorker component" + - "background tasks" + - "Asynchronous Pattern" + - "forms [Windows Forms], multithreading" + - "components [Windows Forms], asynchronous" + - "forms [Windows Forms], background operations" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: 64e9b3ab-7443-4a77-ab17-b8b8c0cb3f62 +--- +# BackgroundWorker Component Overview +There are many commonly performed operations that can take a long time to execute. For example: + +- Image downloads + +- Web service invocations + +- File downloads and uploads (including for peer-to-peer applications) + +- Complex local computations + +- Database transactions + +- Local disk access, given its slow speed relative to memory access + + Operations like these can cause your user interface to block while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the component provides a convenient solution. + + The component gives you the ability to execute time-consuming operations asynchronously ("in the background"), on a thread different from your application's main UI thread. To use a , you simply tell it what time-consuming worker method to execute in the background, and then you call the method. Your calling thread continues to run normally while the worker method runs asynchronously. When the method is finished, the alerts the calling thread by firing the event, which optionally contains the results of the operation. + + The component is available from the **Toolbox**, in the **Components** tab. To add a to your form, drag the component onto your form. It appears in the component tray, and its properties appear in the **Properties** window. + + To start your asynchronous operation, use the method. takes an optional `object` parameter, which can be used to pass arguments to your worker method. The class exposes the event, to which your worker thread is attached through a event handler. + + The event handler takes a parameter, which has an property. This property receives the parameter from and can be passed to your worker method, which will be called in the event handler. The following example shows how to assign a result from a worker method called `ComputeFibonacci`. It is part of a larger example, which you can find at [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md). + + [!code-cpp[System.ComponentModel.BackgroundWorker#5](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#5)] + [!code-csharp[System.ComponentModel.BackgroundWorker#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#5)] + [!code-vb[System.ComponentModel.BackgroundWorker#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#5)] + + For more information on using event handlers, see [Events](https://docs.microsoft.com/dotnet/standard/events/index). + +> [!CAUTION] +> When using multithreading of any sort, you potentially expose yourself to very serious and complex bugs. Consult the [Managed Threading Best Practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) before implementing any solution that uses multithreading. + + For more information on using the class, see [How to: Run an Operation in the Background](how-to-run-an-operation-in-the-background.md). + +## See also + +- [Managed Threading](https://docs.microsoft.com/dotnet/standard/threading/index) +- [Event-based Asynchronous Pattern Overview](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview) +- [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/backgroundworker-component.md b/dotnet-desktop-guide/framework/winforms/controls/backgroundworker-component.md new file mode 100644 index 0000000000..31c2f14e42 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/backgroundworker-component.md @@ -0,0 +1,49 @@ +--- +title: "BackgroundWorker Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "BackgroundWorker component" + - "background tasks" + - "Asynchronous Pattern" + - "forms [Windows Forms], multithreading" + - "components [Windows Forms], asynchronous" + - "forms [Windows Forms], background operations" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: bef7b0ab-ce57-475a-a2d6-fb8a702a9417 +--- +# BackgroundWorker Component +The `BackgroundWorker` component enables your form or control to run an operation asynchronously. + +## In This Section + [BackgroundWorker Component Overview](backgroundworker-component-overview.md) + Describes the `BackgroundWorker` component, which gives you the ability to execute time-consuming operations asynchronously ("in the background"), on a thread different from your application's main UI thread. + + [Walkthrough: Running an Operation in the Background](walkthrough-running-an-operation-in-the-background.md) + Demonstrates how to use the `BackgroundWorker` component in the designer to run a time-consuming operation on a separate thread. + + [How to: Run an Operation in the Background](how-to-run-an-operation-in-the-background.md) + Demonstrates how to use the `BackgroundWorker` component to run a time-consuming operation on a separate thread. + + [Walkthrough: Implementing a Form That Uses a Background Operation](walkthrough-implementing-a-form-that-uses-a-background-operation.md) + Creates an application using the designer that does mathematical computations asynchronously. + + [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md) + Creates an application that does mathematical computations asynchronously. + + [How to: Download a File in the Background](how-to-download-a-file-in-the-background.md) + Demonstrates how to use the `BackgroundWorker` component to download a file on a separate thread. + +## Reference + + Describes this class and has links to all its members. + + + Describes the type that holds data for the event. + + + Describes the type that holds data for the event. + +## Related Sections + [Event-based Asynchronous Pattern Overview](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview) + Describes how the asynchronous pattern makes available the advantages of multithreaded applications while hiding many of the complex issues inherent in multithreaded design. diff --git a/dotnet-desktop-guide/framework/winforms/controls/basic-column-row-and-cell-features-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/basic-column-row-and-cell-features-wf-datagridview-control.md new file mode 100644 index 0000000000..7e73c5fa27 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/basic-column-row-and-cell-features-wf-datagridview-control.md @@ -0,0 +1,53 @@ +--- +title: Basic Column, Row, and Cell Features in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], basic features" + - "columns [Windows Forms], DataGridView control" + - "data grids [Windows Forms], examples" + - "DataGridView control [Windows Forms], examples" +ms.assetid: 78085f26-d5d2-4b75-813e-e932b72fd06f +--- +# Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control +Many basic behaviors of `DataGridView` cells, rows, and columns can be modified by setting single properties. The topics in this section describe several of the most commonly used of these features. + +## In This Section + [How to: Hide Columns in the Windows Forms DataGridView Control](how-to-hide-columns-in-the-windows-forms-datagridview-control.md) + Describes how to prevent specific columns from appearing in the control. + + [How to: Hide Column Headers in the Windows Forms DataGridView Control](how-to-hide-column-headers-in-the-windows-forms-datagridview-control.md) + Describes how to prevent the column headers from appearing in the control. + + [How to: Enable Column Reordering in the Windows Forms DataGridView Control](how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md) + Describes how to enable users to rearrange columns in the control. + + [How to: Freeze Columns in the Windows Forms DataGridView Control](how-to-freeze-columns-in-the-windows-forms-datagridview-control.md) + Describes how prevent one or more adjacent columns from scrolling. + + [How to: Make Columns Read-Only in the Windows Forms DataGridView Control](how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md) + Describes how to prevent users from editing specific columns in the control. + + [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md) + Describes how to remove the row for new records at the bottom of the control to prevent users from adding rows. Also describes how to prevent users from deleting rows. + + [How to: Get and Set the Current Cell in the Windows Forms DataGridView Control](get-and-set-the-current-cell-wf-datagridview-control.md) + Describes how to access the cell that currently has focus in the control. + + [How to: Display Images in Cells of the Windows Forms DataGridView Control](how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md) + Describes how to create an image column that displays an icon in every cell. + +## Reference + + Provides reference documentation for the control. + +## Related Sections + [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to modify the basic appearance of the control and the display formatting of cell data. + + [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) + Provides topics that describe how to program with cell, row, and column objects. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..df0d2ba7be --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,56 @@ +--- +title: Basic Formatting and Styling in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], formatting and styling" + - "data grids [Windows Forms], formatting" +ms.assetid: b9b90836-1f56-4aa9-8db8-edc78fe830e8 +--- +# Basic Formatting and Styling in the Windows Forms DataGridView Control +The `DataGridView` control makes it easy to define the basic appearance of cells and the display formatting of cell values. You can define appearance and formatting styles for individual cells, for cells in specific columns and rows, or for all cells in the control by setting the properties of the `DataGridViewCellStyle` objects accessed through various `DataGridView` control properties. Additionally, you can modify these styles dynamically based on factors such as the cell value by handling the `CellFormatting` event. + +## In This Section + [How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control](change-the-border-and-gridline-styles-in-the-datagrid.md) + Describes how to set `DataGridView` properties that define the appearance of the control border and the boundary lines between cells. + + [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) + Describes the `DataGridViewCellStyle` class and how properties of that type interact to define how cells are displayed in the control. + + [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md) + Describes how to use `DataGridViewCellStyle` properties to define the default appearance of cells in specific rows and columns and in the entire control. + + [How to: Format Data in the Windows Forms DataGridView Control](how-to-format-data-in-the-windows-forms-datagridview-control.md) + Describes how to format cell display values using `DataGridViewCellStyle` properties. + + [How to: Set Font and Color Styles in the Windows Forms DataGridView Control](how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md) + Describes how to use the `DefaultCellStyle` property to set basic display characteristics for all cells in the control. + + [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control](how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md) + Describes how to create a ledger-like effect in the control using alternating rows that are displayed differently. + + [How to: Use the Row Template to Customize Rows in the Windows Forms DataGridView Control](use-the-row-template-to-customize-rows-in-the-datagrid.md) + Describes how to use the `RowTemplate` property to set row properties that will be used for all rows in the control. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the class. + + + Provides reference documentation for the event. + + + Provides reference documentation for the property. + +## Related Sections + [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) + Provides topics that describe custom painting cells and rows, and creating derived cell, column, and row types. + + [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) + Provides topics that describe commonly used cell, row, and column properties. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/best-practices-for-scaling-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/best-practices-for-scaling-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..6635236fb0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/best-practices-for-scaling-the-windows-forms-datagridview-control.md @@ -0,0 +1,147 @@ +--- +title: Best Practices for Scaling DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], row sharing" + - "data grids [Windows Forms], best practices" + - "DataGridView control [Windows Forms], shared rows" + - "DataGridView control [Windows Forms], best practices" + - "best practices [Windows Forms], dataGridView control" + - "DataGridView control [Windows Forms], scaling" +ms.assetid: 8321a8a6-6340-4fd1-b475-fa090b905aaf +--- +# Best Practices for Scaling the Windows Forms DataGridView Control + +The control is designed to provide maximum scalability. If you need to display large amounts of data, you should follow the guidelines described in this topic to avoid consuming large amounts of memory or degrading the responsiveness of the user interface (UI). This topic discusses the following issues: + +- Using cell styles efficiently + +- Using shortcut menus efficiently + +- Using automatic resizing efficiently + +- Using the selected cells, rows, and columns collections efficiently + +- Using shared rows + +- Preventing rows from becoming unshared + +If you have special performance needs, you can implement virtual mode and provide your own data management operations. For more information, see [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md). + +## Using Cell Styles Efficiently + +Each cell, row, and column can have its own style information. Style information is stored in objects. Creating cell style objects for many individual elements can be inefficient, especially when working with large amounts of data. To avoid a performance impact, use the following guidelines: + +- Avoid setting cell style properties for individual or objects. This includes the row object specified by the property. Each new row that is cloned from the row template will receive its own copy of the template's cell style object. For maximum scalability, set cell style properties at the level. For example, set the property rather than the property. + +- If some cells require formatting other than default formatting, use the same instance across groups of cells, rows, or columns. Avoid directly setting properties of type on individual cells, rows, and columns. For an example of cell style sharing, see [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md). You can also avoid a performance penalty when setting cell styles individually by handling the event handler. For an example, see [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md). + +- When determining a cell's style, use the property rather than the property. Accessing the property creates a new instance of the class if the property has not already been used. Additionally, this object might not contain the complete style information for the cell if some styles are inherited from the row, column, or control. For more information about cell style inheritance, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + +## Using Shortcut Menus Efficiently + +Each cell, row, and column can have its own shortcut menu. Shortcut menus in the control are represented by controls. Just as with cell style objects, creating shortcut menus for many individual elements will negatively impact performance. To avoid this penalty, use the following guidelines: + +- Avoid creating shortcut menus for individual cells and rows. This includes the row template, which is cloned along with its shortcut menu when new rows are added to the control. For maximum scalability, use only the control's property to specify a single shortcut menu for the entire control. + +- If you require multiple shortcut menus for multiple rows or cells, handle the or events. These events let you manage the shortcut menu objects yourself, allowing you to tune performance. + +## Using Automatic Resizing Efficiently + +Rows, columns, and headers can be automatically resized as cell content changes so that the entire contents of cells are displayed without clipping. Changing sizing modes can also resize rows, columns, and headers. To determine the correct size, the control must examine the value of each cell that it must accommodate. When working with large data sets, this analysis can negatively impact the performance of the control when automatic resizing occurs. To avoid performance penalties, use the following guidelines: + +- Avoid using automatic sizing on a control with a large set of rows. If you do use automatic sizing, only resize based on the displayed rows. Use only the displayed rows in virtual mode as well. + + - For rows and columns, use the `DisplayedCells` or `DisplayedCellsExceptHeaders` field of the , , and enumerations. + + - For row headers, use the or field of the enumeration. + +- For maximum scalability, turn off automatic sizing and use programmatic resizing. + +For more information, see [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md). + +## Using the Selected Cells, Rows, and Columns Collections Efficiently + +The collection does not perform efficiently with large selections. The and collections can also be inefficient, although to a lesser degree because there are many fewer rows than cells in a typical control, and many fewer columns than rows. To avoid performance penalties when working with these collections, use the following guidelines: + +- To determine whether all the cells in the have been selected before you access the contents of the collection, check the return value of the method. Note, however, that this method can cause rows to become unshared. For more information, see the next section. + +- Avoid using the property of the to determine the number of selected cells. Instead, use the method and pass in the value. Similarly, use the and methods to determine the number of selected elements, rather than accessing the selected row and column collections. + +- Avoid cell-based selection modes. Instead, set the property to or . + +## Using Shared Rows + +Efficient memory use is achieved in the control through shared rows. Rows will share as much information about their appearance and behavior as possible by sharing instances of the class. + +While sharing row instances saves memory, rows can easily become unshared. For example, whenever a user interacts directly with a cell, its row becomes unshared. Because this cannot be avoided, the guidelines in this topic are useful only when working with very large amounts of data and only when users will interact with a relatively small part of the data each time your program is run. + +A row cannot be shared in an unbound control if any of its cells contain values. When the control is bound to an external data source or when you implement virtual mode and provide your own data source, the cell values are stored outside the control rather than in cell objects, allowing the rows to be shared. + +A row object can only be shared if the state of all its cells can be determined from the state of the row and the states of the columns containing the cells. If you change the state of a cell so that it can no longer be deduced from the state of its row and column, the row cannot be shared. + +For example, a row cannot be shared in any of the following situations: + +- The row contains a single selected cell that is not in a selected column. + +- The row contains a cell with its or properties set. + +- The row contains a with its property set. + +In bound mode or virtual mode, you can provide ToolTips and shortcut menus for individual cells by handling the and events. + +The control will automatically attempt to use shared rows whenever rows are added to the . Use the following guidelines to ensure that rows are shared: + +- Avoid calling the `Add(Object[])` overload of the method and the `Insert(Object[])` overload of the method of the collection. These overloads automatically create unshared rows. + +- Be sure that the row specified in the property can be shared in the following cases: + + - When calling the `Add()` or `Add(Int32)` overloads of the method or the `Insert(Int32,Int32)` overload of the method of the collection. + + - When increasing the value of the property. + + - When setting the property. + +- Be sure that the row indicated by the `indexSource` parameter can be shared when calling the , , , and methods of the collection. + +- Be sure that the specified row or rows can be shared when calling the `Add(DataGridViewRow)` overload of the method, the method, the `Insert(Int32,DataGridViewRow)` overload of the method, and the method of the collection. + +To determine whether a row is shared, use the method to retrieve the row object, and then check the object's property. Shared rows always have an property value of –1. + +## Preventing Rows from Becoming Unshared + +Shared rows can become unshared as a result of code or user action. To avoid a performance impact, you should avoid causing rows to become unshared. During application development, you can handle the event to determine when rows become unshared. This is useful when debugging row-sharing problems. + +To prevent rows from becoming unshared, use the following guidelines: + +- Avoid indexing the collection or iterating through it with a `foreach` loop. You will not typically need to access rows directly. methods that operate on rows take row index arguments rather than row instances. Additionally, handlers for row-related events receive event argument objects with row properties that you can use to manipulate rows without causing them to become unshared. + +- If you need to access a row object, use the method and pass in the row's actual index. Note, however, that modifying a shared row object retrieved through this method will modify all the rows that share this object. The row for new records is not shared with other rows, however, so it will not be affected when you modify any other row. Note also that different rows represented by a shared row may have different shortcut menus. To retrieve the correct shortcut menu from a shared row instance, use the method and pass in the row's actual index. If you access the shared row's property instead, it will use the shared row index of -1 and will not retrieve the correct shortcut menu. + +- Avoid indexing the collection. Accessing a cell directly will cause its parent row to become unshared, instantiating a new . Handlers for cell-related events receive event argument objects with cell properties that you can use to manipulate cells without causing rows to become unshared. You can also use the property to retrieve the row and column indexes of the current cell without accessing the cell directly. + +- Avoid cell-based selection modes. These modes cause rows to become unshared. Instead, set the property to or . + +- Do not handle the or events. These events cause rows to become unshared. Also, do not call the or methods, which raise these events. + +- Do not access the collection when the property value is , , , or . This causes all selected rows to become unshared. + +- Do not call the method. This method can cause rows to become unshared. + +- Do not call the method when the property value is . This causes all rows to become unshared. + +- Do not set the or property of a cell to `false` when the corresponding property in its column is set to `true`. This causes all rows to become unshared. + +- Do not access the property. This causes all rows to become unshared. + +- Do not call the `Sort(IComparer)` overload of the method. Sorting with a custom comparer causes all rows to become unshared. + +## See also + +- +- [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) +- [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md) +- [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md) +- [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/best-practices-for-the-tablelayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/best-practices-for-the-tablelayoutpanel-control.md new file mode 100644 index 0000000000..c111eb5ce5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/best-practices-for-the-tablelayoutpanel-control.md @@ -0,0 +1,55 @@ +--- +title: "Best Practices for the TableLayoutPanel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "layout [Windows Forms]" + - "TableLayoutPanel control [Windows Forms], best practices" + - "forms [Windows Forms], best practices" + - "AutoSize property [Windows Forms], tableLayoutPanel control" + - "controls [Windows Forms], sizing" + - "TableLayoutPanel control [Windows Forms], AutoSize behavior" + - "layout [Windows Forms], AutoSize" + - "layout [Windows Forms], best practices" + - "best practices [Windows Forms], tableLayoutPanel control" + - "sizing [Windows Forms], automatic" + - "automatic sizing" +ms.assetid: b6706efb-d7a4-45ec-8cf4-08fa993e3afb +--- +# Best Practices for the TableLayoutPanel Control +The control provides powerful layout features that you should consider carefully before using on your Windows Forms. + +## Recommendations + The following recommendations will help you use the control to its best advantage. + +### Targeted Use + Use the control sparingly. You should not use it in all situations that require a resizable layout. The following list describes layouts that benefit most from the use of the control: + +- Layouts in which there are multiple parts of the form that resize proportionally to each other. + +- Layouts that will be modified or generated dynamically at run time, such as data entry forms that have user-customizable fields added or subtracted based on preferences. + +- Layouts that should remain at an overall fixed size. For example, you may have a dialog box that should remain smaller than 800 x 600, but you need to support localized strings. + + The following list describes layouts that do not benefit greatly from using the control: + +- Simple data entry forms with a single column of labels and a single column of text-entry areas. + +- Forms with a single large display area that should fill all the available space when a resize occurs. An example of this is a form that displays a single control. In this case, use anchoring, because nothing else should expand when the form is resized. + + Choose carefully which controls need to be in a control. If you have room for your text to grow by 30% using anchoring, consider using the property only. If you can estimate the space required by your layout, use of and is easier than estimating the details of remaining space and behavior. + + In general, when designing your layout with the control, keep the design as simple as possible. + +### Use the Document Outline Window + The Document Outline window gives you a tree view of your layout, which you can use to manipulate the z-order and parent-child relationships of your controls. From the **View menu**, select **Other Windows**, then select **Document Outline**. + +### Avoid Nesting + Avoid nesting other controls within a control. Debugging nested layouts can be difficult. + +### Avoid Visual Inheritance + The control does not support visual inheritance in the Windows Forms Designer in Visual Studio. A control in a derived class appears as "locked" at design time. + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/bind-data-to-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/bind-data-to-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..2d3049e250 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bind-data-to-the-datagrid-using-the-designer.md @@ -0,0 +1,54 @@ +--- +title: Bind Data to DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, binding to a data source" + - "data sources [Windows Forms], binding to Windows Forms controls" + - "DataGridView control [Windows Forms], data binding" +ms.assetid: f4f46009-cec2-441b-8668-6b5af057558b +--- +# How to: Bind Data to the Windows Forms DataGridView Control Using the Designer +You can use the designer to connect a control to data sources of several different varieties, including databases, business objects, or Web services. When you bind the control to a data source using the designer, the control is automatically bound to a component that represents the data source. Additionally, columns are automatically generated in the control to match the schema information provided by the data source. + + After columns have been generated, you can modify them to meet your needs. For example, you can remove or hide columns you are not interested in displaying, you can rearrange the columns, or you can modify the column types. For more information about modifying columns, see the topics listed in the See Also section. + + You can also bind multiple controls to related tables to create master/detail relationships. In this configuration, one control displays a parent table and another control displays only those rows from a child table that are related to the current row in the parent table. For more information, see [How to: Display Related Data in a Windows Forms Application](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/57tx3hhe(v=vs.120)). + + The following procedure requires a **Windows Application** project with a form that contains a control or two controls for a master/detail relationship. For information about starting such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To bind the control to a data source + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control. + +2. Click the drop-down arrow for the **Choose Data Source** option. + +3. If your project does not already have a data source, click **Add Project Data Source** and follow the steps indicated by the wizard. + + For more information, see [Data Source Configuration Wizard](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/w4dd7z6t(v=vs.120)). Your new data source will appear in the **Choose Data Source** drop-down window. If your new data source contains only one member, such as a single database table, the control will automatically bind to that member. Otherwise, continue to the next step. + +4. Expand the **Other Data Sources** and **Project Data Sources** nodes if they are not already expanded, and then select the data source to bind the control to. + +5. If your data source contains more than one member, such as if you have created a that contains multiple tables, expand the data source, and then select the specific member to bind to. + +6. To create a master/detail relationship, in the **Choose Data Source** drop-down window for a second control, expand the created for the parent table, and then select the related child table from the list shown. + + > [!NOTE] + > If your project already has a data source, you can also use the **Data Sources** window to create a data form. For more information, see [Data Sources Window](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/6ckyxa83(v=vs.120)). + +## See also + +- +- +- +- +- [How to: Connect to Data in a Database](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/fxk9yw1t(v=vs.120)) +- [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md) +- [How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer](change-the-order-of-columns-in-the-datagrid-using-the-designer.md) +- [How to: Change the Type of a Windows Forms DataGridView Column Using the Designer](change-the-type-of-a-wf-datagridview-column-using-the-designer.md) +- [How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer](freeze-columns-in-the-datagrid-using-the-designer.md) +- [How to: Hide Columns in the Windows Forms DataGridView Control Using the Designer](hide-columns-in-the-datagrid-using-the-designer.md) +- [How to: Make Columns Read-Only in the Windows Forms DataGridView Control Using the Designer](make-columns-read-only-in-the-datagrid-using-the-designer.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) +- [Data Sources Window](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/6ckyxa83(v=vs.120)) +- [How to: Display Related Data in a Windows Forms Application](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/57tx3hhe(v=vs.120)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bind-wf-controls-with-the-bindingsource.md b/dotnet-desktop-guide/framework/winforms/controls/bind-wf-controls-with-the-bindingsource.md new file mode 100644 index 0000000000..c026907593 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bind-wf-controls-with-the-bindingsource.md @@ -0,0 +1,58 @@ +--- +title: Bind Controls with the BindingSource Component Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], binding" + - "BindingSource component [Windows Forms], binding controls" + - "data binding [Windows Forms], BindingSource component" +ms.assetid: 391ae170-de5c-40f8-8233-91cb2ee4683a +--- +# How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer +After you have added controls to your form and determined the user interface for your application, you can bind the controls to a data source, so that, at run time, users can alter and save data related to the application. + + Binding a control or series of controls in Windows Forms is most easily accomplished using the control as a bridge between the controls on the form and the data source. + + One or more controls on a form can be bound to data; in the following procedure, a control is bound to a data source. + + To complete the procedure, it is assumed that you will bind to a data source derived from a database. For more information on creating data sources from other stores of data, see [Add new data sources](/visualstudio/data-tools/add-new-data-sources). + +## To bind a control at design time + +1. Drag a control on to the form. + +2. In the **Properties** window: + + 1. Expand the **(DataBindings)** node. + + 2. Click the arrow next to the property. + + The **DataSource** UI type editor opens. + + If a data source has previously been configured for the project or form, it will appear. + +3. Click **Add Project Data Source** to connect to data and create a data source. + +4. On the **Data Source Configuration Wizard** welcome page, click **Next**. + +5. On the **Choose a Data Source Type** page, select **Database**. + +6. On the **Choose Your Data Connection** page, select a data connection from the list of available connections. If your desired data connection is not available select **New Connection** to create a new data connection. + +7. Select **Yes, save the connection** to save the connection string in the application configuration file. + +8. Select the database objects to bring into your application. In this case, select a field in a table that you would like the to display. + +9. Replace the default dataset name if you want. + +10. Click **Finish**. + +11. In the **Properties** window, click the arrow next to the property again. In the **DataSource** UI type editor, select the name of the field to bind the to. + + The **DataSource** UI type editor closes and the data set, and table adapter specific to that data connection are added to your form. + +## See also + +- +- +- [Add new data sources](/visualstudio/data-tools/add-new-data-sources) +- [Data Sources Window](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/6ckyxa83(v=vs.120)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bind-wf-datagrid-control-to-a-data-source-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/bind-wf-datagrid-control-to-a-data-source-using-the-designer.md new file mode 100644 index 0000000000..8b48542611 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bind-wf-datagrid-control-to-a-data-source-using-the-designer.md @@ -0,0 +1,69 @@ +--- +title: Bind DataGrid Control to a Data Source Using the Designer +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "datasets [Windows Forms], binding to DataGrid control" + - "data binding [Windows Forms], DataGrid control" + - "DataGrid control [Windows Forms], data binding" + - "Windows Forms controls, data binding" + - "bound controls [Windows Forms]" +ms.assetid: 4e96e3d0-b1cc-4de1-8774-bc9970ec4554 +--- +# How to: Bind the Windows Forms DataGrid Control to a Data Source Using the Designer + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + The Windows Forms control is specifically designed to display information from a data source. You bind the control at design time by setting the and properties, or at run time by calling the method. Although you can display data from a variety of data sources, the most typical sources are datasets and data views. + + If the data source is available at design time—for example, if the form contains an instance of a dataset or a data view—you can bind the grid to the data source at design time. You can then preview what the data will look like in the grid. + + You can also bind the grid programmatically, at run time. This is useful when you want to set a data source based on information you get at run time. For example, the application might let the user specify the name of a table to view. It is also necessary in situations where the data source does not exist at design time. This includes data sources such as arrays, collections, untyped datasets, and data readers. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). In Visual Studio 2005, the control is not in the **Toolbox** by default. For information about adding it, see [How to: Add Items to the Toolbox](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms165355(v=vs.100)). Additionally in Visual Studio 2005, you can use the **Data Sources** window for design-time data binding. For more information see [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio). + +## To data-bind the DataGrid control to a single table in the designer + +1. Set the control's property to the object containing the data items you want to bind to. + +2. If the data source is a dataset, set the property to the name of the table to bind to. + +3. If the data source is a dataset or a data view based on a dataset table, add code to the form to fill the dataset. + + The exact code you use depends on where the dataset is getting data. If the dataset is being populated directly from a database, you typically call the `Fill` method of a data adapter, as in the following code example, which populates a dataset called `DsCategories1`: + + ```vb + sqlDataAdapter1.Fill(DsCategories1) + ``` + + ```csharp + sqlDataAdapter1.Fill(DsCategories1); + ``` + + ```cpp + sqlDataAdapter1->Fill(dsCategories1); + ``` + +4. (Optional) Add the appropriate table styles and column styles to the grid. + + If there are no table styles, you will see the table, but with minimal formatting and with all columns visible. + +## To data-bind the DataGrid control to multiple tables in a dataset in the designer + +1. Set the control's property to the object containing the data items you want to bind to. + +2. If the dataset contains related tables (that is, if it contains a relation object), set the property to the name of the parent table. + +3. Write code to fill the dataset. + +## See also + +- [DataGrid Control Overview](datagrid-control-overview-windows-forms.md) +- [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) +- [DataGrid Control](datagrid-control-windows-forms.md) +- [Windows Forms Data Binding](../windows-forms-data-binding.md) +- [Accessing data in Visual Studio](/visualstudio/data-tools/accessing-data-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bindingnavigator-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/bindingnavigator-control-overview-windows-forms.md new file mode 100644 index 0000000000..13977b69ba --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bindingnavigator-control-overview-windows-forms.md @@ -0,0 +1,43 @@ +--- +title: "BindingNavigator Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "DataNavigator" +helpviewer_keywords: + - "BindingNavigator control [Windows Forms], about BindingNavigator control" + - "records [Windows Forms], navigating on a form" + - "data [Windows Forms], navigating" + - "data navigation" +ms.assetid: 4423eede-f8d1-4d02-822f-5bf8432680d0 +--- +# BindingNavigator Control Overview (Windows Forms) +You can use the control to create a standardized means for users to search and change data on a Windows Form. You frequently use with the component to enable users to move through data records on a form and interact with the records. + +## How the BindingNavigator Works + + The control is composed of a with a series of objects for most of the common data-related actions: adding data, deleting data, and navigating through data. By default, the control contains these standard buttons. The following screenshot shows the control on a form: + + ![Screenshot showing the BindingNavigator control.](./media/bindingnavigator-control-overview-windows-forms/bindingnavigator-control-form.gif) + + The following table lists the controls and describes their functions. + +|Control|Function| +|-------------|--------------| +| button|Inserts a new row into the underlying data source.| +| button|Deletes the current row from the underlying data source.| +| button|Moves to the first item in the underlying data source.| +| button|Moves to the last item in the underlying data source.| +| button|Moves to the next item in the underlying data source.| +| button|Moves to the previous item in the underlying data source.| +| text box|Returns the current position within the underlying data source.| +| text box|Returns the total number of items in the underlying data source.| + + For each control in this collection, there is a corresponding member of the component that programmatically provides the same functionality. For example, the button corresponds to the method of the component, the button corresponds to the method, and so on. + + If the default buttons are not suited to your application, or if you require additional buttons to support other types of functionality, you can supply your own buttons. Also see [How to: Add Load, Save, and Cancel Buttons to the Windows Forms BindingNavigator Control](load-save-and-cancel-bindingnavigator.md). + +## See also + +- +- +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bindingnavigator-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/bindingnavigator-control-windows-forms.md new file mode 100644 index 0000000000..fb4522cace --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bindingnavigator-control-windows-forms.md @@ -0,0 +1,35 @@ +--- +title: "BindingNavigator Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "BindingNavigator control [Windows Forms]" + - "data [Windows Forms], navigating" + - "data navigation" +ms.assetid: 18c1e2a5-9834-40d3-9b2e-2b545e4e769e +--- +# BindingNavigator Control (Windows Forms) +The `BindingNavigator` control is the navigation and manipulation user interface (UI) for controls that are bound to data. The `BindingNavigator` control enables users to navigate through and manipulate data on a Windows Form. + + The topics in this section provide an overview of the `BindingNavigator` control and offer step-by-step instructions how to use the control navigate data and move through a . + +## In This Section + [BindingNavigator Control Overview](bindingnavigator-control-overview-windows-forms.md) + Introduces the general concepts of the `BindingNavigator` control, which enables users to move through the items of a data source. + + [How to: Navigate Data with the Windows Forms BindingNavigator Control](how-to-navigate-data-with-the-windows-forms-bindingnavigator-control.md) + Provides steps to bind a `BindingNavigator` control to a data source. + + [How to: Move Through a DataSet with the Windows Forms BindingNavigator Control](move-through-a-dataset-with-wf-bindingnavigator-control.md) + Demonstrates using a `BindingNavigator` control to move through records in a . + + Also see [How to: Add Load, Save, and Cancel Buttons to the Windows Forms BindingNavigator Control](load-save-and-cancel-bindingnavigator.md). + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the control. + +## Related Sections + [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component-architecture.md b/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component-architecture.md new file mode 100644 index 0000000000..f46ca22605 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component-architecture.md @@ -0,0 +1,174 @@ +--- +title: "BindingSource Component Architecture" +ms.date: "03/30/2017" +helpviewer_keywords: + - "BindingSource component [Windows Forms], architecture" + - "Windows Forms, data binding" + - "BindingSource component [Windows Forms], about BindingSource component" + - "data binding [Windows Forms], BindingSource component" +ms.assetid: 7bc69c90-8a11-48b1-9336-3adab5b41591 +--- +# BindingSource Component Architecture +With the component, you can universally bind all Windows Forms controls to data sources. + + The component simplifies the process of binding controls to a data source and provides the following advantages over traditional data binding: + +- Enables design-time binding to business objects. + +- Encapsulates functionality and exposes events at design time. + +- Simplifies creating a list that supports the interface by providing list change notification for data sources that do not natively support list change notification. + +- Provides an extensibility point for the method. + +- Provides a level of indirection between the data source and the control. This indirection is important when the data source may change at run time. + +- Interoperates with other data-related Windows Forms controls, specifically the and the controls. + + For these reasons, the component is the preferred way to bind your Windows Forms controls to data sources. + +## BindingSource Features + The component provides several features for binding controls to data. With these features, you can implement most data-binding scenarios with almost no coding on your part. + + The component accomplishes this by providing a consistent interface for accessing many different kinds of data sources. This means that you use the same procedure for binding to any type. For example, you can attach the property to a or to a business object and in both cases you use the same set of properties, methods, and events to manipulate the data source. + + The consistent interface provided by the component greatly simplifies the process of binding data to controls. For data-source types that provide change notification, the component automatically communicates changes between the control and the data source. For data-source types that do not provide change notification, events are provided that let you raise change notifications. The following list shows the features supported by the component: + +- Indirection. + +- Currency management. + +- Data source as a list. + +- as an . + +- Custom item creation. + +- Transactional item creation. + +- support. + +- Design-time support. + +- Static methods. + +- Sorting and filtering with the interface. + +- Integration with . + +### Indirection + The component provides a level of indirection between a control and a data source. Instead of binding a control directly to a data source, you bind the control to a , and you attach the data source to the component's property. + + With this level of indirection, you can change the data source without resetting the control binding. This gives you the following capabilities: + +- You can attach the to different data sources while retaining the current control bindings. + +- You can change items in the data source and notify bound controls. For more information, see [How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource](reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md). + +- You can bind to a instead of an object in memory. For more information, see [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md). You can then bind to an object at run time. + +### Currency Management + The component implements the interface to handle currency management for you. With the interface, you can also access to the currency manager for a , in addition to the currency manager for another bound to the same . + + The component encapsulates functionality and exposes the most common properties and events. The following table describes some of the members related to currency management. + + property + Gets the currency manager associated with the . + + method + If there is another bound to the specified data member, gets its currency manager. + + property + Gets the current item of the data source. + + property + Gets or sets the current position in the underlying list. + + method + Applies pending changes to the underlying data source. + + method + Cancels the current edit operation. + +### Data Source as a List + The component implements the and interfaces. With this implementation, you can use the component itself as a data source, without any external storage. + + When the component is attached to a data source, it exposes the data source as a list. + + The property can be set to several data sources. These include types, objects, and lists of types. The resulting data source will be exposed as a list. The following table shows some of the common data sources and the resulting list evaluation. + +|DataSource property|List results| +|-------------------------|------------------| +|A null reference (`Nothing` in Visual Basic)|An empty of objects. Adding an item sets the list to the type of the added item.| +|A null reference (`Nothing` in Visual Basic) with set|Not supported; raises .| +|Non-list type or object of type "T"|An empty of type "T".| +|Array instance|An containing the array elements.| +| instance|An containing the items| +|List instance containing type "T"|An instance containing type "T".| + + Additionally, can be set to other list types, such as and , and the will handle them appropriately. In this case, the type that is contained in the list should have a parameterless constructor. + +### BindingSource as an IBindingList + The component provides members for accessing and manipulating the underlying data as an . The following table describes some of these members. + +|Member|Description| +|------------|-----------------| +| property|Gets the list that results from the evaluation of the or properties.| +| method|Adds a new item to the underlying list. Applies to data sources that implement the interface and allow adding items (that is, the property is set to `true`).| + +### Custom Item Creation + You can handle the event to provide your own item-creation logic. The event occurs before a new object is added to the . This event is raised after the method is called, but before the new item is added to the underlying list. By handling this event, you can provide custom item creation behavior without deriving from the class. For more information, see [How to: Customize Item Addition with the Windows Forms BindingSource](how-to-customize-item-addition-with-the-windows-forms-bindingsource.md). + +### Transactional Item Creation + The component implements the interface, which enables transactional item creation. After a new item is provisionally created by using a call to , the addition may be committed or rolled back in the following ways: + +- The method will explicitly commit the pending addition. + +- Performing another collection operation, such as an insertion, removal, or move, will implicitly commit the pending addition. + +- The method will roll back the pending addition if the method has not already been committed. + +### IEnumerable Support + The component enables binding controls to data sources. With this component, you can bind to a data source such as a . + + When an data source is assigned to the component, the creates an and adds the contents of the data source to the list. + +### Design-Time Support + Some object types cannot be created at design time, such as objects created from a factory class, or objects returned by a Web service. You may sometimes have to bind your controls to these types at design time, even though there is no object in memory to which your controls can bind. You may, for example, need to label the column headers of a control with the names of your custom type's public properties. + + To support this scenario, the component supports binding to a . When you assign a to the property, the component creates an empty of items. Any controls you subsequently bind to the component will be alerted to the presence of the properties or schema of your type at design time, or at run time. For more information, see [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md). + +### Static ListBindingHelper Methods + The , , and types all share common logic to generate a list from a `DataSource`/`DataMember` pair. Additionally, this common logic is publicly exposed for use by control authors and other third parties in the following `static` methods: + +- + +- . + +- + +- + +### Sorting and Filtering with the IBindingListView Interface + The component implements the interface, which extends the interface. The offers single column sorting and the offers advanced sorting and filtering. With , you can sort and filter items in the data source, if the data source also implements one of these interfaces. The component does not provide a reference implementation of these members. Instead, calls are forwarded to the underlying list. + + The following table describes the properties you use for sorting and filtering. + +|Member|Description| +|------------|-----------------| +| property|If the data source is an , gets or sets the expression used to filter which rows are viewed.| +| property|If the data source is an , gets or sets a column name used for sorting and sort order information.

-or-

If the data source is an and supports advanced sorting, gets multiple column names used for sorting and sort order| + +### Integration with BindingNavigator + You can use the component to bind any Windows Forms control to a data source, but the control is designed specifically to work with the component. The control provides a user interface for controlling the component's current item. By default, the control provides buttons that correspond to the navigation methods on the component. For more information, see [How to: Navigate Data with the Windows Forms BindingNavigator Control](how-to-navigate-data-with-the-windows-forms-bindingnavigator-control.md). + +## See also + +- +- +- [BindingSource Component Overview](bindingsource-component-overview.md) +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) +- [Windows Forms Data Binding](../windows-forms-data-binding.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) +- [How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource](reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component-overview.md b/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component-overview.md new file mode 100644 index 0000000000..1e41a763f1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component-overview.md @@ -0,0 +1,62 @@ +--- +title: "BindingSource Component Overview" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, data binding" + - "controls [Windows Forms], binding to data" + - "BindingSource component [Windows Forms], about BindingSource component" + - "data binding [Windows Forms], BindingSource component" +ms.assetid: be838caf-fcb0-4b68-827f-58b2c04b747f +--- +# BindingSource Component Overview +The component is designed to simplify the process of binding controls to an underlying data source. The component acts as both a conduit and a data source for other controls to bind to. It provides an abstraction of your form's data connection while passing through commands to the underlying list of data. Additionally, you can add data directly to it, so that the component itself functions as a data source. + +## BindingSource Component as an Intermediary + The component acts as the data source for some or all of the controls on the form. In Visual Studio, the can be bound to a control by means of the `DataBindings` property, which is accessible from the **Properties** window. Also see [How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer](bind-wf-controls-with-the-bindingsource.md). + + You can bind the component to both simple data sources, like a single property of an object or a basic collection like , and complex data sources, like a database table. The component acts as an intermediary that provides binding and currency management services. At design time or run time, you can bind a component to a complex data source by setting its and properties to the database and table, respectively. The following illustration demonstrates where the component fits into the existing data-binding architecture. + + ![Binding Source and Data Binding Architecture](./media/net-bindsrcdatabindarch.gif "NET_BindSrcDataBindArch") + +> [!NOTE] +> At design time, some actions, like dragging a database table from a data window onto a blank form, will create the component, bind it to the underlying data source, and add data-aware controls all in one operation. Also see [Bind Windows Forms controls to data in Visual Studio](/visualstudio/data-tools/bind-windows-forms-controls-to-data-in-visual-studio). + +## BindingSource Component as a Data Source + If you start adding items to the component without first specifying a list to be bound to, the component will act like a list-style data source and accept these added items. + + Additionally, you can write code to provide custom "AddNew" functionality by means of the event, which is raised when the method is called prior to the item being added to the list. For more information, see [BindingSource Component Architecture](bindingsource-component-architecture.md). + +## Navigation + For users that need to navigate the data on a form, the component enables you to navigate and manipulate data, in coordination with a component. For more information, see [BindingNavigator Control](bindingnavigator-control-windows-forms.md). + +## Data Manipulation + The: acts as a for all of its bindings and can, therefore, provide access to currency and position information regarding the data source. The following table shows the members that the component provides for accessing and manipulating the underlying data. + +|Member|Description| +|------------|-----------------| +| property|Gets the current item of the data source.| +| property|Gets or sets the current position in the underlying list.| +| property|Gets the list that is the evaluation of the and evaluation. If is not set, returns the list specified by .| +| method|Inserts an item in the list at the specified index.| +| method|Removes the current item from the list.| +| method|Applies pending changes to the underlying data source.| +| method|Cancels the current edit operation.| +| method|Adds a new item to the underlying list. If the data source implements and returns an item from the event, adds this item. Otherwise, the request is passed to the list's method. If the underlying list is not an , the item is automatically created through its public parameterless constructor.| + +## Sorting and Filtering + Usually, you should work with an ordered or filtered view of the data source. The following table shows the members that the component data source provides. + +|Member|Description| +|------------|-----------------| +| property|If the data source is an , gets or sets a column name used for sorting and sort order information. If the data source is an and supports advanced sorting, gets multiple column names used for sorting and sort order information| +| property|If the data source is an , gets or sets the expression used to filter which rows are viewed.| + +## See also + +- +- +- [BindingSource Component Architecture](bindingsource-component-architecture.md) +- [BindingSource Component](bindingsource-component.md) +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) +- [Windows Forms Data Binding](../windows-forms-data-binding.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component.md b/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component.md new file mode 100644 index 0000000000..275ea3da6f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/bindingsource-component.md @@ -0,0 +1,65 @@ +--- +title: "BindingSource Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "data binding [Windows Forms], Windows Forms" + - "Windows Forms, data binding control" + - "BindingSource component [Windows Forms]" +ms.assetid: 3e2faf4c-f5b8-4fa6-9fbc-f59c37ec2fb9 +--- +# BindingSource Component +Encapsulates a data source for binding to controls. + + The component serves two purposes. First, it provides a layer of indirection when binding the controls on a form to data. This is accomplished by binding the component to your data source, and then binding the controls on your form to the component. All further interaction with the data, including navigating, sorting, filtering, and updating, is accomplished with calls to the component. + + Second, the component can act as a strongly typed data source. Adding a type to the component with the method creates a list of that type. + +## In This Section + [BindingSource Component Overview](bindingsource-component-overview.md) + Introduces the general concepts of the component, which allows you to bind a data source to a control. + + [How to: Bind Windows Forms Controls to DBNull Database Values](how-to-bind-windows-forms-controls-to-dbnull-database-values.md) + Shows how to handle a value from the data source using the component. + + [How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component](sort-and-filter-ado-net-data-with-wf-bindingsource-component.md) + Demonstrates using the component to apply sorts and filters to displayed data. + + [How to: Bind to a Web Service Using the Windows Forms BindingSource](how-to-bind-to-a-web-service-using-the-windows-forms-bindingsource.md) + Shows how to use the component to bind to a Web service. + + [How to: Handle Errors and Exceptions that Occur with Databinding](how-to-handle-errors-and-exceptions-that-occur-with-databinding.md) + Demonstrates using the component to gracefully handle errors that occur in a data binding operation. + + [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) + Demonstrates using a component to bind to a type. + + [How to: Bind a Windows Forms Control to a Factory Object](how-to-bind-a-windows-forms-control-to-a-factory-object.md) + Demonstrates using a component to bind to a factory object or method. + + [How to: Customize Item Addition with the Windows Forms BindingSource](how-to-customize-item-addition-with-the-windows-forms-bindingsource.md) + Demonstrates using a component to create new items and add them to a data source. + + [How to: Raise Change Notifications Using the BindingSource ResetItem Method](how-to-raise-change-notifications-using-the-bindingsource-resetitem-method.md) + Demonstrates using a component to raise change-notification events for data sources that do not support change notification. + + [How to: Raise Change Notifications Using a BindingSource and the INotifyPropertyChanged Interface](raise-change-notifications--bindingsource.md) + Demonstrates how to use a type that inherits from the with a control. + + [How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource](reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md) + Demonstrates how to respond to changes in the data source using the component. + + [How to: Share Bound Data Across Forms Using the BindingSource Component](how-to-share-bound-data-across-forms-using-the-bindingsource-component.md) + Shows how to use the to bind multiple forms to the same data source. + +## Reference + + Provides reference documentation for the component. + + + Provides reference documentation for the control. + +## Related Sections + [Windows Forms Data Binding](../windows-forms-data-binding.md) + Contains links to topics describing the Windows Forms data binding architecture. + + Also see [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio). diff --git a/dotnet-desktop-guide/framework/winforms/controls/button-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/button-control-overview-windows-forms.md new file mode 100644 index 0000000000..f6d5111481 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/button-control-overview-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "Button Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "Button" +helpviewer_keywords: + - "Button control [Windows Forms], about Button control" + - "buttons [Windows Forms], about buttons" +ms.assetid: 255b291b-51a9-4a92-a1a4-2400cd82443f +--- +# Button Control Overview (Windows Forms) +The Windows Forms control allows the user to click it to perform an action. When the button is clicked, it looks as if it is being pushed in and released. Whenever the user clicks a button, the event handler is invoked. You place code in the event handler to perform any action you choose. + + The text displayed on the button is contained in the property. If your text exceeds the width of the button, it will wrap to the next line. However, it will be clipped if the control cannot accommodate its overall height. For more information, see [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md). The property can contain an access key, which allows a user to "click" the control by pressing the ALT key with the access key. For details, see [How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md). The appearance of the text is controlled by the property and the property. + + The control can also display images using the and properties. For more information, see [How to: Set the Image Displayed by a Windows Forms Control](how-to-set-the-image-displayed-by-a-windows-forms-control.md). + +## See also + +- +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) +- [How to: Designate a Windows Forms Button as the Accept Button Using the Designer](designate-a-wf-button-as-the-accept-button-using-the-designer.md) +- [How to: Designate a Windows Forms Button as the Cancel Button Using the Designer](designate-a-wf-button-as-the-cancel-button-using-the-designer.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/button-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/button-control-windows-forms.md new file mode 100644 index 0000000000..4b73c93628 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/button-control-windows-forms.md @@ -0,0 +1,38 @@ +--- +title: "Button Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "buttons" + - "Button control [Windows Forms]" +ms.assetid: d38bc40c-8040-4f19-9e88-2c665b0ab80b +--- +# Button Control (Windows Forms) +The Windows Forms `Button` control allows the user to click it to perform an action. The `Button` control can display both text and images. When the button is clicked, it looks as if it is being pushed in and released. + +## In This Section + [Button Control Overview](button-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) + Explains the most basic use of a button on a Windows Form. + + [How to: Designate a Windows Forms Button as the Accept Button](how-to-designate-a-windows-forms-button-as-the-accept-button.md) + Explains how to designate a `Button` control to be the accept button, also known as the default button. + + [How to: Designate a Windows Forms Button as the Cancel Button](how-to-designate-a-windows-forms-button-as-the-cancel-button.md) + Explains how to designate a `Button` control to be the cancel button, which is clicked whenever the user presses the ESC key. + + [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) + Lists methods of selecting a button. + + Also see [How to: Designate a Windows Forms Button as the Accept Button Using the Designer](designate-a-wf-button-as-the-accept-button-using-the-designer.md) and [How to: Designate a Windows Forms Button as the Cancel Button Using the Designer](designate-a-wf-button-as-the-cancel-button-using-the-designer.md). + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + Also see [User Input to Dialog Boxes](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/1s9ws53w(v=vs.100)) and [How to: Close Dialog Boxes and Retain User Input](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/65ad5907(v=vs.100)). diff --git a/dotnet-desktop-guide/framework/winforms/controls/cell-styles-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/cell-styles-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..ad83eaa890 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/cell-styles-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,162 @@ +--- +title: Cell Styles in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], cell styles" + - "cells [Windows Forms], styles" + - "data grids [Windows Forms], cell styles" +ms.assetid: dbb75ed6-8804-4232-8382-f9920c2e380c +--- +# Cell Styles in the Windows Forms DataGridView Control +Each cell within the control can have its own style, such as text format, background color, foreground color, and font. Typically, however, multiple cells will share particular style characteristics. + + Groups of cells that share styles may include all cells within particular rows or columns, all cells that contain particular values, or all cells in the control. Because these groups overlap, each cell may get its styling information from more than one place. For example, you may want every cell in a control to use the same font, but only cells in currency columns to use currency format, and only currency cells with negative numbers to use a red foreground color. + +## The DataGridViewCellStyle Class + The class contains the following properties related to visual style: + +- and + +- and + +- + + This class also contains the following properties related to formatting: + +- and + +- and + +- + +- + +- + + For more information on these properties and other cell-style properties, see the reference documentation and the topics listed in the See Also section below. + +## Using DataGridViewCellStyle Objects + You can retrieve objects from various properties of the , , , and classes and their derived classes. If one of these properties has not yet been set, retrieving its value will create a new object. You can also instantiate your own objects and assign them to these properties. + + You can avoid unnecessary duplication of style information by sharing objects among multiple elements. Because the styles set at the control, column, and row levels filter down through each level to the cell level, you can also avoid style duplication by setting only those style properties at each level that differ from the levels above. This is described in more detail in the Style Inheritance section that follows. + + The following table lists the primary properties that get or set objects. + +|Property|Classes|Description| +|--------------|-------------|-----------------| +|`DefaultCellStyle`|, , , and derived classes|Gets or sets default styles used by all cells in the entire control (including header cells), in a column, or in a row.| +|||Gets or sets default cell styles used by all rows in the control. This does not include header cells.| +|||Gets or sets default cell styles used by alternating rows in the control. Used to create a ledger-like effect.| +|||Gets or sets default cell styles used by the control's row headers. Overridden by the current theme if visual styles are enabled.| +|||Gets or sets default cell styles used by the control's column headers. Overridden by the current theme if visual styles are enabled.| +|| and derived classes|Gets or sets styles specified at the cell level. These styles override those inherited from higher levels.| +|`InheritedStyle`|, , , and derived classes|Gets all the styles currently applied to the cell, row, or column, including styles inherited from higher levels.| + + As mentioned above, getting the value of a style property automatically instantiates a new object if the property has not been previously set. To avoid creating these objects unnecessarily, the row and column classes have a property that you can check to determine whether the property has been set. Similarly, the cell classes have a property that indicates whether the property has been set. + + Each of the style properties has a corresponding *PropertyName*`Changed` event on the control. For row, column, and cell properties, the name of the event begins with "`Row`", "`Column`", or "`Cell`" (for example, ). Each of these events occurs when the corresponding style property is set to a different object. These events do not occur when you retrieve a object from a style property and modify its property values. To respond to changes to the cell style objects themselves, handle the event. + +## Style Inheritance + Each gets its appearance from its property. The object returned by this property inherits its values from a hierarchy of properties of type . These properties are listed below in the order in which the for non-header cells obtains its values. + +1. + +2. + +3. (only for cells in rows with odd index numbers) + +4. + +5. + +6. + + For row and column header cells, the property is populated by values from the following list of source properties in the given order. + +1. + +2. or + +3. + + The following diagram illustrates this process. + + ![Properties of type DataGridViewCellStyle](./media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-inheritance-diagram.gif "DataGridViewCells inheritance diagram") + + You can also access the styles inherited by specific rows and columns. The column property inherits its values from the following properties. + +1. + +2. + + The row property inherits its values from the following properties. + +1. + +2. (only for cells in rows with odd index numbers) + +3. + +4. + + For each property in a object returned by an `InheritedStyle` property, the property value is obtained from the first cell style in the appropriate list that has the corresponding property set to a value other than the class defaults. + + The following table illustrates how the property value for an example cell is inherited from its containing column. + +|Property of type `DataGridViewCellStyle`|Example `ForeColor` value for retrieved object| +|----------------------------------------------|----------------------------------------------------| +||| +||| +||| +||| +||| +||| + + In this case, the value from the cell's row is the first real value on the list. This becomes the property value of the cell's . + + The following diagram illustrates how different properties can inherit their values from different places. + + ![DataGridView property-value inheritance](./media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-value-inheritance-diagram.gif "DataGridViewCells value inheritance diagram") + + By taking advantage of style inheritance, you can provide appropriate styles for the entire control without having to specify the same information in multiple places. + + Although header cells participate in style inheritance as described, the objects returned by the and properties of the control have initial property values that override the property values of the object returned by the property. If you want the properties set for the object returned by the property to apply to row and column headers, you must set the corresponding properties of the objects returned by the and properties to the defaults indicated for the class. + +> [!NOTE] +> If visual styles are enabled, the row and column headers (except for the ) are automatically styled by the current theme, overriding any styles specified by these properties. + + The , , and types also initialize some values of the object returned by the column property. For more information, see the reference documentation for these types. + +## Setting Styles Dynamically + To customize the styles of cells with particular values, implement a handler for the event. Handlers for this event receive an argument of the type. This object contains properties that let you determine the value of the cell being formatted along with its location in the control. This object also contains a property that is initialized to the value of the property of the cell being formatted. You can modify the cell style properties to specify style information appropriate to the cell value and location. + +> [!NOTE] +> The and events also receive a object in the event data, but in their case, it is a copy of the row property for read-only purposes, and changes to it do not affect the control. + + You can also dynamically modify the styles of individual cells in response to events such as the and events. For example, in a handler for the event, you could store the current value of the cell background color (retrieved through the cell's property), then set it to a new color that will highlight the cell when the mouse hovers over it. In a handler for the event, you can then restore the background color to the original value. + +> [!NOTE] +> Caching the values stored in the cell's property is important regardless of whether a particular style value is set. If you temporarily replace a style setting, restoring it to its original "not set" state ensures that the cell will go back to inheriting the style setting from a higher level. If you need to determine the actual style in effect for a cell regardless of whether the style is inherited, use the cell's property. + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md) +- [Data Formatting in the Windows Forms DataGridView Control](data-formatting-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/change-displayed-data-at-run-time-wf-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/change-displayed-data-at-run-time-wf-datagrid-control.md new file mode 100644 index 0000000000..48c3b4fdb8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/change-displayed-data-at-run-time-wf-datagrid-control.md @@ -0,0 +1,95 @@ +--- +title: Change Displayed Data at Run Time in DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "DataGrid control [Windows Forms], dynamically changing at run time" + - "DataGrid control [Windows Forms], data binding" + - "cells [Windows Forms], changing DataGrid cell values" +ms.assetid: 0c7a6d00-30de-416e-8223-0a81ddb4c1f8 +--- +# How to: Change Displayed Data at Run Time in the Windows Forms DataGrid Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + After you have created a Windows Forms using the design-time features, you may also wish to dynamically change elements of the object of the grid at run time. This can include changes to either individual values of the table or changing which data source is bound to the control. Changes to individual values are done through the object, not the control. + +### To change data programmatically + +1. Specify the desired table from the object and the desired row and field from the table and set the cell equal to the new value. + + > [!NOTE] + > To specify the first table of the or the first row of the table, use 0. + + The following example shows how to change the second entry of the first row of the first table of a dataset by clicking `Button1`. The (`ds`) and Tables (`0` and `1`) were previously created. + + ```vb + Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + ds.tables(0).rows(0)(1) = "NewEntry" + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + ds.Tables[0].Rows[0][1]="NewEntry"; + } + ``` + + ```cpp + private: + void button1_Click(System::Object^ sender, System::EventArgs^ e) + { + dataSet1->Tables[0]->Rows[0][1] = "NewEntry"; + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + + ```cpp + this->button1->Click += + gcnew System::EventHandler(this, &Form1::button1_Click); + ``` + + At run time you can use the method to bind the control to a different data source. For example, you may have several ADO.NET data controls, each connected to a different database. + +### To change the DataSource programmatically + +1. Set the method to the name of the data source and table you want to bind to. + + The following example shows how to change the date source using the method to an ADO.NET data control (adoPubsAuthors) that is connected to the Authors table in the Pubs database. + + ```vb + Private Sub ResetSource() + DataGrid1.SetDataBinding(adoPubsAuthors, "Authors") + End Sub + ``` + + ```csharp + private void ResetSource() + { + DataGrid1.SetDataBinding(adoPubsAuthors, "Authors"); + } + ``` + + ```cpp + private: + void ResetSource() + { + dataGrid1->SetDataBinding(adoPubsAuthors, "Authors"); + } + ``` + +## See also + +- [ADO.NET DataSets](https://docs.microsoft.com/dotnet/framework/data/adonet/ado-net-datasets) +- [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) +- [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) +- [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/change-the-border-and-gridline-styles-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/change-the-border-and-gridline-styles-in-the-datagrid.md new file mode 100644 index 0000000000..a6863f28c5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/change-the-border-and-gridline-styles-in-the-datagrid.md @@ -0,0 +1,63 @@ +--- +title: Change the Border and Gridline Styles in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "gridlines [Windows Forms], changing styles" + - "data grids [Windows Forms], changing gridline styles" + - "DataGridView control [Windows Forms], border styles" + - "data grids [Windows Forms], changing border styles" + - "DataGridView control [Windows Forms], gridline styles" +ms.assetid: 2f413c7a-4025-4171-8e3a-66ef908ea583 +--- +# How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control +With the control, you can customize the appearance of the control's border and gridlines to improve the user experience. You can modify the gridline color and the control border style in addition to the border styles for the cells within the control. You can also apply different cell border styles for ordinary cells, row header cells, and column header cells. + +> [!NOTE] +> The gridline color is used only with the , , and values of the enumeration and the value of the enumeration. The other values of these enumerations use colors specified by the operating system. Additionally, when visual styles are enabled on Windows XP and the Windows Server 2003 family through the method, the property value is not used. + +### To change the gridline color programmatically + +- Set the property. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#031](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#031)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#031](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#031)] + +### To change the border style of the entire DataGridView control programmatically + +- Set the property to one of the enumeration values. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#032](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#032)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#032](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#032)] + +### To change the border styles for DataGridView cells programmatically + +- Set the , , and properties. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#033](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#033)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#033](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#033)] + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#030](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#030)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#030](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#030)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the , , and assemblies. + +## See also + +- +- +- +- +- +- +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/change-the-order-of-columns-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/change-the-order-of-columns-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..a0973e4c36 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/change-the-order-of-columns-in-the-datagrid-using-the-designer.md @@ -0,0 +1,30 @@ +--- +title: Change the Order of Columns in DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "columns [Windows Forms], order of" + - "DataGridView control [Windows Forms], column order" + - "Windows Forms, columns" + - "data [Windows Forms], displaying" +ms.assetid: 7fe52a98-75d6-448c-97a5-65ca2c568c1a +--- +# How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer + +When you bind a Windows Forms control to a data source, the display order of the automatically generated columns is dictated by the data source. If this order is not what you prefer, you can change the order of the columns using the designer. You may also want to add unbound columns to the control and change their display order. For information about how to change the column order programmatically, see [How to: Change the Order of Columns in the Windows Forms DataGridView Control](how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md). + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To change the column order using the designer + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Edit Columns**. + +2. Select a column from the **Selected Columns** list. + +3. Click the up or down arrow to the right of the **Selected Columns** list until the selected column is in the position you want. + +## See also + +- +- [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/change-the-type-of-a-wf-datagridview-column-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/change-the-type-of-a-wf-datagridview-column-using-the-designer.md new file mode 100644 index 0000000000..2979af0859 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/change-the-type-of-a-wf-datagridview-column-using-the-designer.md @@ -0,0 +1,32 @@ +--- +title: Change the Type of a DataGridView Column Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, columns" + - "columns [Windows Forms], types" + - "DataGridView control [Windows Forms], changing column type" + - "data [Windows Forms], displaying" +ms.assetid: 7f994d45-600d-4190-a187-35803214b40c +--- +# How to: Change the Type of a Windows Forms DataGridView Column Using the Designer +Sometimes you will want to change the type of a column that has already been added to a Windows Forms control. For example, you may want to modify the types of some of the columns that are generated automatically when you bind the control to a data source. This is useful when the table you display has columns containing foreign keys to rows in a related table. In this case, you may want to replace the text box columns that display these foreign keys with combo box columns that display more meaningful values from the related table. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To change the type of a column using the designer + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Edit Columns**. + +2. Select a column from the **Selected Columns** list. + +3. In the **Column Properties** grid, set the `ColumnType` property to the new column type. + + > [!NOTE] + > The `ColumnType` property is a design-time-only property that indicates the class representing the column type. It is not an actual property defined in a column class. + +## See also + +- +- +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/checkbox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/checkbox-control-overview-windows-forms.md new file mode 100644 index 0000000000..1d43d7fb14 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/checkbox-control-overview-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "CheckBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "CheckBox" +helpviewer_keywords: + - "CheckBox control [Windows Forms], about CheckBox control" + - "data binding [Windows Forms], checkbox controls" + - "check boxes [Windows Forms], about check boxes" +ms.assetid: 085a4e0b-9046-473f-b141-d0edddfb2ebb +--- +# CheckBox Control Overview (Windows Forms) +The Windows Forms control indicates whether a particular condition is on or off. It is commonly used to present a Yes/No or True/False selection to the user. You can use check box controls in groups to display multiple choices from which the user can select one or more. + + The check box control is similar to the radio button control in that each is used to indicate a selection that is made by the user. They differ in that only one radio button in a group can be selected at a time. With the check box control, however, any number of check boxes may be selected. + + A check box may be connected to elements in a database using simple data binding. Multiple check boxes may be grouped using the control. This is useful for visual appearance and also for user interface design, since grouped controls can be moved around together on the form designer. For more information, see [Windows Forms Data Binding](../windows-forms-data-binding.md) and [GroupBox Control](groupbox-control-windows-forms.md). + + The control has two important properties, and . The property returns either `true` or `false`. The property returns either or ; or, if the property is set to `true`, may also return . In the indeterminate state, the box is displayed with a dimmed appearance to indicate the option is unavailable. + +## See also + +- +- [How to: Set Options with Windows Forms CheckBox Controls](how-to-set-options-with-windows-forms-checkbox-controls.md) +- [How to: Respond to Windows Forms CheckBox Clicks](how-to-respond-to-windows-forms-checkbox-clicks.md) +- [CheckBox Control](checkbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/checkbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/checkbox-control-windows-forms.md new file mode 100644 index 0000000000..b585d99915 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/checkbox-control-windows-forms.md @@ -0,0 +1,32 @@ +--- +title: "CheckBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "checked list items [Windows Forms], Windows Forms controls" + - "CheckBox control [Windows Forms]" + - "list controls [Windows Forms], Windows Forms" + - "list items [Windows Forms], Windows Forms controls that display" + - "checked list items" + - "check boxes" +ms.assetid: 0719d798-c307-40d3-9040-72a62679c227 +--- +# CheckBox Control (Windows Forms) +The Windows Forms `CheckBox` control indicates whether a particular condition is on or off. It is commonly used to present a Yes/No or True/False selection to the user. You can use check box controls in groups to display multiple choices from which the user can select one or more. It is similar to the control, but any number of grouped `CheckBox` controls may be selected. + +## In This Section + [CheckBox Control Overview](checkbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Respond to Windows Forms CheckBox Clicks](how-to-respond-to-windows-forms-checkbox-clicks.md) + Explains how to use a check box to determine your application's actions. + + [How to: Set Options with Windows Forms CheckBox Controls](how-to-set-options-with-windows-forms-checkbox-controls.md) + Describes how to use a check box to set options such as properties of an object. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/checkedlistbox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/checkedlistbox-control-overview-windows-forms.md new file mode 100644 index 0000000000..774932b3be --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/checkedlistbox-control-overview-windows-forms.md @@ -0,0 +1,24 @@ +--- +title: "CheckedListBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "CheckedListBox" +helpviewer_keywords: + - "CheckedListBox control [Windows Forms], about CheckedListBox control" + - "check marks" + - "list boxes [Windows Forms], about list boxes" +ms.assetid: e6cff3ce-e2ba-458e-851f-299e8e9c8abf +--- +# CheckedListBox Control Overview (Windows Forms) +The Windows Forms control extends the control. It does almost everything that a list box does and also can display a check mark next to items in the list. Other differences between the two controls are that checked list boxes only support ; and that checked list boxes can only have one item or none selected. Note that a selected item appears highlighted on the form and is not the same as a checked item. + + Checked list boxes can have items added at design time using the **String Collection Editor** or their items can added dynamically from a collection at run time, using the property. For more information, see [How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control](add-and-remove-items-from-a-wf-combobox.md). + +## See also + +- +- +- +- [ListBox Control Overview](listbox-control-overview-windows-forms.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) +- [How to: Determine Checked Items in the Windows Forms CheckedListBox Control](how-to-determine-checked-items-in-the-windows-forms-checkedlistbox-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/checkedlistbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/checkedlistbox-control-windows-forms.md new file mode 100644 index 0000000000..e406a774ae --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/checkedlistbox-control-windows-forms.md @@ -0,0 +1,36 @@ +--- +title: "CheckedListBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "CheckedListBox control [Windows Forms], reference" + - "checked list items [Windows Forms], Windows Forms controls" + - "list controls [Windows Forms], Windows Forms" + - "CheckedListBox control [Windows Forms]" + - "list box controls [Windows Forms]" + - "check marks" + - "list boxes [Windows Forms], displaying check marks" + - "list boxes [Windows Forms], Windows Forms controls" + - "list items [Windows Forms], Windows Forms controls that display" + - "list boxes" +ms.assetid: 2a525f72-0245-41d7-94e9-b9c971dc4484 +--- +# CheckedListBox Control (Windows Forms) +The Windows Forms `CheckedListBox` control displays a list of items, like the control, and also can display a check mark next to items in the list. + +## In This Section + [CheckedListBox Control Overview](checkedlistbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Determine Checked Items in the Windows Forms CheckedListBox Control](how-to-determine-checked-items-in-the-windows-forms-checkedlistbox-control.md) + Describes how to step through a list to determine which items are checked. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) + Provides a list of things you can do with list boxes, combo boxes, and checked list boxes. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/colordialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/colordialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..0be46c8992 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/colordialog-component-overview-windows-forms.md @@ -0,0 +1,21 @@ +--- +title: "ColorDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ColorDialog" +helpviewer_keywords: + - "color dialog box [Windows Forms], about color dialog box" + - "ColorDialog component [Windows Forms], about ColorDialog" +ms.assetid: 6dbdd8f0-f697-4728-bb09-7ea156f6d800 +--- +# ColorDialog Component Overview (Windows Forms) +The Windows Forms component is a pre-configured dialog box that allows the user to select a color from a palette and to add custom colors to that palette. It is the same dialog box that you see in other Windows-based applications to select colors. Use it within your Windows-based application as a simple solution in lieu of configuring your own dialog box. + + The color selected in the dialog box is returned in the property. If the property is set to `false`, the "Define Custom Colors" button is disabled and the user is restricted to the predefined colors in the palette. If the property is set to `true`, the user cannot select dithered colors. To display the dialog box, you must call its method. + +## See also + +- +- [ColorDialog Component](colordialog-component-windows-forms.md) +- [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) +- [How to: Change the Appearance of the Windows Forms ColorDialog Component](how-to-change-the-appearance-of-the-windows-forms-colordialog-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/colordialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/colordialog-component-windows-forms.md new file mode 100644 index 0000000000..cc81e793d8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/colordialog-component-windows-forms.md @@ -0,0 +1,31 @@ +--- +title: "ColorDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ColorDialog component" + - "colors [Windows Forms], dialog box" + - "color dialog box" +ms.assetid: 261793e0-8252-47c5-b76c-621857b8da44 +--- +# ColorDialog Component (Windows Forms) +The Windows Forms component is a pre-configured dialog box that allows the user to select a color from a palette and to add custom colors to that palette. It is the same dialog box that you see in other Windows-based applications to select colors. Use it within your Windows-based application as a simple solution in lieu of configuring your own dialog box. + +## In This Section + [ColorDialog Component Overview](colordialog-component-overview-windows-forms.md) + Introduces the general concepts of the component, which allows you to display a pre-configured dialog box that users can use to select colors from a palette. + + [How to: Change the Appearance of the Windows Forms ColorDialog Component](how-to-change-the-appearance-of-the-windows-forms-colordialog-component.md) + Describes how to change the colors available to users and other properties. + + [How to: Show a Color Palette with the ColorDialog Component](how-to-show-a-color-palette-with-the-colordialog-component.md) + Explains how to select a color at run time by means of an instance of the component. + +## Related Sections + [Controls You Can Use On Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + + Provides reference information on the class and its members. + + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Lists a set of controls that allow users to perform standard interactions with the application or system. diff --git a/dotnet-desktop-guide/framework/winforms/controls/column-fill-mode-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/column-fill-mode-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..e84b7d7c57 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/column-fill-mode-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,73 @@ +--- +title: Column Fill Mode in DataGridView Control +description: Learn how the Windows Forms DataGridView control in column fill mode resizes its columns automatically so that they fill the width of the available display area. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], automatically resizing columns" + - "DataGridView control [Windows Forms], column fill mode" + - "data grids [Windows Forms], column fill mode" +ms.assetid: b4ef7411-ebf4-4e26-bb33-aecec90de80c +--- +# Column Fill Mode in the Windows Forms DataGridView Control +In column fill mode, the control resizes its columns automatically so that they fill the width of the available display area. The control does not display the horizontal scroll bar except when it is necessary to keep the width of every column equal to or greater than its property value. + + The sizing behavior of each column depends on its property. The value of this property is inherited from the column's property or the control's property if the column value is (the default value). + + Each column can have a different size mode, but any columns with a size mode of will share the display-area width that is not used by the other columns. This width is divided among the fill-mode columns in proportions relative to their property values. For example, if two columns have values of 100 and 200, the first column will be half as wide as the second column. + +## User Resizing in Fill Mode + Unlike sizing modes that resize based on cell contents, fill mode does not prevent users from resizing columns that have property values of `true`. When a user resizes a fill-mode column, any fill-mode columns after the resized column (to the right if is `false`; otherwise, to the left) are also resized to compensate for the change in the available width. If there are no fill-mode columns after the resized column, then all other fill-mode columns in the control are resized to compensate. If there are no other fill-mode columns in the control, the resize is ignored. If a column that is not in fill mode is resized, all fill-mode columns in the control change sizes to compensate. + + After resizing a fill-mode column, the values for all columns that changed are adjusted proportionally. For example, if four fill-mode columns have values of 100, resizing the second column to half its original width will result in values of 100, 50, 125, and 125. Resizing a column that is not in fill mode will not change any values because the fill-mode columns will simply resize to compensate while retaining the same proportions. + +## Content-Based FillWeight Adjustment + You can initialize values for fill-mode columns by using the automatic resizing methods, such as the method. This method first calculates the widths required by columns to display their contents. Next, the control adjusts the values for all fill-mode columns so that their proportions match the proportions of the calculated widths. Finally, the control resizes the fill-mode columns using the new proportions so that all columns in the control fill the available horizontal space. + +## Example + +### Description + By using appropriate values for the , , , and properties, you can customize the column-sizing behaviors for many different scenarios. + + The following demonstration code enables you to experiment with different values for the , , and properties of different columns. In this example, a control is bound to its own collection, and one column is bound to each of the , , , , and properties. Each of the columns is also represented by a row in the control, and changing values in a row will update the properties of the corresponding column so that you can see how the values interact. + +### Code + [!code-csharp[System.Windows.Forms.DataGridViewFillColumnsDemo#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/CS/fillcolumns.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewFillColumnsDemo#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/vb/fillcolumns.vb#00)] + +### Comments + To use this demonstration application: + +- Change the size of the form. Observe how columns change their widths while retaining the proportions indicated by the property values. + +- Change the column sizes by dragging the column dividers with the mouse. Observe how the values change. + +- Change the value for one column, then drag to resize the form. Observe how, when you make the form small enough, the values do not go below the values. + +- Change the values for all columns to large numbers so that the combined values exceed the width of the control. Observe how the horizontal scroll bar appears. + +- Change the values for some columns. Observe the effect when you resize columns or the form. + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- +- +- [Resizing Columns and Rows in the Windows Forms DataGridView Control](resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/column-sort-modes-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/column-sort-modes-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..c5ac148964 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/column-sort-modes-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,65 @@ +--- +title: Column Sort Modes in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "data grids [Windows Forms], sort modes" + - "DataGridView control [Windows Forms], sort mode" +ms.assetid: 43715887-2df9-4da7-bcf1-b9c7c842b2bf +--- +# Column Sort Modes in the Windows Forms DataGridView Control + columns have three sort modes. The sort mode for each column is specified through the property of the column, which can be set to one of the following enumeration values. + +|`DataGridViewColumnSortMode` value|Description| +|----------------------------------------|-----------------| +||Default for text box columns. Unless column headers are used for selection, clicking the column header automatically sorts the by this column and displays a glyph indicating the sort order.| +||Default for non–text box columns. You can sort this column programmatically; however, it is not intended for sorting, so no space is reserved for the sorting glyph.| +||You can sort this column programmatically, and space is reserved for the sorting glyph.| + + You might want to change the sort mode for a column that defaults to if it contains values that can be meaningfully ordered. For example, if you have a database column containing numbers that represent item states, you can display these numbers as corresponding icons by binding an image column to the database column. You can then change the numerical cell values into image display values in a handler for the event. In this case, setting the property to will enable your users to sort the column. Automatic sorting will enable your users to group items that have the same state even if the states corresponding to the numbers do not have a natural sequence. Check box columns are another example where automatic sorting is useful for grouping items in the same state. + + You can sort a programmatically by the values in any column or in multiple columns, regardless of the settings. Programmatic sorting is useful when you want to provide your own user interface (UI) for sorting or when you want to implement custom sorting. Providing your own sorting UI is useful, for example, when you set the selection mode to enable column header selection. In this case, although the column headers cannot be used for sorting, you still want the headers to display the appropriate sorting glyph, so you would set the property to . + + Columns set to programmatic sort mode do not automatically display a sorting glyph. For these columns, you must display the glyph yourself by setting the property. This is necessary if you want flexibility in custom sorting. For example, if you sort the by multiple columns, you might want to display multiple sorting glyphs or no sorting glyph. + + Although you can programmatically sort a by any column, some columns, such as button columns, might not contain values that can be meaningfully ordered. For these columns, a property setting of indicates that it will never be used for sorting, so there is no need to reserve space in the header for the sorting glyph. + + When a is sorted, you can determine both the sort column and the sort order by checking the values of the and properties. These values are not meaningful after a custom sorting operation. For more information about custom sorting, see the Custom Sorting section later in this topic. + + When a control containing both bound and unbound columns is sorted, the values in the unbound columns cannot be maintained automatically. To maintain these values, you must implement virtual mode by setting the property to `true` and handling the and events. For more information, see [How to: Implement Virtual Mode in the Windows Forms DataGridView Control](how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md). Sorting by unbound columns in bound mode is not supported. + +## Programmatic Sorting + You can sort a programmatically by calling its method. + + The `Sort(DataGridViewColumn,ListSortDirection)` overload of the method takes a and a enumeration value as parameters. This overload is useful when sorting by columns with values that can be meaningfully ordered, but which you do not want to configure for automatic sorting. When you call this overload and pass in a column with a property value of , the and properties are set automatically and the appropriate sorting glyph appears in the column header. + +> [!NOTE] +> When the control is bound to an external data source by setting the property, the `Sort(DataGridViewColumn,ListSortDirection)` method overload does not work for unbound columns. Additionally, when the property is `true`, you can call this overload only for bound columns. To determine whether a column is data-bound, check the property value. Sorting unbound columns in bound mode is not supported. + +## Custom Sorting + You can customize by using the `Sort(IComparer)` overload of the method or by handling the event. + + The `Sort(IComparer)` method overload takes an instance of a class that implements the interface as a parameter. This overload is useful when you want to provide custom sorting; for example, when the values in a column do not have a natural sort order or when the natural sort order is inappropriate. In this case, you cannot use automatic sorting, but you might still want your users to sort by clicking the column headers. You can call this overload in a handler for the event if you do not use column headers for selection. + +> [!NOTE] +> The `Sort(IComparer)` method overload works only when the control is not bound to an external data source and the property value is `false`. To customize sorting for columns bound to an external data source, you must use the sorting operations provided by the data source. In virtual mode, you must provide your own sorting operations for unbound columns. + + To use the `Sort(IComparer)` method overload, you must create your own class that implements the interface. This interface requires your class to implement the method, to which the passes objects as input when the `Sort(IComparer)` method overload is called. With this, you can calculate the correct row ordering based on the values in any column. + + The `Sort(IComparer)` method overload does not set the and properties, so you must always set the property to display the sorting glyph. + + As an alternative to the `Sort(IComparer)` method overload, you can provide custom sorting by implementing a handler for the event. This event occurs when users click the headers of columns configured for automatic sorting or when you call the `Sort(DataGridViewColumn,ListSortDirection)` overload of the method. The event occurs for each pair of rows in the control, enabling you to calculate their correct order. + +> [!NOTE] +> The event does not occur when the property is set or when the property value is `true`. + +## See also + +- +- +- +- +- +- +- [Sorting Data in the Windows Forms DataGridView Control](sorting-data-in-the-windows-forms-datagridview-control.md) +- [How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control](set-the-sort-modes-for-columns-wf-datagridview-control.md) +- [How to: Customize Sorting in the Windows Forms DataGridView Control](how-to-customize-sorting-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/column-types-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/column-types-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..521e222e0f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/column-types-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,90 @@ +--- +title: Column Types in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "columns [Windows Forms], types" + - "DataGridView control [Windows Forms], column types" + - "data grids [Windows Forms], columns" +ms.assetid: f0a0a9f1-8757-4bfd-891f-d7d12870dbed +--- +# Column Types in the Windows Forms DataGridView Control +The control uses several column types to display its information and enable users to modify or add information. + + When you bind a control and set the property to `true`, columns are automatically generated using default column types appropriate for the data types contained in the bound data source. + + You can also create instances of any of the column classes yourself and add them to the collection returned by the property. You can create these instances for use as unbound columns, or you can manually bind them. Manually bound columns are useful, for example, when you want to replace an automatically generated column of one type with a column of another type. + + The following table describes the various column classes available for use in the control. + +|Class|Description| +|-----------|-----------------| +||Used with text-based values. Generated automatically when binding to numbers and strings.| +||Used with and values. Generated automatically when binding to values of these types.| +||Used to display images. Generated automatically when binding to byte arrays, objects, or objects.| +||Used to display buttons in cells. Not automatically generated when binding. Typically used as unbound columns.| +||Used to display drop-down lists in cells. Not automatically generated when binding. Typically data-bound manually.| +||Used to display links in cells. Not automatically generated when binding. Typically data-bound manually.| +|Your custom column type|You can create your own column class by inheriting the class or any of its derived classes to provide custom appearance, behavior, or hosted controls. For more information, see [How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance](customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md)| + + These column types are described in more detail in the following sections. + +## DataGridViewTextBoxColumn + The is a general-purpose column type for use with text-based values such as numbers and strings. In editing mode, a control is displayed in the active cell, enabling users to modify the cell value. + + Cell values are automatically converted to strings for display. Values entered or modified by the user are automatically parsed to create a cell value of the appropriate data type. You can customize these conversions by handling the and events of the control. + + The cell value data type of a column is specified in the property of the column. + +## DataGridViewCheckBoxColumn + The is used with and values. values display as two-state or three-state check boxes, depending on the value of the property. When the column is bound to values, the property value is `true` by default. + + Typically, check box cell values are intended either for storage, like any other data, or for performing bulk operations. If you want to respond immediately when users click a check box cell, you can handle the event, but this event occurs before the cell value is updated. If you need the new value at the time of the click, one option is to calculate what the expected value will be based on the current value. Another approach is to commit the change immediately, and handle the event to respond to it. To commit the change when the cell is clicked, you must handle the event. In the handler, if the current cell is a check box cell, call the method and pass in the value. + +## DataGridViewImageColumn + The is used to display images. Image columns can be populated automatically from a data source, populated manually for unbound columns, or populated dynamically in a handler for the event. + + The automatic population of an image column from a data source works with byte arrays in a variety of image formats, including all formats supported by the class and the OLE Picture format used by Microsoft® Access and the Northwind sample database. + + Populating an image column manually is useful when you want to provide the functionality of a , but with a customized appearance. You can handle the event to respond to clicks within an image cell. + + Populating the cells of an image column in a handler for the event is useful when you want to provide images for calculated values or values in non-image formats. For example, you may have a "Risk" column with string values such as `"high"`, `"middle"`, and `"low"` that you want to display as icons. Alternately, you may have an "Image" column that contains the locations of images that must be loaded rather than the binary content of the images. + +## DataGridViewButtonColumn + With the , you can display a column of cells that contain buttons. This is useful when you want to provide an easy way for your users to perform actions on particular records, such as placing an order or displaying child records in a separate window. + + Button columns are not generated automatically when data-binding a control. To use button columns, you must create them manually and add them to the collection returned by the property. + + You can respond to user clicks in button cells by handling the event. + +## DataGridViewComboBoxColumn + With the , you can display a column of cells that contain drop-down list boxes. This is useful for data entry in fields that can only contain particular values, such as the Category column of the Products table in the Northwind sample database. + + You can populate the drop-down list used for all cells the same way you would populate a drop-down list, either manually through the collection returned by the property, or by binding it to a data source through the , , and properties. For more information, see [ComboBox Control](combobox-control-windows-forms.md). + + You can bind the actual cell values to the data source used by the control by setting the property of the . + + Combo box columns are not generated automatically when data-binding a control. To use combo box columns, you must create them manually and add them to the collection returned by the property. + +## DataGridViewLinkColumn + With the , you can display a column of cells that contain hyperlinks. This is useful for URL values in the data source or as an alternative to the button column for special behaviors such as opening a window with child records. + + Link columns are not generated automatically when data-binding a control. To use link columns, you must create them manually and add them to the collection returned by the property. + + You can respond to user clicks on links by handling the event. This event is distinct from the and events, which occur when a user clicks anywhere in a cell. + + The class provides several properties for modifying the appearance of links before, during, and after they are clicked. + +## See also + +- +- +- +- +- +- +- +- +- [DataGridView Control](datagridview-control-windows-forms.md) +- [How to: Display Images in Cells of the Windows Forms DataGridView Control](how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md) +- [How to: Work with Image Columns in the Windows Forms DataGridView Control](how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md) +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/combobox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/combobox-control-overview-windows-forms.md new file mode 100644 index 0000000000..b38686d846 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/combobox-control-overview-windows-forms.md @@ -0,0 +1,30 @@ +--- +title: "ComboBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ComboBox" +helpviewer_keywords: + - "drop-down lists [Windows Forms], Windows Forms" + - "ComboBox control [Windows Forms], about ComboBox control" + - "drop-down lists [Windows Forms], ComboBox control" + - "combo boxes [Windows Forms], about combo boxes" +ms.assetid: a58b393f-a614-45d1-8961-857a024b5acd +--- +# ComboBox Control Overview (Windows Forms) +The Windows Forms control is used to display data in a drop-down combo box. By default, the control appears in two parts: the top part is a text box that allows the user to type a list item. The second part is a list box that displays a list of items from which the user can select one. For more information on other styles of combo box, see [When to Use a Windows Forms ComboBox Instead of a ListBox](when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md). + + The property returns an integer value that corresponds to the selected list item. You can programmatically change the selected item by changing the value in code; the corresponding item in the list will appear in the text box portion of the combo box. If no item is selected, the value is -1. If the first item in the list is selected, then the value is 0. The property is similar to , but returns the item itself, usually a string value. The property reflects the number of items in the list, and the value of the property is always one more than the largest possible value because is zero-based. + + To add or delete items in a control, use the , , or method. Alternatively, you can add items to the list by using the property in the designer. + +## See also + +- +- [ListBox Control Overview](listbox-control-overview-windows-forms.md) +- [When to Use a Windows Forms ComboBox Instead of a ListBox](when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md) +- [How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control](add-and-remove-items-from-a-wf-combobox.md) +- [How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control](sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md) +- [How to: Access Specific Items in a Windows Forms ComboBox, ListBox, or CheckedListBox Control](access-specific-items-in-a-wf-combobox-listbox-or-checkedlistbox.md) +- [How to: Bind a Windows Forms ComboBox or ListBox Control to Data](how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) +- [How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control](create-a-lookup-table-for-a-wf-combobox-listbox.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/combobox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/combobox-control-windows-forms.md new file mode 100644 index 0000000000..d162065ac1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/combobox-control-windows-forms.md @@ -0,0 +1,34 @@ +--- +title: "ComboBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "drop-down lists [Windows Forms], Windows Forms" + - "list controls [Windows Forms], Windows Forms" + - "combo boxes [Windows Forms], Windows Forms controls" + - "combo boxes" + - "list items [Windows Forms], Windows Forms controls that display" + - "drop-down lists [Windows Forms], ComboBox control" + - "ComboBox control [Windows Forms]" +ms.assetid: 86a1bbc3-0469-4290-91c5-99ff61b739ff +--- +# ComboBox Control (Windows Forms) +The Windows Forms `ComboBox` control is used to display data in a drop-down combo box. By default, the `ComboBox` control appears in two parts: the top part is a text box that allows the user to type a list item. The second part is a list box that displays a list of items from which the user can select one. + +## In This Section + [ComboBox Control Overview](combobox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Create Variable Sized Text in a ComboBox Control](how-to-create-variable-sized-text-in-a-combobox-control.md) + Demonstrates custom drawing of text in a `ComboBox` control. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) + Provides a list of things you can do with list boxes, combo boxes, and checked list boxes. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/considerations-when-hosting-an-activex-control-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/considerations-when-hosting-an-activex-control-on-a-windows-form.md new file mode 100644 index 0000000000..017af200e7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/considerations-when-hosting-an-activex-control-on-a-windows-form.md @@ -0,0 +1,31 @@ +--- +title: "Considerations When Hosting an ActiveX Control on a Windows Form" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, ActiveX controls" + - "ActiveX controls [Windows Forms], hosting" + - "Windows Forms, ActiveX controls" + - "Windows Forms, hosting ActiveX controls" + - "ActiveX controls [Windows Forms], adding" +ms.assetid: 2509302d-a74e-484f-9890-2acdbfa67a68 +--- +# Considerations When Hosting an ActiveX Control on a Windows Form +Although Windows Forms have been optimized to host Windows Forms controls, you can still use ActiveX controls. Keep the following considerations in mind when planning an application that uses ActiveX controls: + +- **Security** The common language runtime has been enhanced with regard to code access security. Applications featuring Windows Forms can run in a fully trusted environment without issue and in a semi-trusted environment with most of the functionality accessible. Windows Forms controls can be hosted in a browser with no complications. However, ActiveX controls on Windows Forms cannot take advantage of these security enhancements. Running an ActiveX control requires unmanaged code permission, which is set with the property. For more information about security and unmanaged code permission, see . + +- **Total Cost of Ownership** ActiveX controls added to a Windows Form are deployed with that Windows Form in their entirety, which can add significantly to the size of the file(s) created. Additionally, using ActiveX controls on Windows Forms requires writing to the registry. This is more invasive to a user's computer than Windows Forms controls, which do not require this. + + > [!NOTE] + > Working with an ActiveX control requires the use of a COM interop wrapper. For more information, see [COM Interoperability in Visual Basic and Visual C#](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/com-interop/com-interoperability-in-net-framework-applications). + + > [!NOTE] + > If the name of a member of the ActiveX control matches a name defined in the .NET Framework, then the ActiveX Control Importer will prefix the member name with **Ctl** when it creates the derived class. For example, if your ActiveX control has a member named **Layout**, it is renamed **CtlLayout** in the AxHost-derived class because the **Layout** event is defined within the .NET Framework. + +## See also + +- [How to: Add ActiveX Controls to Windows Forms](how-to-add-activex-controls-to-windows-forms.md) +- [Code Access Security](https://docs.microsoft.com/dotnet/framework/misc/code-access-security) +- [Controls and Programmable Objects Compared in Various Languages and Libraries](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/0061wezk(v=vs.100)) +- [Putting Controls on Windows Forms](putting-controls-on-windows-forms.md) +- [Windows Forms Controls](index.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/constituent-controls.md b/dotnet-desktop-guide/framework/winforms/controls/constituent-controls.md new file mode 100644 index 0000000000..3ca0d5780e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/constituent-controls.md @@ -0,0 +1,46 @@ +--- +title: "Constituent Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], constituent controls" + - "constituent controls [Windows Forms]" + - "user controls [Windows Forms], constituent controls" +ms.assetid: 5565e720-198b-4bbd-a2bd-c447ba641798 +--- +# Constituent Controls +The controls that make up a user control, or *constituent controls* as they are termed, are relatively inflexible when it comes to custom graphics rendering. All Windows Forms controls handle their own rendering through their own method. Because this method is protected, it is not accessible to the developer, and thus cannot be prevented from executing when the control is painted. This does not mean, however, that you cannot add code to affect the appearance of constituent controls. Additional rendering can be accomplished by adding an event handler. For example, suppose you were authoring a with a button named `MyButton`. If you wished to have additional rendering beyond what was provided by the , you would add code to your user control similar to the following: + +```vb +Public Sub MyPaint(ByVal sender as Object, e as PaintEventArgs) Handles _ + MyButton.Paint + 'Additional rendering code goes here +End Sub +``` + +```csharp +// Add the event handler to the button's Paint event. +MyButton.Paint += + new System.Windows.Forms.PaintEventHandler (this.MyPaint); +// Create the custom painting method. +protected void MyPaint (object sender, +System.Windows.Forms.PaintEventArgs e) +{ + // Additional rendering code goes here. +} +``` + +> [!NOTE] +> Some Windows Forms controls, such as , are painted directly by Windows. In these instances, the method is never called, and thus the above example will never be called. + + This creates a method that executes every time the `MyButton.Paint` event executes, thereby adding additional graphical representation to your control. Note that this does not prevent the execution of `MyButton.OnPaint`, and thus all of the painting usually performed by a button will still be performed in addition to your custom painting. For details about GDI+ technology and custom rendering, see the [Creating Graphical Images with GDI+](../advanced/how-to-create-graphics-objects-for-drawing.md). If you wish to have a unique representation of your control, your best course of action is to create an inherited control, and to write custom rendering code for it. For details, see [User-Drawn Controls](user-drawn-controls.md). + +## See also + +- +- +- [User-Drawn Controls](user-drawn-controls.md) +- [How to: Create Graphics Objects for Drawing](../advanced/how-to-create-graphics-objects-for-drawing.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/contextmenu-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/contextmenu-component-overview-windows-forms.md new file mode 100644 index 0000000000..5f624bd1bd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/contextmenu-component-overview-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "ContextMenu Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ContextMenu" +helpviewer_keywords: + - "ContextMenu component [Windows Forms], about ContextMenu component" + - "context menus [Windows Forms], ContextMenu component" + - "shortcut menus [Windows Forms], ContextMenu component" +ms.assetid: 49d6398f-d3c4-4679-84fa-1de07b68b05e +--- +# ContextMenu Component Overview (Windows Forms) +> [!IMPORTANT] +> Although and replace and add functionality to the and controls of previous versions, and are retained for both backward compatibility and future use if you choose. + + With the Windows Forms component, you can provide users with an easily accessible shortcut menu of frequently used commands that are associated with the selected object. The items in a shortcut menu are frequently a subset of the items from main menus that appear elsewhere in the application. A user can typically access a shortcut menu by right-clicking the mouse. On Windows Forms, shortcut menus are associated with controls. + +## Key Properties + You can associate a shortcut menu with a control by setting the control's property to the component. A single shortcut menu can be associated with multiple controls, but each control can have only one shortcut menu. + + The key property of the component is the property. You can add menu items by programmatically creating objects and adding them to the of the shortcut menu. Because the items in a shortcut menu are usually drawn from other menus, you will most frequently add items to a shortcut menu by copying them. + +## See also + +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/contextmenu-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/contextmenu-component-windows-forms.md new file mode 100644 index 0000000000..62d2f4e262 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/contextmenu-component-windows-forms.md @@ -0,0 +1,38 @@ +--- +title: "ContextMenu Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "menus [Windows Forms], shortcut menus" + - "Windows Forms, menus" + - "pop-up menus" + - "ContextMenu component [Windows Forms]" + - "menus [Windows Forms], context menus" + - "context menus [Windows Forms], for Windows Forms" + - "shortcut menus [Windows Forms], ContextMenu component" +ms.assetid: 9b93ccbc-c0fe-44a2-968e-faac25971831 +--- +# ContextMenu Component (Windows Forms) +> [!NOTE] +> Although `MenuStrip` and `ContextMenuStrip` replace and add functionality to the and controls of previous versions, and are retained for both backward compatibility and future use if you choose. + + The Windows Forms `ContextMenu` component is used to provide users with an easily accessible shortcut menu of frequently used commands that are associated with the selected object. The items in a shortcut menu are frequently a subset of the items from main menus that appear elsewhere in the application. Shortcut menus are usually available by right-clicking the mouse. On Windows Forms they are associated with other controls. + +## In This Section + [ContextMenu Component Overview](contextmenu-component-overview-windows-forms.md) + Introduces the general concepts of the `ContextMenu` component, which allows users to create menus of frequently used commands associated with a selected object. + + [How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component](add-and-remove-menu-items-with-wf-contextmenu-component.md) + Explains how to add and remove shortcut menu items in Windows Forms. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/contextmenustrip-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/contextmenustrip-control-overview.md new file mode 100644 index 0000000000..f36d22ba96 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/contextmenustrip-control-overview.md @@ -0,0 +1,34 @@ +--- +title: "ContextMenuStrip Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ContextMenuStrip" +helpviewer_keywords: + - "context menus [Windows Forms], ContextMenuStrip control [Windows Forms]" + - "shortcut menus [Windows Forms], ContextMenuStrip control [Windows Forms]" + - "ContextMenuStrip control [Windows Forms], about ContextMenuStrip control" +ms.assetid: 9787cdb3-88f1-4198-972f-eefd9524ce39 +--- +# ContextMenuStrip Control Overview +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for backward compatibility and future use if you choose. + + Shortcut menus, also called context menus, appear at the mouse position when the user clicks the right mouse button. Shortcut *menus* provide options for the client area or the control at the mouse pointer location. + + The control is designed to work seamlessly with the new and related controls, but you can associate a with other controls just as easily. + + The following table shows the important companion classes. + +|Class|Description| +|-----------|-----------------| +||Represents a selectable option displayed on a or .| +||Represents a control that enables the user to select a single item from a list that is displayed when the user clicks a or a higher-level menu item.| +||Provides basic functionality for controls derived from that display drop-down items when clicked.| + +## See also + +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/contextmenustrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/contextmenustrip-control.md new file mode 100644 index 0000000000..8541ced07e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/contextmenustrip-control.md @@ -0,0 +1,46 @@ +--- +title: "ContextMenuStrip Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "context menus" + - "ContextMenuStrip control [Windows Forms]" + - "shortcut menus" +ms.assetid: 76e070b2-65d7-457f-8300-d104e4e01e5e +--- +# ContextMenuStrip Control +The control provides a shortcut menu that you associate with a control. + +## In This Section + [ContextMenuStrip Control Overview](contextmenustrip-control-overview.md) + Explains what the control is and its key features and properties. + + [How to: Associate a ContextMenuStrip with a Control](how-to-associate-a-contextmenustrip-with-a-control.md) + Describes making a the shortcut menu for a specific control. + + [How to: Add Menu Items to a ContextMenuStrip](how-to-add-menu-items-to-a-contextmenustrip.md) + Describes how to add selectable options to a . + + [How to: Configure ContextMenuStrip Check Margins and Image Margins](how-to-configure-contextmenustrip-check-margins-and-image-margins.md) + Describes how to customize a by setting check and image margin properties in various ways. + + [How to: Enable Check Margins and Image Margins in ContextMenuStrip Controls](how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md) + Describes how to turn check margins on and off. + + [How to: Handle the ContextMenuStrip Opening Event](how-to-handle-the-contextmenustrip-opening-event.md) + Describes how to customize the behavior of a control by handling the event. + + Also see [ContextMenuStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233646(v=vs.100)) or [ContextMenuStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233641(v=vs.100)). + +## Reference + + Describes the features of the class, which provides a menu system for a form. + + + Describes the features of the , which represents a shortcut menu. + + + Describes the features of the class, which represents a selectable option displayed on a or . + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/control-type-recommendations.md b/dotnet-desktop-guide/framework/winforms/controls/control-type-recommendations.md new file mode 100644 index 0000000000..85e133bbb5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/control-type-recommendations.md @@ -0,0 +1,81 @@ +--- +title: "Control Type Recommendations" +ms.date: "03/30/2017" +helpviewer_keywords: + - "inheritance [Windows Forms], Windows Forms custom controls" + - "user controls [Windows Forms], when to use" + - "custom controls [Windows Forms], types" + - "controls [Windows Forms], creating" +ms.assetid: 5235fe9d-c36a-4c08-ae76-6cb90b50085e +--- +# Control Type Recommendations + +The .NET Framework gives you power to develop and implement new controls. In addition to the familiar user control, you will now find that you are able to write custom controls that perform their own painting, and are even able to extend the functionality of existing controls through inheritance. Deciding which type of control to create can be confusing. This section highlights the differences between the various types of controls from which you can inherit, and gives considerations regarding the type to choose for your project. + +> [!NOTE] +> If you want to author a control to use on Web Forms, see [Developing Custom ASP.NET Server Controls](https://docs.microsoft.com/previous-versions/aspnet/zt27tfhy(v=vs.100)). + +## Inheriting from a Windows Forms Control + +You can derive an inherited control from any existing Windows Forms control. This approach allows you to retain all of the inherent functionality of a Windows Forms control, and to then extend that functionality by adding custom properties, methods, or other functionality. For example, you might create a control derived from that can accept only numbers and automatically converts input into a value. Such a control might contain validation code that was called whenever the text in the text box changed, and could have an additional property, Value. In some controls, you can also add a custom appearance to the graphical interface of your control by overriding the method of the base class. + + Inherit from a Windows Forms control if: + +- Most of the functionality you need is already identical to an existing Windows Forms control. + +- You do not need a custom graphical interface, or you want to design a new graphical front end for an existing control. + +## Inheriting from the UserControl Class + +A user control is a collection of Windows Forms controls encapsulated into a common container. The container holds all of the inherent functionality associated with each of the Windows Forms controls and allows you to selectively expose and bind their properties. An example of a user control might be a control built to display customer address data from a database. This control would include several textboxes to display each field, and button controls to navigate through the records. Data-binding properties could be selectively exposed, and the entire control could be packaged and reused from application to application. + +Inherit from the class if: + +- You want to combine the functionality of several Windows Forms controls into a single reusable unit. + +## Inheriting from the Control Class + +Another way to create a control is to create one substantially from scratch by inheriting from . The class provides all of the basic functionality required by controls (for example, events), but no control-specific functionality or graphical interface. Creating a control by inheriting from the class requires a lot more thought and effort than inheriting from user control or an existing Windows Forms control. The author must write code for the event of the control, as well as any functionality specific code that is needed. Greater flexibility is allowed, however, and you can custom tailor a control to suit your exact needs. An example of a custom control is a clock control that duplicates the look and action of an analog clock. Custom painting would be invoked to cause the hands of the clock to move in response to events from an internal timer component. + +Inherit from the class if: + +- You want to provide a custom graphical representation of your control. + +- You need to implement custom functionality that is not available through standard controls. + +## Related articles + +- [How to: Display a Control in the Choose Toolbox Items Dialog Box](how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md) + +- [Walkthrough: Serializing Collections of Standard Types with the DesignerSerializationVisibilityAttribute](serializing-collections-designerserializationvisibilityattribute.md) + +- [Walkthrough: Inheriting from a Windows Forms Control](walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md) + +- [How to: Provide a Toolbox Bitmap for a Control](how-to-provide-a-toolbox-bitmap-for-a-control.md) + +- [How to: Inherit from Existing Windows Forms Controls](how-to-inherit-from-existing-windows-forms-controls.md) + +- [Walkthrough: Debugging Custom Windows Forms Controls at Design Time](walkthrough-debugging-custom-windows-forms-controls-at-design-time.md) + +- [How to: Inherit from the Control Class](how-to-inherit-from-the-control-class.md) + +- [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md) + +- [How to: Align a Control to the Edges of Forms at Design Time](how-to-align-a-control-to-the-edges-of-forms-at-design-time.md) + +- [How to: Inherit from the UserControl Class](how-to-inherit-from-the-usercontrol-class.md) + +- [How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md) + +- [How to: Author Composite Controls](how-to-author-composite-controls.md) + +- [Walkthrough: Authoring a Composite Control](walkthrough-authoring-a-composite-control-with-visual-csharp.md) + +- [Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md) + +- [How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/307hck25(v=vs.120)) + +## See also + +- [How to: Develop a Simple Windows Forms Control](how-to-develop-a-simple-windows-forms-control.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/controls-to-use-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/controls-to-use-on-windows-forms.md new file mode 100644 index 0000000000..689be23c3c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/controls-to-use-on-windows-forms.md @@ -0,0 +1,232 @@ +--- +title: Controls to Use +description: Learn about controls and components that can be used on Windows Forms. You can also add ActiveX and custom controls to Windows Forms. +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms]" + - "Windows Forms controls, list of" +ms.assetid: dec51976-eae0-4398-a537-20bca7974722 +--- +# Controls to Use on Windows Forms +The following is an alphabetic list of controls and components that can be used on Windows Forms. In addition to the Windows Forms controls covered in this section, you can add ActiveX and custom controls to Windows Forms. If you do not find the control you need listed here, you can also create your own. For details, see [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md). For more information about choosing the control you need, see [Windows Forms Controls by Function](windows-forms-controls-by-function.md). + +> [!NOTE] +> Visual Basic controls are based on classes provided by the .NET Framework. + +## In This Section + [Windows Forms Controls by Function](windows-forms-controls-by-function.md) + Lists and describes Windows Forms controls based on the .NET Framework. + + [Controls with Built-In Owner-Drawing Support](controls-with-built-in-owner-drawing-support.md) + Describes how to alter aspects of a control's appearance that are not available through properties. + + [BackgroundWorker Component](backgroundworker-component.md) + Enables a form or control to run an operation asynchronously. + + [BindingNavigator Control](bindingnavigator-control-windows-forms.md) + Provides the navigation and manipulation user interface (UI) for controls that are bound to data. + + [BindingSource Component](bindingsource-component.md) + Encapsulates a data source for binding to controls. + + [Button Control](button-control-windows-forms.md) + Presents a standard button that the user can click to perform actions. + + [CheckBox Control](checkbox-control-windows-forms.md) + Indicates whether a condition is on or off. + + [CheckedListBox Control](checkedlistbox-control-windows-forms.md) + Displays a list of items with a check box next to each item. + + [ColorDialog Component](colordialog-component-windows-forms.md) + Allows the user to select a color from a palette in a pre-configured dialog box and to add custom colors to that palette. + + [ComboBox Control](combobox-control-windows-forms.md) + Displays data in a drop-down combo box. + + [ContextMenu Component](contextmenu-component-windows-forms.md) + Provides users with an easily accessible menu of frequently used commands that are associated with the selected object. Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if so desired. + + [ContextMenuStrip Control](contextmenustrip-control.md) + Represents a shortcut menu. Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if so desired. + + [DataGrid Control](datagrid-control-windows-forms.md) + Displays tabular data from a dataset and allows for updates to the data source. + + [DataGridView Control](datagridview-control-windows-forms.md) + Provides a flexible, extensible system for displaying and editing tabular data. + + [DateTimePicker Control](datetimepicker-control-windows-forms.md) + Allows the user to select a single item from a list of dates or times. + + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Describes a set of controls that allow users to perform standard interactions with the application or system. + + [DomainUpDown Control](domainupdown-control-windows-forms.md) + Displays text strings that a user can browse through and select from. + + [ErrorProvider Component](errorprovider-component-windows-forms.md) + Displays error information to the user in a non-intrusive way. + + [FileDialog Class](filedialog-class.md) + Provides base-class functionality for file dialog boxes. + + [FlowLayoutPanel Control](flowlayoutpanel-control-windows-forms.md) + Represents a panel that dynamically lays out its contents horizontally or vertically. + + [FolderBrowserDialog Component](folderbrowserdialog-component-windows-forms.md) + Displays an interface with which users can browse and select a directory or create a new one. + + [FontDialog Component](fontdialog-component-windows-forms.md) + Exposes the fonts that are currently installed on the system. + + [GroupBox Control](groupbox-control-windows-forms.md) + Provides an identifiable grouping for other controls. + + [HelpProvider Component](helpprovider-component-windows-forms.md) + Associates an HTML Help file with a Windows-based application. + + [HScrollBar and VScrollBar Controls](hscrollbar-and-vscrollbar-controls-windows-forms.md) + Provide navigation through a list of items or a large amount of information by scrolling either horizontally or vertically within an application or control. + + [ImageList Component](imagelist-component-windows-forms.md) + Displays images on other controls. + + [Label Control](label-control-windows-forms.md) + Displays text that cannot be edited by the user. + + [LinkLabel Control](linklabel-control-windows-forms.md) + Allows you to add Web-style links to Windows Forms applications. + + [ListBox Control](listbox-control-windows-forms.md) + Allows the user to select one or more items from a predefined list. + + [ListView Control](listview-control-windows-forms.md) + Displays a list of items with icons, in the manner of Windows Explorer. + + [MainMenu Component](mainmenu-component-windows-forms.md) + Displays a menu at run time. Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if you choose. + + [MaskedTextBox Control](maskedtextbox-control-windows-forms.md) + Constrains the format of user input in a form. + + [MenuStrip Control](menustrip-control-windows-forms.md) + Provides a menu system for a form. Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if you choose. + + [MonthCalendar Control](monthcalendar-control-windows-forms.md) + Presents an intuitive graphical interface for users to view and set date information. + + [NotifyIcon Component](notifyicon-component-windows-forms.md) + Displays icons for processes that run in the background and would not otherwise have user interfaces. + + [NumericUpDown Control](numericupdown-control-windows-forms.md) + Displays numerals that a user can browse through and select from. + + [OpenFileDialog Component](openfiledialog-component-windows-forms.md) + Allows users to open files by using a pre-configured dialog box. + + [PageSetupDialog Component](pagesetupdialog-component-windows-forms.md) + Sets page details for printing through a pre-configured dialog box. + + [Panel Control](panel-control-windows-forms.md) + Provide an identifiable grouping for other controls, and allows for scrolling. + + [PictureBox Control](picturebox-control-windows-forms.md) + Displays graphics in bitmap, GIF, JPEG, metafile, or icon format. + + [PrintDialog Component](printdialog-component-windows-forms.md) + Selects a printer, chooses the pages to print, and determines other print-related settings. + + [PrintDocument Component](printdocument-component-windows-forms.md) + Sets the properties that describe what to print, and prints the document in Windows-based applications. + + [PrintPreviewControl Control](printpreviewcontrol-control-windows-forms.md) + Allows you to create your own `PrintPreview` component or dialog box instead of using the pre-configured version. + + [PrintPreviewDialog Control](printpreviewdialog-control-windows-forms.md) + Displays a document as it will appear when it is printed. + + [ProgressBar Control](progressbar-control-windows-forms.md) + Graphically indicates the progress of an action towards completion. + + [RadioButton Control](radiobutton-control-windows-forms.md) + Presents a set of two or more mutually exclusive options to the user. + + [RichTextBox Control](richtextbox-control-windows-forms.md) + Allows users to enter, display, and manipulate text with formatting. + + [SaveFileDialog Component](savefiledialog-component-windows-forms.md) + Selects files to save and where to save them. + + [SoundPlayer Class](soundplayer-class.md) + Enables you to easily include sounds in your applications. + + [SplitContainer Control](splitcontainer-control-windows-forms.md) + Allows the user to resize a docked control. + + [Splitter Control](splitter-control-windows-forms.md) + Allows the user to resize a docked control (.NET Framework version 1.x). + + [StatusBar Control](statusbar-control-windows-forms.md) + Displays status information related to the control that has focus. Although replaces and extends the control of previous versions, is retained for both backward compatibility and future use if you choose. + + [StatusStrip Control](statusstrip-control.md) + Represents a Windows status bar control. Although replaces and extends the control of previous versions, is retained for both backward compatibility and future use if you choose. + + [TabControl Control](tabcontrol-control-windows-forms.md) + Displays multiple tabs that can contain pictures or other controls. + + [TableLayoutPanel Control](tablelayoutpanel-control-windows-forms.md) + Represents a panel that dynamically lays out its contents in a grid composed of rows and columns. + + [TextBox Control](textbox-control-windows-forms.md) + Allows editable, multiline input from the user. + + [Timer Component](timer-component-windows-forms.md) + Raises an event at regular intervals. + + [ToolBar Control](toolbar-control-windows-forms.md) + Displays menus and bitmapped buttons that activate commands. You can extend the functionality of the control and modify its appearance and behavior. Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if you choose. + + [ToolStrip Control](toolstrip-control-windows-forms.md) + Creates custom toolbars and menus in your Windows Forms applications. Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if you choose. + + [ToolStripContainer Control](toolstripcontainer-control.md) + Provides panels on each side of a form for docking, rafting, and arranging controls, and a central for traditional controls. + + [ToolStripPanel Control](toolstrippanel-control.md) + Provides one panel for docking, rafting and arranging controls. + + [ToolStripProgressBar Control Overview](toolstripprogressbar-control-overview.md) + Graphically indicates the progress of an action towards completion. The is typically contained in a . + + [ToolStripStatusLabel Control](toolstripstatuslabel-control.md) + Represents a panel in a control. + + [ToolTip Component](tooltip-component-windows-forms.md) + Displays text when the user points at other controls. + + [TrackBar Control](trackbar-control-windows-forms.md) + Allows navigation through a large amount of information or visually adjusting a numeric setting. + + [TreeView Control](treeview-control-windows-forms.md) + Displays a hierarchy of nodes that can be expanded or collapsed. + + [WebBrowser Control](webbrowser-control-windows-forms.md) + Hosts Web pages and provides Internet Web browsing capabilities to your application. + + [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) + Describes a set of controls used to provide users with a list of options to choose from. + +## Related Sections + [Windows Forms Controls](index.md) + Explains the use of Windows Forms controls, and describes important concepts for working with them. + + [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md) + Provides links to step-by-step topics, recommendations for which kind of control to create, and other information about creating your own control. + + [Controls and Programmable Objects Compared in Various Languages and Libraries](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/0061wezk(v=vs.100)) + Provides a table that maps controls in Visual Basic 6.0 to the corresponding control in Visual Basic .NET. Note that controls are now classes in the .NET Framework. + + [How to: Add ActiveX Controls to Windows Forms](how-to-add-activex-controls-to-windows-forms.md) + Describes how to use ActiveX controls on Windows Forms. diff --git a/dotnet-desktop-guide/framework/winforms/controls/controls-with-built-in-owner-drawing-support.md b/dotnet-desktop-guide/framework/winforms/controls/controls-with-built-in-owner-drawing-support.md new file mode 100644 index 0000000000..853905ff12 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/controls-with-built-in-owner-drawing-support.md @@ -0,0 +1,188 @@ +--- +title: "Controls with Built-In Owner-Drawing Support" +ms.date: "03/30/2017" +helpviewer_keywords: + - "drawing [Windows Forms], owner" + - "drawing [Windows Forms], custom" + - "controls [Windows Forms], changing appearance" + - "custom drawing" + - "owner drawing" +ms.assetid: 3823d01e-9610-43e6-864d-99f9b7c2b351 +--- +# Controls with Built-In Owner-Drawing Support +Owner drawing in Windows Forms, which is also known as custom drawing, is a technique for changing the visual appearance of certain controls. + +> [!NOTE] +> The word "control" in this topic is used to mean classes that derive from either or . + + Typically, Windows handles painting automatically by using property settings such as to determine the appearance of a control. With owner drawing, you take over the painting process, changing elements of appearance that are not available by using properties. For example, many controls let you set the color of the text that is displayed, but you are limited to a single color. Owner drawing enables you to do things like display part of the text in black and part in red. + + In practice, owner drawing is similar to drawing graphics on a form. For example, you could use graphics methods in a handler for the form's event to emulate a `ListBox` control, but you would have to write your own code to handle all user interaction. With owner drawing, the control uses your code to draw its contents but otherwise retains all its intrinsic capabilities. You can use graphics methods to draw each item in the control or to customize some aspects of each item while you use the default appearance for other aspects of each item. + +## Owner Drawing in Windows Forms Controls + To perform owner drawing in controls that support it, you will typically set one property and handle one or more events. + + Most controls that support owner drawing have an `OwnerDraw` or `DrawMode` property that indicates whether the control will raise its drawing-related event or events when it paints itself. + + Controls that do not have an `OwnerDraw` or `DrawMode` property include the `DataGridView` control, which provides drawing events that occur automatically, and the `ToolStrip` control, which is drawn using an external rendering class that has its own drawing-related events. + + There are many different kinds of drawing events, but a typical drawing event occurs in order to draw a single item within a control. The event handler receives an `EventArgs` object that contains information about the item being drawn and tools you can use to draw it. For example, this object typically contains the item's index number within its parent collection, a that indicates the item's display boundaries, and a object for calling paint methods. For some events, the `EventArgs` object provides additional information about the item and methods that you can call to paint some aspects of the item by default, such as the background or a focus rectangle. + + To create a reusable control that contains your owner-drawn customizations, create a new class that derives from a control class that supports owner drawing. Rather than handling drawing events, include your owner-drawing code in overrides for the appropriate `On`*EventName* method or methods in the new class. Make sure that you call the base class `On`*EventName* method or methods in this case so that users of your control can handle owner-drawing events and provide additional customization. + + The following Windows Forms controls support owner drawing in all versions of the .NET Framework: + +- + +- + +- (used by and ) + +- + + The following controls support owner drawing only in .NET Framework 2.0: + +- + +- + +- + + The following controls support owner drawing and are new in .NET Framework 2.0: + +- + +- + + The following sections provide additional details for each of these controls. + +### ListBox and ComboBox Controls + The and controls enable you to draw individual items in the control either all in one size, or in varying sizes. + +> [!NOTE] +> Although the control is derived from the control, it does not support owner drawing. + + To draw each item the same size, set the `DrawMode` property to and handle the `DrawItem` event. + + To draw each item using a different size, set the `DrawMode` property to and handle both the `MeasureItem` and `DrawItem` events. The `MeasureItem` event lets you indicate the size of an item before the `DrawItem` event occurs for that item. + + For more information, including code examples, see the following topics: + +- + +- + +- + +- + +- + +- + +- [How to: Create Variable Sized Text in a ComboBox Control](how-to-create-variable-sized-text-in-a-combobox-control.md) + +### MenuItem Component + The component represents a single menu item in a or component. + + To draw a , set its `OwnerDraw` property to `true` and handle its `DrawItem` event. To customize the size of the menu item before the `DrawItem` event occurs, handle the item's `MeasureItem` event. + + For more information, including code examples, see the following reference topics: + +- + +- + +- + +### TabControl Control + The control enables you to draw individual tabs in the control. Owner drawing affects only the tabs; the contents are not affected. + + To draw each tab in a , set the `DrawMode` property to and handle the `DrawItem` event. This event occurs once for each tab only when the tab is visible in the control. + + For more information, including code examples, see the following reference topics: + +- + +- + +### ToolTip Component + The component enables you to draw the entire ToolTip when it is displayed. + + To draw a , set its `OwnerDraw` property to `true` and handle its `Draw` event. To customize the size of the before the `Draw` event occurs, handle the `Popup` event and set the property in the event handler. + + For more information, including code examples, see the following reference topics: + +- + +- + +- + +### ListView Control + The control enables you to draw individual items, subitems, and column headers in the control. + + To enable owner drawing in the control, set the `OwnerDraw` property to `true`. + + To draw each item in the control, handle the `DrawItem` event. + + To draw each subitem or column header in the control when the property is set to , handle the `DrawSubItem` and `DrawColumnHeader` events. + + For more information, including code examples, see the following reference topics: + +- + +- + +- + +- + +### TreeView Control + The control enables you to draw individual nodes in the control. + + To draw only the text displayed in each node, set the `DrawMode` property to and handle the `DrawNode` event to draw the text. + + To draw all elements of each node, set the `DrawMode` property to and handle the `DrawNode` event to draw whichever elements you need, such as text, icons, check boxes, plus and minus signs, and lines connecting the nodes. + + For more information, including code examples, see the following reference topics: + +- + +- + +### DataGridView Control + The control enables you to draw individual cells and rows in the control. + + To draw individual cells, handle the `CellPainting` event. + + To draw individual rows or elements of rows, handle one or both of the `RowPrePaint` and `RowPostPaint` events. The `RowPrePaint` event occurs before the cells in a row are painted, and the `RowPostPaint` event occurs after the cells are painted. You can handle both events and the `CellPainting` event to paint row background, individual cells, and row foreground separately, or you can provide specific customizations where you need them and use the default display for other elements of the row. + + For more information, including code examples, see the following topics: + +- + +- + +- + +- [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) + +- [How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control](customize-the-appearance-of-rows-in-the-datagrid.md) + +### ToolStrip Control + and derived controls enable you to customize any aspect of their appearance. + + To provide custom rendering for controls, set the `Renderer` property of a , , , or to a `ToolStripRenderer` object and handle one or more of the many drawing events provided by the `ToolStripRenderer` class. Alternatively, set a `Renderer` property to an instance of your own class derived from `ToolStripRenderer`, , or that implements or overrides specific `On`*EventName* methods. + + For more information, including code examples, see the following topics: + +- + +- [How to: Create and Set a Custom Renderer for the ToolStrip Control in Windows Forms](create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md) + +- [How to: Custom Draw a ToolStrip Control](how-to-custom-draw-a-toolstrip-control.md) + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md new file mode 100644 index 0000000000..be5ae67ef5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md @@ -0,0 +1,28 @@ +--- +title: Create a Basic ToolStrip with Standard Items Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], creating" + - "toolbars [Windows Forms], creating" + - "toolbars [Windows Forms], adding items" + - "ToolStrip control [Windows Forms], adding standard items" +ms.assetid: 028deb1a-acf8-4911-979a-ba8431cd9d82 +--- +# How to: Create a Basic Windows Forms ToolStrip with Standard Items Using the Designer +The following procedure demonstrates how to create a and add seven controls that represent typical tasks. + +## To add standard items in the designer + +1. Create a control. + +2. In the upper right corner of the , click the smart task arrow to display the **ToolStrip Tasks** pane. + +3. In the **ToolStrip Tasks** pane, choose **Insert Standard Items**. + +## See also + +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control](toolstrip-control-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/create-a-lookup-table-for-a-wf-combobox-listbox.md b/dotnet-desktop-guide/framework/winforms/controls/create-a-lookup-table-for-a-wf-combobox-listbox.md new file mode 100644 index 0000000000..2c89f789b9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/create-a-lookup-table-for-a-wf-combobox-listbox.md @@ -0,0 +1,73 @@ +--- +title: Create a Lookup Table for ComboBox, ListBox, or CheckedListBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "CheckedListBox control [Windows Forms], creating lookup tables" + - "lookup tables" + - "list boxes [Windows Forms], lookup tables" + - "ListBox control [Windows Forms], lookup tables" + - "ComboBox control [Windows Forms], lookup table" + - "lookup tables [Windows Forms], creating for controls" + - "combo boxes [Windows Forms], lookup tables" + - "ListBox control [Windows Forms], creating lookup tables" +ms.assetid: 4ce35f12-1f4e-4317-92d1-af8686a8cfaa +--- +# How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control +Sometimes it is useful to display data in a user-friendly format on a Windows Form, but store the data in a format that is more meaningful to your program. For example, an order form for food might display the menu items by name in a list box. However, the data table recording the order would contain the unique ID numbers representing the food. The following tables show an example of how to store and display order-form data for food. + +### OrderDetailsTable + +|OrderID|ItemID|Quantity| +|-------------|------------|--------------| +|4085|12|1| +|4086|13|3| + +### ItemTable + +|ID|Name| +|--------|----------| +|12|Potato| +|13|Chicken| + + In this scenario, one table, **OrderDetailsTable**, stores the actual information you are concerned with displaying and saving. But to save space, it does so in a fairly cryptic fashion. The other table, **ItemTable**, contains only appearance-related information about which ID number is equivalent to which food name, and nothing about the actual food orders. + + The **ItemTable** is connected to the , , or control through three properties. The `DataSource` property contains the name of this table. The `DisplayMember` property contains the data column of that table that you want to display in the control (the food name). The `ValueMember` property contains the data column of that table with the stored information (the ID number). + + The **OrderDetailsTable** is connected to the control by its bindings collection, accessed through the property. When you add a binding object to the collection, you connect a control property to a specific data member (the column of ID numbers) in a data source (the **OrderDetailsTable**). When a selection is made in the control, this table is where the form input is saved. + +### To create a lookup table + +1. Add a , , or control to the form. + +2. Connect to your data source. + +3. Establish a data relation between the two tables. See [Introduction to DataRelation Objects](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/0k21zcyx(v=vs.120)). + +4. Set the following properties. They can be set in code or in the designer. + + |Property|Setting| + |--------------|-------------| + ||The table that contains information about which ID number is equivalent to which item. In the previous scenario, this is `ItemTable`.| + ||The column of the data source table that you want to display in the control. In the previous scenario, this is `"Name"` (to set in code, use quotation marks).| + ||The column of the data source table that contains the stored information. In the previous scenario, this is `"ID"` (to set in code, use quotation marks).| + +5. In a procedure, call the method of the class to bind the control's property to the table recording the form input. You can also do this in the Designer instead of in code, by accessing the control's property in the **Properties** window. In the previous scenario, this is `OrderDetailsTable`, and the column is `"ItemID"`. + + ```vb + ListBox1.DataBindings.Add("SelectedValue", OrderDetailsTable, "ItemID") + ``` + + ```csharp + listBox1.DataBindings.Add("SelectedValue", OrderDetailsTable, "ItemID"); + ``` + +## See also + +- [Data Binding and Windows Forms](../data-binding-and-windows-forms.md) +- [ListBox Control Overview](listbox-control-overview-windows-forms.md) +- [ComboBox Control Overview](combobox-control-overview-windows-forms.md) +- [CheckedListBox Control Overview](checkedlistbox-control-overview-windows-forms.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/create-a-master-detail-form-using-two-datagridviews.md b/dotnet-desktop-guide/framework/winforms/controls/create-a-master-detail-form-using-two-datagridviews.md new file mode 100644 index 0000000000..900a51fd17 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/create-a-master-detail-form-using-two-datagridviews.md @@ -0,0 +1,38 @@ +--- +title: Create a Master-Detail Form Using Two DataGridView Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], master/detail form" + - "parent-child tables [Windows Forms], displaying on Windows Forms" + - "master-details lists [Windows Forms], creating" +ms.assetid: 99f6e876-3f7f-4139-9063-e36587c95b02 +--- +# How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls +The following code example creates a master/detail form using two controls bound to two components. The data source is a that contains the `Customers` and `Orders` tables from the Northwind SQL Server sample database along with a that relates the two through the `CustomerID` column. + + One is bound to the parent `Customers` table in the data set. This data is displayed in the master control. The other is bound to the first data connector. The property of the second is set to the name. This causes the associated detail control to display the rows of the child `Orders` table that correspond to the current row in the master control. + + For a complete explanation of this code example, see [Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls](creating-a-master-detail-form-using-two-datagridviews.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMasterDetails#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewMasterDetails#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb#00)] + +## Compiling the Code + This example requires: + + References to the System, System.Data, System.Windows.Forms, and System.XML assemblies. + +## .NET Framework Security + Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + +## See also + +- +- +- [Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls](creating-a-master-detail-form-using-two-datagridviews.md) +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/create-a-multipane-user-interface-with-wf-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/create-a-multipane-user-interface-with-wf-using-the-designer.md new file mode 100644 index 0000000000..b076edabf1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/create-a-multipane-user-interface-with-wf-using-the-designer.md @@ -0,0 +1,43 @@ +--- +title: Create a Multipane User Interface Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "user interface [Windows Forms], multipane" + - "SplitContainer control [Windows Forms], using the designer" + - "multipane user interface" +ms.assetid: c3f9294d-a26c-4198-9242-f237f55f7573 +--- +# How to: Create a Multipane User Interface with Windows Forms Using the Designer +In the following procedure, you will create a multipane user interface that is similar to the one used in Microsoft Outlook, with a **Folder** list, a **Messages** pane, and a **Preview** pane. This arrangement is achieved chiefly through docking controls with the form. + + When you dock a control, you determine which edge of the parent container a control is fastened to. Thus, if you set the property to , the right edge of the control will be docked to the right edge of its parent control. Additionally, the docked edge of the control is resized to match that of its container control. For more information about how the property works, see [How to: Dock Controls on Windows Forms](how-to-dock-controls-on-windows-forms.md). + + This procedure focuses on arranging the and the other controls on the form, not on adding functionality to make the application mimic Microsoft Outlook. + + To create this user interface, you place all the controls within a control, which contains a control in the left-hand panel. The right-hand panel of the control contains a second control with a control above a control. These controls enable independent resizing of the other controls on the form. You can adapt the techniques in this procedure to craft custom user interfaces of your own. + +## To create an Outlook-style user interface at design time + +1. Create a new Windows Application project (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. Drag a control from the **Toolbox** to the form. In the **Properties** window, set the property to . + +3. Drag a control from the **Toolbox** to the left-hand panel of the control. In the **Properties** window, set the property to by clicking the left hand panel in the value editor shown when the down arrow is clicked. + +4. Drag another control from the **Toolbox**; place it in the right-hand panel of the control you added to your form. In the **Properties** window, set the property to and the property to . + +5. Drag a control from the **Toolbox** to the upper panel of the second control you added to your form. Set the property of the control to . + +6. Drag a control from the **Toolbox** to the lower panel of the second control. Set the property of the control to . + + At this point, if you press F5 to run the application, the form displays a three-part user interface, similar to that of Microsoft Outlook. + + > [!NOTE] + > When you put the mouse pointer over either of the splitters within the controls, you can resize the internal dimensions. + +At this point in application development, you have crafted a sophisticated user interface. The next step is proceeding with the programming of the application itself, perhaps by connecting the control and controls to some kind of data source. For more information about connecting controls to data, see [Data Binding and Windows Forms](../data-binding-and-windows-forms.md). + +## See also + +- +- [SplitContainer Control](splitcontainer-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md b/dotnet-desktop-guide/framework/winforms/controls/create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md new file mode 100644 index 0000000000..cc2451a817 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md @@ -0,0 +1,85 @@ +--- +title: "How to: Create and Set a Custom Renderer for the ToolStrip Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], custom rendering" + - "toolbars [Windows Forms], rendering" + - "examples [Windows Forms], toolbars" + - "ToolStrip control [Windows Forms], rendering" +ms.assetid: 88a804ba-679f-4ba3-938a-0dc396199c5b +--- +# How to: Create and Set a Custom Renderer for the ToolStrip Control in Windows Forms + controls give easy support to themes and styles. You can achieve completely custom appearance and behavior (look and feel) by setting either the property or the property to a custom renderer. + + You can assign renderers to each individual , , , or control, or you can use the property to affect all objects by setting the property to . + +> [!NOTE] +> returns only if the value of is not `null`. + +### To create a custom renderer + +1. Extend the class. + +2. Implement desired custom rendering by overriding appropriate *On…* members + + ```vb + Public Class RedTextRenderer + Inherits System.Windows.Forms.ToolStripRenderer + Protected Overrides Sub OnRenderItemText(ByVal e As _ + ToolStripItemTextRenderEventArgs) + e.TextColor = Color.Red + e.TextFont = New Font("Helvetica", 7, FontStyle.Bold) + MyBase.OnRenderItemText(e) + End Sub + End Class + ``` + + ```csharp + public class RedTextRenderer : _ + System.Windows.Forms.ToolStripRenderer + { + protected override void _ + OnRenderItemText(ToolStripItemTextRenderEventArgs e) + { + e.TextColor = Color.Red; + e.TextFont = new Font("Helvetica", 7, FontStyle.Bold); + base.OnRenderItemText(e); + } + } + ``` + +### To set the custom renderer to be the current renderer + +1. To set the custom renderer for one , set the property to the custom renderer. + + ```vb + toolStrip1.Renderer = New RedTextRenderer() + ``` + + ```csharp + toolStrip1.Renderer = new RedTextRenderer(); + ``` + +2. Or to set the custom renderer for all classes contained in your application: Set the property to the custom renderer and set the property to . + + ```vb + toolStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode + ToolStripManager.Renderer = New RedTextRenderer() + ``` + + ```csharp + toolStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode; + ToolStripManager.Renderer = new RedTextRenderer(); + ``` + +## See also + +- +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/create-master-details-lists-with-wf-datagrid-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/create-master-details-lists-with-wf-datagrid-control-using-the-designer.md new file mode 100644 index 0000000000..d6e73f7cd3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/create-master-details-lists-with-wf-datagrid-control-using-the-designer.md @@ -0,0 +1,51 @@ +--- +title: Create Master-Details Lists with DataGrid Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "master-details lists" + - "DataGrid control [Windows Forms], master-details lists" + - "related tables [Windows Forms], displaying in DataGrid control" +ms.assetid: 19438ba2-f687-4417-a2fb-ab1cd69d4ded +--- +# How to: Create Master-Details Lists with the Windows Forms DataGrid Control Using the Designer + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + If your contains a series of related tables, you can use two controls to display the data in a master-detail format. One is designated to be the master grid, and the second is designated to be the details grid. When you select an entry in the master list, all of the related child entries are shown in the details list. For example, if your contains a Customers table and a related Orders table, you would specify the Customers table to be the master grid and the Orders table to be the details grid. When a customer is selected from the master grid, all of the orders associated with that customer in the Orders table would be displayed in the details grid. + + The following procedure requires a **Windows Application** project (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +## To create a master-details list in the designer + +1. Add two controls to the form. For more information, see [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). In Visual Studio 2005, the control is not in the **Toolbox** by default. For more information, see [How to: Add Items to the Toolbox](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms165355(v=vs.100)). + + > [!NOTE] + > The following steps are not applicable to Visual Studio 2005, which uses the **Data Sources** window for design-time data binding. For more information, see [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio) and [How to: Display Related Data in a Windows Forms Application](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/57tx3hhe(v=vs.120)). + +2. Drag two or more tables from **Server Explorer** to the form. + +3. From the **Data** menu, select **Generate DataSet**. + +4. Set the relationships between the tables using the XML Designer. For details, see "How to: Create One-to-Many Relationships in XML Schemas and Datasets" on MSDN. + +5. Save the relationships by selecting **Save All** from the **File** menu. + +6. Configure the control that you want to designate the master grid, as follows: + + 1. Select the from the drop-down list in the property. + + 2. Select the master table (for example, "Customers") from the drop-down list in the property. + +7. Configure the control that you want to designate the details grid, as follows: + + 1. Select the from the drop-down list in the property. + + 2. Select the relationship (for example, "Customers.CustOrd") between the master and detail tables from the drop-down list in the property. In order to see the relationship, expand the node by clicking on the plus (**+**) sign next to the master table in the drop-down list. + +## See also + +- [DataGrid Control](datagrid-control-windows-forms.md) +- [DataGrid Control Overview](datagrid-control-overview-windows-forms.md) +- [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md) +- [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/controls/creating-a-master-detail-form-using-two-datagridviews.md b/dotnet-desktop-guide/framework/winforms/controls/creating-a-master-detail-form-using-two-datagridviews.md new file mode 100644 index 0000000000..2210a14565 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/creating-a-master-detail-form-using-two-datagridviews.md @@ -0,0 +1,82 @@ +--- +title: "Walkthrough: Create a master-detail form using two DataGridView controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], master/detail form" + - "parent-child tables [Windows Forms], displaying on Windows Forms" + - "master-details lists [Windows Forms], displaying on Windows Forms" + - "walkthroughs [Windows Forms], DataGridView control" +ms.assetid: c5fa29e8-47f7-4691-829b-0e697a691f36 +--- +# Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls + +One of the most common scenarios for using the control is the *master/detail* form, in which a parent/child relationship between two database tables is displayed. Selecting rows in the master table causes the detail table to update with the corresponding child data. + +Implementing a master/detail form is easy using the interaction between the control and the component. In this walkthrough, you will build the form using two controls and two components. The form will show two related tables in the Northwind SQL Server sample database: `Customers` and `Orders`. When you are finished, you will have a form that shows all the customers in the database in the master and all the orders for the selected customer in the detail . + +To copy the code in this topic as a single listing, see [How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls](create-a-master-detail-form-using-two-datagridviews.md). + +## Prerequisites + +In order to complete this walkthrough, you will need: + +- Access to a server that has the Northwind SQL Server sample database. + +## Creating the form + +#### To create a master/detail form + +1. Create a class that derives from and contains two controls and two components. The following code provides basic form initialization and includes a `Main` method. If you use the Visual Studio designer to create your form, you can use the designer generated code instead of this code, but be sure to use the names shown in the variable declarations here. + + [!code-csharp[System.Windows.Forms.DataGridViewMasterDetails#01](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs#01)] + [!code-vb[System.Windows.Forms.DataGridViewMasterDetails#01](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb#01)] + [!code-csharp[System.Windows.Forms.DataGridViewMasterDetails#02](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs#02)] + [!code-vb[System.Windows.Forms.DataGridViewMasterDetails#02](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb#02)] + +2. Implement a method in your form's class definition for handling the detail of connecting to the database. This example uses a `GetData` method that populates a object, adds a object to the data set, and binds the components. Be sure to set the `connectionString` variable to a value that is appropriate for your database. + + > [!IMPORTANT] + > Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + + [!code-csharp[System.Windows.Forms.DataGridViewMasterDetails#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs#20)] + [!code-vb[System.Windows.Forms.DataGridViewMasterDetails#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb#20)] + +3. Implement a handler for your form's event that binds the controls to the components and calls the `GetData` method. The following example includes code that resizes columns to fit the displayed data. + + [!code-csharp[System.Windows.Forms.DataGridViewMasterDetails#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewMasterDetails#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb#10)] + +## Testing the Application + +You can now test the form to make sure it behaves as expected. + +#### To test the form + +- Compile and run the application. + + You will see two controls, one above the other. On top are the customers from the Northwind `Customers` table, and at the bottom are the `Orders` corresponding to the selected customer. As you select different rows in the upper , the contents of the lower change accordingly. + +## Next Steps + +This application gives you a basic understanding of the control's capabilities. You can customize the appearance and behavior of the control in several ways: + +- Change border and header styles. For more information, see [How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control](change-the-border-and-gridline-styles-in-the-datagrid.md). + +- Enable or restrict user input to the control. For more information, see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md), and [How to: Make Columns Read-Only in the Windows Forms DataGridView Control](how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md). + +- Validate user input to the control. For more information, see [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md). + +- Handle very large data sets using virtual mode. For more information, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +- Customize the appearance of cells. For more information, see [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) and [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls](create-a-master-detail-form-using-two-datagridviews.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/creating-a-wf-control-design-time-features.md b/dotnet-desktop-guide/framework/winforms/controls/creating-a-wf-control-design-time-features.md new file mode 100644 index 0000000000..dfa48098fe --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/creating-a-wf-control-design-time-features.md @@ -0,0 +1,614 @@ +--- +title: Create a Control That Takes Advantage of Visual Studio Design-Time Features +description: Learn how to create a custom designer for a custom control in Windows Forms that takes advantage of design-time features. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms controls, creating" + - "design-time functionality [Windows Forms], Windows Forms" + - "DocumentDesigner class [Windows Forms]" + - "walkthroughs [Windows Forms], controls" +ms.assetid: 6f487c59-cb38-4afa-ad2e-95edacb1d626 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Create a control that takes advantage of design-time features + +The design-time experience for a custom control can be enhanced by authoring an associated custom designer. + +This article illustrates how to create a custom designer for a custom control. You'll implement a `MarqueeControl` type and an associated designer class called `MarqueeControlRootDesigner`. + +The `MarqueeControl` type implements a display similar to a theater marquee with animated lights and flashing text. + +The designer for this control interacts with the design environment to provide a custom design-time experience. With the custom designer, you can assemble a custom `MarqueeControl` implementation with animated lights and flashing text in many combinations. You can use the assembled control on a form like any other Windows Forms control. + +When you're finished with this walkthrough, your custom control will look something like the following: + +![The app showing a marquee saying Text and a Start and Stop buttons.](./media/creating-a-wf-control-design-time-features/demo-marquee-control.gif) + +For the complete code listing, see [How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/307hck25(v=vs.120)). + +## Prerequisites + +In order to complete this walkthrough, you'll need Visual Studio. + +## Create the project + +The first step is to create the application project. You will use this project to build the application that hosts the custom control. + +In Visual Studio, create a new Windows Forms Application project, and name it **MarqueeControlTest**. + +## Create the control library project + +1. Add a Windows Forms Control Library project to the solution. Name the project **MarqueeControlLibrary**. + +2. Using **Solution Explorer**, delete the project's default control by deleting the source file named "UserControl1.cs" or "UserControl1.vb", depending on your language of choice. + +3. Add a new item to the `MarqueeControlLibrary` project. Give the new source file a base name of **MarqueeControl**. + +4. Using **Solution Explorer**, create a new folder in the `MarqueeControlLibrary` project. + +5. Right-click the **Design** folder and add a new class. Name it **MarqueeControlRootDesigner**. + +6. You'll need to use types from the System.Design assembly, so add this reference to the `MarqueeControlLibrary` project. + +## Reference the Custom Control Project + +You will use the `MarqueeControlTest` project to test the custom control. The test project will become aware of the custom control when you add a project reference to the `MarqueeControlLibrary` assembly. + +In the `MarqueeControlTest` project, add a project reference to the `MarqueeControlLibrary` assembly. Be sure to use the **Projects** tab in the **Add Reference** dialog box instead of referencing the `MarqueeControlLibrary` assembly directly. + +## Define a Custom Control and Its Custom Designer + +Your custom control will derive from the class. This allows your control to contain other controls, and it gives your control a great deal of default functionality. + +Your custom control will have an associated custom designer. This allows you to create a unique design experience tailored specifically for your custom control. + +You associate the control with its designer by using the class. Because you are developing the entire design-time behavior of your custom control, the custom designer will implement the interface. + +### To define a custom control and its custom designer + +1. Open the `MarqueeControl` source file in the **Code Editor**. At the top of the file, import the following namespaces: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#220](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs#220)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#220](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb#220)] + +2. Add the to the `MarqueeControl` class declaration. This associates the custom control with its designer. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#240](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs#240)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#240](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb#240)] + +3. Open the `MarqueeControlRootDesigner` source file in the **Code Editor**. At the top of the file, import the following namespaces: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#520](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#520)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#520](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#520)] + +4. Change the declaration of `MarqueeControlRootDesigner` to inherit from the class. Apply the to specify the designer interaction with the **Toolbox**. + + > [!NOTE] + > The definition for the `MarqueeControlRootDesigner` class has been enclosed in a namespace called MarqueeControlLibrary.Design. This declaration places the designer in a special namespace reserved for design-related types. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#530](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#530)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#530](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#530)] + +5. Define the constructor for the `MarqueeControlRootDesigner` class. Insert a statement in the constructor body. This will be useful for debugging. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#540](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#540)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#540](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#540)] + +## Create an instance of your custom control + +1. Add a new item to the `MarqueeControlTest` project. Give the new source file a base name of **DemoMarqueeControl**. + +2. Open the `DemoMarqueeControl` file in the **Code Editor**. At the top of the file, import the `MarqueeControlLibrary` namespace: + + ```vb + Imports MarqueeControlLibrary + ``` + + ```csharp + using MarqueeControlLibrary; + ``` + +3. Change the declaration of `DemoMarqueeControl` to inherit from the `MarqueeControl` class. + +4. Build the project. + +5. Open Form1 in the Windows Forms Designer. + +6. Find the **MarqueeControlTest Components** tab in the **Toolbox** and open it. Drag a `DemoMarqueeControl` from the **Toolbox** onto your form. + +7. Build the project. + +## Set Up the Project for Design-Time Debugging + +When you're developing a custom design-time experience, it will be necessary to debug your controls and components. There is a simple way to set up your project to allow debugging at design time. For more information, see [Walkthrough: Debugging Custom Windows Forms Controls at Design Time](walkthrough-debugging-custom-windows-forms-controls-at-design-time.md). + +1. Right-click the `MarqueeControlLibrary` project and select **Properties**. + +2. In the **MarqueeControlLibrary Property Pages** dialog box, select the **Debug** page. + +3. In the **Start Action** section, select **Start External Program**. You will be debugging a separate instance of Visual Studio, so click the ellipsis (![The Ellipsis button (...) in the Properties window of Visual Studio](./media/visual-studio-ellipsis-button.png)) button to browse for the Visual Studio IDE. The name of the executable file is devenv.exe, and if you installed to the default location, its path is *%ProgramFiles(x86)%\Microsoft Visual Studio\2019\\\\Common7\IDE\devenv.exe*. + +4. Select **OK** to close the dialog box. + +5. Right-click the MarqueeControlLibrary project and select **Set as StartUp Project** to enable this debugging configuration. + +## Checkpoint + +You are now ready to debug the design-time behavior of your custom control. Once you've determined that the debugging environment is set up correctly, you'll test the association between the custom control and the custom designer. + +### To test the debugging environment and the designer association + +1. Open the MarqueeControlRootDesigner source file in the **Code Editor** and place a breakpoint on the statement. + +2. Press **F5** to start the debugging session. + + A new instance of Visual Studio is created. + +3. In the new instance of Visual Studio, open the MarqueeControlTest solution. You can easily find the solution by selecting **Recent Projects** from the **File** menu. The MarqueeControlTest.sln solution file will be listed as the most recently used file. + +4. Open the `DemoMarqueeControl` in the designer. + + The debugging instance of Visual Studio obtains focus and execution stops at your breakpoint. Press **F5** to continue the debugging session. + +At this point, everything is in place for you to develop and debug your custom control and its associated custom designer. The remainder of this article concentrates on the details of implementing features of the control and the designer. + +## Implement the Custom Control + +The `MarqueeControl` is a with a little bit of customization. It exposes two methods: `Start`, which starts the marquee animation, and `Stop`, which stops the animation. Because the `MarqueeControl` contains child controls that implement the `IMarqueeWidget` interface, `Start` and `Stop` enumerate each child control and call the `StartMarquee` and `StopMarquee` methods, respectively, on each child control that implements `IMarqueeWidget`. + +The appearance of the `MarqueeBorder` and `MarqueeText` controls is dependent on the layout, so `MarqueeControl` overrides the method and calls on child controls of this type. + +This is the extent of the `MarqueeControl` customizations. The run-time features are implemented by the `MarqueeBorder` and `MarqueeText` controls, and the design-time features are implemented by the `MarqueeBorderDesigner` and `MarqueeControlRootDesigner` classes. + +### To implement your custom control + +1. Open the `MarqueeControl` source file in the **Code Editor**. Implement the `Start` and `Stop` methods. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#260](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs#260)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#260](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb#260)] + +2. Override the method. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#270](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs#270)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#270](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb#270)] + +## Create a Child Control for Your Custom Control + +The `MarqueeControl` will host two kinds of child control: the `MarqueeBorder` control and the `MarqueeText` control. + +- `MarqueeBorder`: This control paints a border of "lights" around its edges. The lights flash in sequence, so they appear to be moving around the border. The speed at which the lights flash is controlled by a property called `UpdatePeriod`. Several other custom properties determine other aspects of the control's appearance. Two methods, called `StartMarquee` and `StopMarquee`, control when the animation starts and stops. + +- `MarqueeText`: This control paints a flashing string. Like the `MarqueeBorder` control, the speed at which the text flashes is controlled by the `UpdatePeriod` property. The `MarqueeText` control also has the `StartMarquee` and `StopMarquee` methods in common with the `MarqueeBorder` control. + +At design time, the `MarqueeControlRootDesigner` allows these two control types to be added to a `MarqueeControl` in any combination. + +Common features of the two controls are factored into an interface called `IMarqueeWidget`. This allows the `MarqueeControl` to discover any Marquee-related child controls and give them special treatment. + +To implement the periodic animation feature, you will use objects from the namespace. You could use objects, but when many `IMarqueeWidget` objects are present, the single UI thread may be unable to keep up with the animation. + +### To create a child control for your custom control + +1. Add a new class item to the `MarqueeControlLibrary` project. Give the new source file a base name of "IMarqueeWidget." + +2. Open the `IMarqueeWidget` source file in the **Code Editor** and change the declaration from `class` to `interface`: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/imarqueewidget.cs#2)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/imarqueewidget.vb#2)] + +3. Add the following code to the `IMarqueeWidget` interface to expose two methods and a property that manipulate the marquee animation: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/imarqueewidget.cs#3)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/imarqueewidget.vb#3)] + +4. Add a new **Custom Control** item to the `MarqueeControlLibrary` project. Give the new source file a base name of "MarqueeText." + +5. Drag a component from the **Toolbox** onto your `MarqueeText` control. This component will allow the `MarqueeText` control to update itself asynchronously. + +6. In the **Properties** window, set the component's `WorkerReportsProgress` and properties to **true**. These settings allow the component to periodically raise the event and to cancel asynchronous updates. + + For more information, see [BackgroundWorker Component](backgroundworker-component.md). + +7. Open the `MarqueeText` source file in the **Code Editor**. At the top of the file, import the following namespaces: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#120](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#120)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#120](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#120)] + +8. Change the declaration of `MarqueeText` to inherit from and to implement the `IMarqueeWidget` interface: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#130](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#130)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#130](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#130)] + +9. Declare the instance variables that correspond to the exposed properties, and initialize them in the constructor. The `isLit` field determines if the text is to be painted in the color given by the `LightColor` property. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#140](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#140)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#140](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#140)] + +10. Implement the `IMarqueeWidget` interface. + + The `StartMarquee` and `StopMarquee` methods invoke the component's and methods to start and stop the animation. + + The and attributes are applied to the `UpdatePeriod` property so it appears in a custom section of the Properties window called "Marquee." + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#150](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#150)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#150](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#150)] + +11. Implement the property accessors. You'll expose two properties to clients: `LightColor` and `DarkColor`. The and attributes are applied to these properties, so the properties appear in a custom section of the Properties window called "Marquee." + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#160](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#160)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#160](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#160)] + +12. Implement the handlers for the component's and events. + + The event handler sleeps for the number of milliseconds specified by `UpdatePeriod` then raises the event, until your code stops the animation by calling . + + The event handler toggles the text between its light and dark state to give the appearance of flashing. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#180](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#180)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#180](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#180)] + +13. Override the method to enable the animation. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#170](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs#170)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#170](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb#170)] + +14. Press **F6** to build the solution. + +## Create the MarqueeBorder Child Control + +The `MarqueeBorder` control is slightly more sophisticated than the `MarqueeText` control. It has more properties and the animation in the method is more involved. In principle, it is quite similar to the `MarqueeText` control. + +Because the `MarqueeBorder` control can have child controls, it needs to be aware of events. + +### To create the MarqueeBorder control + +1. Add a new **Custom Control** item to the `MarqueeControlLibrary` project. Give the new source file a base name of "MarqueeBorder." + +2. Drag a component from the **Toolbox** onto your `MarqueeBorder` control. This component will allow the `MarqueeBorder` control to update itself asynchronously. + +3. In the **Properties** window, set the component's `WorkerReportsProgress` and properties to **true**. These settings allow the component to periodically raise the event and to cancel asynchronous updates. For more information, see [BackgroundWorker Component](backgroundworker-component.md). + +4. In the **Properties** window, select the **Events** button. Attach handlers for the and events. + +5. Open the `MarqueeBorder` source file in the **Code Editor**. At the top of the file, import the following namespaces: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#20)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#20)] + +6. Change the declaration of `MarqueeBorder` to inherit from and to implement the `IMarqueeWidget` interface. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#30)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#30)] + +7. Declare two enumerations for managing the `MarqueeBorder` control's state: `MarqueeSpinDirection`, which determines the direction in which the lights "spin" around the border, and `MarqueeLightShape`, which determines the shape of the lights (square or circular). Place these declarations before the `MarqueeBorder` class declaration. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#97](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#97)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#97](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#97)] + +8. Declare the instance variables that correspond to the exposed properties, and initialize them in the constructor. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#40](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#40)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#40](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#40)] + +9. Implement the `IMarqueeWidget` interface. + + The `StartMarquee` and `StopMarquee` methods invoke the component's and methods to start and stop the animation. + + Because the `MarqueeBorder` control can contain child controls, the `StartMarquee` method enumerates all child controls and calls `StartMarquee` on those that implement `IMarqueeWidget`. The `StopMarquee` method has a similar implementation. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#50](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#50)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#50](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#50)] + +10. Implement the property accessors. The `MarqueeBorder` control has several properties for controlling its appearance. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#60](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#60)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#60](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#60)] + +11. Implement the handlers for the component's and events. + + The event handler sleeps for the number of milliseconds specified by `UpdatePeriod` then raises the event, until your code stops the animation by calling . + + The event handler increments the position of the "base" light, from which the light/dark state of the other lights is determined, and calls the method to cause the control to repaint itself. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#90](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#90)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#90](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#90)] + +12. Implement the helper methods, `IsLit` and `DrawLight`. + + The `IsLit` method determines the color of a light at a given position. Lights that are "lit" are drawn in the color given by the `LightColor` property, and those that are "dark" are drawn in the color given by the `DarkColor` property. + + The `DrawLight` method draws a light using the appropriate color, shape, and position. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#80](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#80)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#80](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#80)] + +13. Override the and methods. + + The method draws the lights along the edges of the `MarqueeBorder` control. + + Because the method depends on the dimensions of the `MarqueeBorder` control, you need to call it whenever the layout changes. To achieve this, override and call . + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#70](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#70)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#70](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#70)] + +## Create a Custom Designer to Shadow and Filter Properties + +The `MarqueeControlRootDesigner` class provides the implementation for the root designer. In addition to this designer, which operates on the `MarqueeControl`, you'll need a custom designer that is specifically associated with the `MarqueeBorder` control. This designer provides custom behavior that is appropriate in the context of the custom root designer. + +Specifically, the `MarqueeBorderDesigner` will "shadow" and filter certain properties on the `MarqueeBorder` control, changing their interaction with the design environment. + +Intercepting calls to a component's property accessor is known as "shadowing." It allows a designer to track the value set by the user and optionally pass that value to the component being designed. + +For this example, the and properties will be shadowed by the `MarqueeBorderDesigner`, which prevents the user from making the `MarqueeBorder` control invisible or disabled during design time. + +Designers can also add and remove properties. For this example, the property will be removed at design time, because the `MarqueeBorder` control programmatically sets the padding based on the size of the lights specified by the `LightSize` property. + +The base class for `MarqueeBorderDesigner` is , which has methods that can change the attributes, properties, and events exposed by a control at design time: + +- + +- + +- + +- + +- + +- + +When changing the public interface of a component using these methods, follow these rules: + +- Add or remove items in the `PreFilter` methods only + +- Modify existing items in the `PostFilter` methods only + +- Always call the base implementation first in the `PreFilter` methods + +- Always call the base implementation last in the `PostFilter` methods + +Adhering to these rules ensures that all designers in the design-time environment have a consistent view of all components being designed. + +The class provides a dictionary for managing the values of shadowed properties, which relieves you of the need to create specific instance variables. + +### To create a custom designer to shadow and filter properties + +1. Right-click the **Design** folder and add a new class. Give the source file a base name of **MarqueeBorderDesigner**. + +2. Open the MarqueeBorderDesigner source file in the **Code Editor**. At the top of the file, import the following namespaces: + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#420](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs#420)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#420](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb#420)] + +3. Change the declaration of `MarqueeBorderDesigner` to inherit from . + + Because the `MarqueeBorder` control can contain child controls, `MarqueeBorderDesigner` inherits from , which handles the parent-child interaction. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#430](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs#430)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#430](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb#430)] + +4. Override the base implementation of . + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#450](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs#450)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#450](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb#450)] + +5. Implement the and properties. These implementations shadow the control's properties. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#440](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs#440)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#440](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb#440)] + +## Handle Component Changes + +The `MarqueeControlRootDesigner` class provides the custom design-time experience for your `MarqueeControl` instances. Most of the design-time functionality is inherited from the class. Your code will implement two specific customizations: handling component changes, and adding designer verbs. + +As users design their `MarqueeControl` instances, your root designer will track changes to the `MarqueeControl` and its child controls. The design-time environment offers a convenient service, , for tracking changes to component state. + +You acquire a reference to this service by querying the environment with the method. If the query is successful, your designer can attach a handler for the event and perform whatever tasks are required to maintain a consistent state at design time. + +In the case of the `MarqueeControlRootDesigner` class, you will call the method on each `IMarqueeWidget` object contained by the `MarqueeControl`. This will cause the `IMarqueeWidget` object to repaint itself appropriately when properties like its parent's are changed. + +### To handle component changes + +1. Open the `MarqueeControlRootDesigner` source file in the **Code Editor** and override the method. Call the base implementation of and query for the . + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#580](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#580)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#580](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#580)] + +2. Implement the event handler. Test the sending component's type, and if it is an `IMarqueeWidget`, call its method. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#560](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#560)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#560](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#560)] + +## Add Designer Verbs to your Custom Designer + +A designer verb is a menu command linked to an event handler. Designer verbs are added to a component's shortcut menu at design time. For more information, see . + +You will add two designer verbs to your designers: **Run Test** and **Stop Test**. These verbs will allow you to view the run-time behavior of the `MarqueeControl` at design time. These verbs will be added to `MarqueeControlRootDesigner`. + +When **Run Test** is invoked, the verb event handler will call the `StartMarquee` method on the `MarqueeControl`. When **Stop Test** is invoked, the verb event handler will call the `StopMarquee` method on the `MarqueeControl`. The implementation of the `StartMarquee` and `StopMarquee` methods call these methods on contained controls that implement `IMarqueeWidget`, so any contained `IMarqueeWidget` controls will also participate in the test. + +### To add designer verbs to your custom designers + +1. In the `MarqueeControlRootDesigner` class, add event handlers named `OnVerbRunTest` and `OnVerbStopTest`. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#570](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#570)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#570](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#570)] + +2. Connect these event handlers to their corresponding designer verbs. `MarqueeControlRootDesigner` inherits a from its base class. You will create two new objects and add them to this collection in the method. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#590](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs#590)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#590](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb#590)] + +## Create a Custom UITypeEditor + +When you create a custom design-time experience for users, it is often desirable to create a custom interaction with the Properties window. You can accomplish this by creating a . + +The `MarqueeBorder` control exposes several properties in the Properties window. Two of these properties, `MarqueeSpinDirection` and `MarqueeLightShape` are represented by enumerations. To illustrate the use of a UI type editor, the `MarqueeLightShape` property will have an associated class. + +### To create a custom UI type editor + +1. Open the `MarqueeBorder` source file in the **Code Editor**. + +2. In the definition of the `MarqueeBorder` class, declare a class called `LightShapeEditor` that derives from . + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#96](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#96)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#96](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#96)] + +3. Declare an instance variable called `editorService`. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#92](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#92)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#92](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#92)] + +4. Override the method. This implementation returns , which tells the design environment how to display the `LightShapeEditor`. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#93](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#93)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#93](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#93)] + +5. Override the method. This implementation queries the design environment for an object. If successful, it creates a `LightShapeSelectionControl`. The method is invoked to start the `LightShapeEditor`. The return value from this invocation is returned to the design environment. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#94](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs#94)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#94](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb#94)] + +## Create a View Control for your Custom UITypeEditor + +The `MarqueeLightShape` property supports two types of light shapes: `Square` and `Circle`. You will create a custom control used solely for the purpose of graphically displaying these values in the Properties window. This custom control will be used by your to interact with the Properties window. + +### To create a view control for your custom UI type editor + +1. Add a new item to the `MarqueeControlLibrary` project. Give the new source file a base name of **LightShapeSelectionControl**. + +2. Drag two controls from the **Toolbox** onto the `LightShapeSelectionControl`. Name them `squarePanel` and `circlePanel`. Arrange them side by side. Set the property of both controls to **(60, 60)**. Set the property of the `squarePanel` control to **(8, 10)**. Set the property of the `circlePanel` control to **(80, 10)**. Finally, set the property of the `LightShapeSelectionControl` to **(150, 80)**. + +3. Open the `LightShapeSelectionControl` source file in the **Code Editor**. At the top of the file, import the namespace: + + ```vb + Imports System.Windows.Forms.Design + ``` + + ```csharp + using System.Windows.Forms.Design; + ``` + +4. Implement event handlers for the `squarePanel` and `circlePanel` controls. These methods invoke to end the custom editing session. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#390](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs#390)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#390](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb#390)] + +5. Declare an instance variable called `editorService`. + + ```vb + Private editorService As IWindowsFormsEditorService + ``` + + ```csharp + private IWindowsFormsEditorService editorService; + ``` + +6. Declare a `MarqueeLightShape` instance variable called `lightShapeValue`. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#330](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs#330)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#330](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb#330)] + +7. In the `LightShapeSelectionControl` constructor, attach the event handlers to the `squarePanel` and `circlePanel` controls' events. Also, define a constructor overload that assigns the `MarqueeLightShape` value from the design environment to the `lightShapeValue` field. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#340](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs#340)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#340](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb#340)] + +8. In the method, detach the event handlers. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#350](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs#350)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#350](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb#350)] + +9. In **Solution Explorer**, click the **Show All Files** button. Open the LightShapeSelectionControl.Designer.cs or LightShapeSelectionControl.Designer.vb file, and remove the default definition of the method. + +10. Implement the `LightShape` property. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#360](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs#360)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#360](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb#360)] + +11. Override the method. This implementation will draw a filled square and circle. It will also highlight the selected value by drawing a border around one shape or the other. + + [!code-csharp[System.Windows.Forms.Design.DocumentDesigner#380](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs#380)] + [!code-vb[System.Windows.Forms.Design.DocumentDesigner#380](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb#380)] + +## Test your Custom Control in the Designer + +At this point, you can build the `MarqueeControlLibrary` project. Test your implementation by creating a control that inherits from the `MarqueeControl` class and using it on a form. + +### To create a custom MarqueeControl implementation + +1. Open `DemoMarqueeControl` in the Windows Forms Designer. This creates an instance of the `DemoMarqueeControl` type and displays it in an instance of the `MarqueeControlRootDesigner` type. + +2. In the **Toolbox**, open the **MarqueeControlLibrary Components** tab. You will see the `MarqueeBorder` and `MarqueeText` controls available for selection. + +3. Drag an instance of the `MarqueeBorder` control onto the `DemoMarqueeControl` design surface. Dock this `MarqueeBorder` control to the parent control. + +4. Drag an instance of the `MarqueeText` control onto the `DemoMarqueeControl` design surface. + +5. Build the solution. + +6. Right-click the `DemoMarqueeControl` and from the shortcut menu select the **Run Test** option to start the animation. Click **Stop Test** to stop the animation. + +7. Open **Form1** in Design view. + +8. Place two controls on the form. Name them `startButton` and `stopButton`, and change the property values to **Start** and **Stop**, respectively. + +9. Implement event handlers for both controls. + +10. In the **Toolbox**, open the **MarqueeControlTest Components** tab. You will see the `DemoMarqueeControl` available for selection. + +11. Drag an instance of `DemoMarqueeControl` onto the **Form1** design surface. + +12. In the event handlers, invoke the `Start` and `Stop` methods on the `DemoMarqueeControl`. + + ```vb + Private Sub startButton_Click(sender As Object, e As System.EventArgs) + Me.demoMarqueeControl1.Start() + End Sub 'startButton_Click + + Private Sub stopButton_Click(sender As Object, e As System.EventArgs) + Me.demoMarqueeControl1.Stop() + End Sub 'stopButton_Click + ``` + + ```csharp + private void startButton_Click(object sender, System.EventArgs e) + { + this.demoMarqueeControl1.Start(); + } + + private void stopButton_Click(object sender, System.EventArgs e) + { + this.demoMarqueeControl1.Stop(); + } + ``` + +13. Set the `MarqueeControlTest` project as the startup project and run it. You will see the form displaying your `DemoMarqueeControl`. Select the **Start** button to start the animation. You should see the text flashing and the lights moving around the border. + +## Next steps + +The `MarqueeControlLibrary` demonstrates a simple implementation of custom controls and associated designers. You can make this sample more sophisticated in several ways: + +- Change the property values for the `DemoMarqueeControl` in the designer. Add more `MarqueBorder` controls and dock them within their parent instances to create a nested effect. Experiment with different settings for the `UpdatePeriod` and the light-related properties. + +- Author your own implementations of `IMarqueeWidget`. You could, for example, create a flashing "neon sign" or an animated sign with multiple images. + +- Further customize the design-time experience. You could try shadowing more properties than and , and you could add new properties. Add new designer verbs to simplify common tasks like docking child controls. + +- License the `MarqueeControl`. + +- Control how your controls are serialized and how code is generated for them. For more information, see [Dynamic Source Code Generation and Compilation](https://docs.microsoft.com/dotnet/framework/reflection-and-codedom/dynamic-source-code-generation-and-compilation). + +## See also + +- +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/creating-an-explorer-style-interface-with-the-listview-and-treeview.md b/dotnet-desktop-guide/framework/winforms/controls/creating-an-explorer-style-interface-with-the-listview-and-treeview.md new file mode 100644 index 0000000000..818f1715cc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/creating-an-explorer-style-interface-with-the-listview-and-treeview.md @@ -0,0 +1,105 @@ +--- +title: "Walkthrough: Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer" +description: Learn how to create an Explorer style interface with the Windows Forms ListView and TreeView controls using the Designer. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Explorer-style applications [Windows Forms], walkthroughs" + - "TreeView control [Windows Forms], ListView controls used with" + - "ListView control [Windows Forms], TreeView controls used with" + - "Explorer-style applications" + - "TreeView control [Windows Forms], using for explorer-style interface" + - "ListView control [Windows Forms], explorer style interface" + - "ListView control [Windows Forms], explorer-style interface" +ms.assetid: 9e5e7721-19e2-4890-b273-a43589fe99ff +--- +# Walkthrough: Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer + +One of the benefits of Visual Studio is the ability to create professional-looking Windows Forms applications in a short of amount of time. A common scenario is creating a user interface (UI) with and controls that resembles the Windows Explorer feature of Windows operating systems. Windows Explorer displays a hierarchical structure of the files and folders on a user's computer. + +### To create the form containing a ListView and TreeView control + +1. On the **File** menu, point to **New**, and then click **Project**. + +2. In the **New Project** dialog box, do the following: + + 1. In the categories, choose either **Visual Basic** or **Visual C#**. + + 2. In the list of templates, choose **Windows Forms Application**. + +3. Click **OK**. A new Windows Forms project is created. + +4. Add a control to the form and set its property to . + +5. Add an named `imageList1` to the form and use the Properties window to add two images: a folder image and a document image, in that order. + +6. Add a control named `treeview1` to the form, and position it on the left side of the control. In the Properties window for `treeView1` do the following: + + 1. Set the property to . + + 2. Set the property to `imagelist1.` + +7. Add a control named `listView1` to the form, and position it on the right side of the control. In the Properties window for `listview1` do the following: + + 1. Set the property to . + + 2. Set the property to . + + 3. Open the ColumnHeader Collection Editor by clicking the ellipses (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) in the property**.** Add three columns and set their property to `Name`, `Type`, and `Last Modified`, respectively. Click **OK** to close the dialog box. + + 4. Set the property to `imageList1.` + +8. Implement the code to populate the with nodes and subnodes. Add this code to the `Form1` class. + + [!code-csharp[System.Windows.Forms.ExplorerStyleInterface#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.ExplorerStyleInterface#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb#1)] + +9. Since the previous code uses the System.IO namespace, add the appropriate using or import statement at the top of the form. + + [!code-csharp[System.Windows.Forms.ExplorerStyleInterface#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs#4)] + [!code-vb[System.Windows.Forms.ExplorerStyleInterface#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb#4)] + +10. Call the set-up method from the previous step in the form's constructor or event-handling method. Add this code to the form constructor. + + [!code-csharp[System.Windows.Forms.ExplorerStyleInterface#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.ExplorerStyleInterface#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb#2)] + +11. Handle the event for `treeview1`**,** and implement the code to populate `listview1` with a node's contents when a node is clicked. Add this code to the `Form1` class. + + [!code-csharp[System.Windows.Forms.ExplorerStyleInterface#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.ExplorerStyleInterface#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb#3)] + + If you are using C#, make sure you have the event associated with its event-handling method. Add this code to the form constructor. + + [!code-csharp[System.Windows.Forms.ExplorerStyleInterface#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs#5)] + +## Testing the Application + +You can now test the form to make sure it behaves as expected. + +#### To test the form + +- Press F5 to run the application. + + You will see a split form containing a control that displays your project directory on the left side, and a control on the right side with three columns. You can traverse the by selecting directory nodes, and the is populated with the contents of the selected directory. + +## Next Steps + +This application gives you an example of a way you can use and controls together. For more information on these controls, see the following topics: + +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) + +- [How to: Add Search Capabilities to a ListView Control](how-to-add-search-capabilities-to-a-listview-control.md) + +- [How to: Attach a ShortCut Menu to a TreeView Node](how-to-attach-a-shortcut-menu-to-a-treeview-node.md) + +## See also + +- +- +- [ListView Control](listview-control-windows-forms.md) +- [How to: Add and Remove Nodes with the Windows Forms TreeView Control](how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) +- [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/custom-control-painting-and-rendering.md b/dotnet-desktop-guide/framework/winforms/controls/custom-control-painting-and-rendering.md new file mode 100644 index 0000000000..1f47a45901 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/custom-control-painting-and-rendering.md @@ -0,0 +1,47 @@ +--- +title: "Custom Control Painting and Rendering" +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], rendering" + - "custom controls [Windows Forms], painting" + - "user controls [Windows Forms], painting" +ms.assetid: a09dbf76-0966-4cbf-a66a-2083ba98e068 +--- +# Custom Control Painting and Rendering +Custom painting of controls is one of the many complicated tasks made easy by the .NET Framework. When authoring a custom control, you have many options regarding your control's graphical appearance. If you are authoring a control that inherits from the `Control`, you must provide code that allows your control to render its graphical representation. If you are creating a user control by inheriting from the `UserControl`, or are inheriting from one of the Windows Forms controls, you may override the standard graphical representation and provide your own graphics code. If you want to provide custom rendering for the constituent controls of a `UserControl` you are authoring, your options become more limited, but still allow a wide range of graphical possibilities for your controls and applications. + +## In This Section + [Rendering a Windows Forms Control](rendering-a-windows-forms-control.md) + Shows how to program the logic that displays a control. + + [User-Drawn Controls](user-drawn-controls.md) + Gives an overview of the steps involved in writing and overriding rendering code for your control. + + [Constituent Controls](constituent-controls.md) + Describes how to implement custom rendering code for constituent controls in your user controls and forms. + + [How to: Make Your Control Invisible at Run Time](how-to-make-your-control-invisible-at-run-time.md) + Shows how to use the property to hide and show a control. + + [How to: Give Your Control a Transparent Background](how-to-give-your-control-a-transparent-background.md) + Shows how to use the method to create a background color that is opaque, transparent, or partially transparent. + + [Rendering Controls with Visual Styles](rendering-controls-with-visual-styles.md) + Shows how to render controls using visual styles in operating systems that support them. + +## Reference + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + + + Describes this method. + +## Related Sections + [How to: Create Graphics Objects for Drawing](../advanced/how-to-create-graphics-objects-for-drawing.md) + Introduces GDI+ graphics functionality from a Visual Studio perspective and gives links to more information. + + [Varieties of Custom Controls](varieties-of-custom-controls.md) + Describes the kinds of custom controls you can author. diff --git a/dotnet-desktop-guide/framework/winforms/controls/customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md b/dotnet-desktop-guide/framework/winforms/controls/customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md new file mode 100644 index 0000000000..3702a6d7e0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md @@ -0,0 +1,73 @@ +--- +title: Customize Cells and Columns in DataGridView Control by Extending Their Behavior and Appearance +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], cell customization" + - "columns [Windows Forms], customizing in DataGridView control" + - "cells [Windows Forms], customizing in DataGridView control" +ms.assetid: 9b7dc7b6-5ce6-4566-9949-902f74f17a81 +--- +# How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance +The control provides a number of ways to customize its appearance and behavior using properties, events, and companion classes. Occasionally, you may have requirements for your cells that go beyond what these features can provide. You can create your own custom class to provide extended functionality. + + You create a custom class by deriving from the base class or one of its derived classes. Although you can display any type of cell in any type of column, you will typically also create a custom class specialized for displaying your cell type. Column classes derive from or one of its derived types. + + In the following code example, you will create a custom cell class called `DataGridViewRolloverCell` that detects when the mouse enters and leaves the cell boundaries. While the mouse is within the cell's bounds, an inset rectangle is drawn. This new type derives from and behaves in all other respects as its base class. The companion column class is called `DataGridViewRolloverColumn`. + + To use these classes, create a form containing a control, add one or more `DataGridViewRolloverColumn` objects to the collection, and populate the control with rows containing values. + +> [!NOTE] +> This example will not work correctly if you add empty rows. Empty rows are created, for example, when you add rows to the control by setting the property. This is because the rows added in this case are automatically shared, which means that `DataGridViewRolloverCell` objects are not instantiated until you click on individual cells, thereby causing the associated rows to become unshared. + + Because this type of cell customization requires unshared rows, it is not appropriate for use with large data sets. For more information about row sharing, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +> [!NOTE] +> When you derive from or and add new properties to the derived class, be sure to override the `Clone` method to copy the new properties during cloning operations. You should also call the base class's `Clone` method so that the properties of the base class are copied to the new cell or column. + +### To customize cells and columns in the DataGridView control + +1. Derive a new cell class, called `DataGridViewRolloverCell`, from the type. + + [!code-csharp[System.Windows.Forms.DataGridViewRolloverCell#201](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs#201)] + [!code-vb[System.Windows.Forms.DataGridViewRolloverCell#201](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb#201)] + [!code-csharp[System.Windows.Forms.DataGridViewRolloverCell#202](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs#202)] + [!code-vb[System.Windows.Forms.DataGridViewRolloverCell#202](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb#202)] + +2. Override the method in the `DataGridViewRolloverCell` class. In the override, first call the base class implementation, which handles the hosted text box functionality. Then use the control's method to transform the cursor position (in screen coordinates) to the client area's coordinates. If the mouse coordinates fall within the bounds of the cell, draw the inset rectangle. + + [!code-csharp[System.Windows.Forms.DataGridViewRolloverCell#210](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs#210)] + [!code-vb[System.Windows.Forms.DataGridViewRolloverCell#210](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb#210)] + +3. Override the and methods in the `DataGridViewRolloverCell` class to force cells to repaint themselves when the mouse pointer enters or leaves them. + + [!code-csharp[System.Windows.Forms.DataGridViewRolloverCell#220](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs#220)] + [!code-vb[System.Windows.Forms.DataGridViewRolloverCell#220](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb#220)] + +4. Derive a new class, called `DataGridViewRolloverCellColumn`, from the type. In the constructor, assign a new `DataGridViewRolloverCell` object to its property. + + [!code-csharp[System.Windows.Forms.DataGridViewRolloverCell#300](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs#300)] + [!code-vb[System.Windows.Forms.DataGridViewRolloverCell#300](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb#300)] + +## Example + The complete code example includes a small test form that demonstrates the behavior of the custom cell type. + + [!code-csharp[System.Windows.Forms.DataGridViewRolloverCell#000](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs#000)] + [!code-vb[System.Windows.Forms.DataGridViewRolloverCell#000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb#000)] + +## Compiling the Code + This example requires: + +- References to the System, System.Windows.Forms, and System.Drawing assemblies. + +## See also + +- +- +- +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) +- [DataGridView Control Architecture](datagridview-control-architecture-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) +- [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/customize-the-appearance-of-cells-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/customize-the-appearance-of-cells-in-the-datagrid.md new file mode 100644 index 0000000000..6acc7eeddb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/customize-the-appearance-of-cells-in-the-datagrid.md @@ -0,0 +1,33 @@ +--- +title: Customize the Appearance of Cells in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], customizing cells" + - "DataGridView control [Windows Forms], customizing cells" + - "cells [Windows Forms], customizing in DataGridView control" +ms.assetid: 478b20c9-625c-4116-9c5c-5a16e6f4ec67 +--- +# How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control +You can customize the appearance of any cell by handling the control's event. You can extract the control's from the property of the . With this , you can affect the appearance of the entire control, but you will usually want to affect only the appearance of the cell that is currently being painted. The property of the enables you to restrict your painting operations to the cell that is currently being painted. + + In the following code example, you will paint all the cells in a `ContactName` column using the control's color scheme. Each cell's text content is painted in , and an inset rectangle is drawn in the same color as the control's property. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewCellPainting#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/CS/form1.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewCellPainting#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/VB/form1.vb#10)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1` with a `ContactName` column such as the one in the Customers table in the Northwind sample database. + +- References to the System, System.Windows.Forms, and System.Drawing assemblies. + +## See also + +- +- +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/customize-the-appearance-of-rows-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/customize-the-appearance-of-rows-in-the-datagrid.md new file mode 100644 index 0000000000..f1ad543d7c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/customize-the-appearance-of-rows-in-the-datagrid.md @@ -0,0 +1,33 @@ +--- +title: Customize the Appearance of Rows in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], customizing rows" + - "rows [Windows Forms], customizing in DataGridView control" + - "DataGridView control [Windows Forms], customizing rows" +ms.assetid: d40b53d2-7e7c-48c5-8570-6e79d15c3bbb +--- +# How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control +You can control the appearance of rows by handling one or both of the and events. These events are designed so that you can paint only what you want to while letting the control paint the rest. For example, if you want to paint a custom background, you can handle the event and let the individual cells paint their own foreground content. Alternately, you can let the cells paint themselves and add custom foreground content in a handler for the event. You can also disable cell painting and paint everything yourself in a event handler. + + The following code example implements handlers for both events in order to provide a gradient selection background and some custom foreground content that spans multiple columns. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewRowPainting#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/CS/datagridviewrowpainting.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewRowPainting#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/VB/datagridviewrowpainting.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) +- [DataGridView Control Architecture](datagridview-control-architecture-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/customizing-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/customizing-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..01776df67a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/customizing-the-windows-forms-datagridview-control.md @@ -0,0 +1,53 @@ +--- +title: Customize DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "data grids [Windows Forms], customization" + - "DataGridView control [Windows Forms], customization" +ms.assetid: 01ea5d4c-a736-4596-b0e9-a67a1b86e15f +--- +# Customizing the Windows Forms DataGridView Control +The `DataGridView` control provides several properties that you can use to adjust the appearance and basic behavior (look and feel) of its cells, rows, and columns. If you have special needs that go beyond the capabilities of the class, however, you can also implement owner drawing for the control or extend its capabilities by creating custom cells, columns, and rows. + + To paint cells and rows yourself, you can handle various `DataGridView` painting events. To modify existing functionality or provide new functionality, you can create your own types derived from the existing `DataGridViewCell`, `DataGridViewColumn`, and `DataGridViewRow` types. You can also provide new editing capabilities by creating derived types that display a control of your choosing when a cell is in edit mode. + +## In This Section + [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) + Describes how to handle the event in order to paint cells manually. + + [How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control](customize-the-appearance-of-rows-in-the-datagrid.md) + Describes how to handle the and events in order to paint rows with a custom, gradient background and content that spans multiple columns. + + [How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance](customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md) + Describes how to create custom types derived from `DataGridViewCell` and `DataGridViewColumn` in order to highlight cells when the mouse pointer rests on them. + + [How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control](disable-buttons-in-a-button-column-in-the-datagrid.md) + Describes how to create custom types derived from and in order to display disabled buttons in a button column. + + [How to: Host Controls in Windows Forms DataGridView Cells](how-to-host-controls-in-windows-forms-datagridview-cells.md) + Describes how to implement the `IDataGridViewEditingControl` interface and create custom types derived from `DataGridViewCell` and `DataGridViewColumn` in order to display a control when a cell is in edit mode. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the class. + + + Provides reference documentation for the class. + + + Provides reference documentation for the class. + + + Provides reference documentation for the interface. + +## Related Sections + [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to modify the basic appearance of the control and the display formatting of cell data. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/data-display-modes-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/data-display-modes-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..7a0fb2eb19 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/data-display-modes-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,50 @@ +--- +title: Data Display Modes in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "data [Windows Forms], display modes" + - "data grids [Windows Forms], display modes" + - "DataGridView control [Windows Forms], display modes" +ms.assetid: 9755a030-3f3f-4705-a661-ba5a48a81875 +--- +# Data Display Modes in the Windows Forms DataGridView Control +The control can display data in three distinct modes: bound, unbound, and virtual. Choose the most suitable mode based on your requirements. + +## Unbound + Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically. You do not attach the control directly to a data source as in bound mode. Instead, you must populate the control yourself, typically by using the method. + + Unbound mode can be particularly useful for static, read-only data, or when you want to provide your own code that interacts with an external data store. When you want your users to interact with an external data source, however, you will typically use bound mode. + + For an example that uses a read-only unbound , see [How to: Create an Unbound Windows Forms DataGridView Control](how-to-create-an-unbound-windows-forms-datagridview-control.md). + +## Bound + Bound mode is suitable for managing data using automatic interaction with the data store. You can attach the control directly to its data source by setting the property. When the control is data bound, data rows are pushed and pulled without the need of explicit management on your part. When the property is `true`, each column in your data source will cause a corresponding column to be created in the control. If you prefer to create your own columns, you can set this property to `false` and use the property to bind each column when you configure it. This is useful when you want to use a column type other than the types that are generated by default. For more information, see [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md). + + For an example that uses a bound control, see [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md). + + You can also add unbound columns to a control in bound mode. This is useful when you want to display a column of buttons or links that enable users to perform actions on specific rows. It is also useful to display columns with values calculated from bound columns. You can populate the cell values for calculated columns in a handler for the event. If you are using a or as the data source, however, you might want to use the property to create a calculated column instead. In this case, the control will treat calculated column just like any other column in the data source. + + Sorting by unbound columns in bound mode is not supported. If you create an unbound column in bound mode that contains user-editable values, you must implement virtual mode to maintain these values when the control is sorted by a bound column. + +## Virtual + With virtual mode, you can implement your own data management operations. This is necessary to maintain the values of unbound columns in bound mode when the control is sorted by bound columns. The primary use of virtual mode, however, is to optimize performance when interacting with large amounts of data. + + You attach the control to a cache that you manage, and your code controls when data rows are pushed and pulled. To keep the memory footprint small, the cache should be similar in size to the number of rows currently displayed. When the user scrolls new rows into view, your code requests new data from the cache and optionally flushes old data from memory. + + When you are implementing virtual mode, you will need to track when a new row is needed in the data model and when to rollback the addition of the new row. The exact implementation of this functionality will depend on the implementation of the data model and the transaction semantics of the data model; whether commit scope is at the cell or row level. + + For more information about virtual mode, see [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md). For an example that shows how to use virtual mode events, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +## See also + +- +- +- +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) +- [Walkthrough: Creating an Unbound Windows Forms DataGridView Control](walkthrough-creating-an-unbound-windows-forms-datagridview-control.md) +- [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md) +- [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md) +- [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/data-entry-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/data-entry-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..f45a95f2e4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/data-entry-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,52 @@ +--- +title: Data Entry in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], data entry" + - "data entry [Windows Forms], dataGridView control" + - "data grids [Windows Forms], data entry" +ms.assetid: 4a6d4676-d4e7-4b0e-9c22-50ce65ffe0d6 +--- +# Data Entry in the Windows Forms DataGridView Control +The `DataGridView` control provides several features that let you change how users add or modify data in the control. For example, you can make data entry more efficient by providing default values for new rows and by alerting users when errors occur. + +## In This Section + [How to: Specify the Edit Mode for the Windows Forms DataGridView Control](how-to-specify-the-edit-mode-for-the-windows-forms-datagridview-control.md) + Describes how to change the way users start editing cells. + + [How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control](specify-default-values-for-new-rows-in-the-datagrid.md) + Describes how to prepopulate the row for new records to save data-entry time. + + [Using the Row for New Records in the Windows Forms DataGridView Control](using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md) + Describes the row for new records in detail, including information on hiding it, on customizing its appearance, and on how it relates to the collection. + + [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md) + Describes how to validate user input to prevent data-entry formatting errors. + + [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md) + Describes how to handle data-entry errors that originate from the data source when the user attempts to commit a new value. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the property. + + + Provides reference documentation for the event. + + + Provides reference documentation for the event. + + + Provides reference documentation for the event. + +## Related Sections + [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to populate the control with data either manually or from an external data source. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/data-formatting-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/data-formatting-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..74481fc864 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/data-formatting-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,35 @@ +--- +title: Data Formatting in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], formatting data" + - "data [Windows Forms], formatting in grids" + - "data grids [Windows Forms], formatting data" +ms.assetid: 07bf558d-3748-42ba-8ba0-37fdef924081 +--- +# Data Formatting in the Windows Forms DataGridView Control +The control provides automatic conversion between cell values and the data types that the parent columns display. Text box columns, for example, display string representations of date, time, number, and enumeration values, and convert user-entered string values to the types required by the data store. + +## Formatting with the DataGridViewCellStyle class + The control provides basic data formatting of cell values through the class. You can use the property to format date, time, number, and enumeration values for the current default culture using the format specifiers described in [Formatting Types](https://docs.microsoft.com/dotnet/standard/base-types/formatting-types). You can also format these values for specific cultures using the property. The specified format is used both to display data and to parse data that the user enters in the specified format. + + The class provides additional formatting properties for wordwrap, text alignment, and the custom display of null database values. For more information, see [How to: Format Data in the Windows Forms DataGridView Control](how-to-format-data-in-the-windows-forms-datagridview-control.md). + +## Formatting with the CellFormatting Event + If the basic formatting does not meet your needs, you can provide custom data formatting in a handler for the event. The passed to the handler has a property that initially contains the cell value. Normally, this value is automatically converted to the display type. To convert the value yourself, set the property to a value of the display type. + +> [!NOTE] +> If a format string is in effect for the cell, it overrides your change of the property value unless you set the property to `true`. + + The event is also useful when you want to set properties for individual cells based on their values. For more information, see [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md). + + If the default parsing of user-specified values does not meet your needs, you can handle the event of the control to provide custom parsing. + +## See also + +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [How to: Format Data in the Windows Forms DataGridView Control](how-to-format-data-in-the-windows-forms-datagridview-control.md) +- [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagrid-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagrid-control-overview-windows-forms.md new file mode 100644 index 0000000000..1f316ef508 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagrid-control-overview-windows-forms.md @@ -0,0 +1,149 @@ +--- +title: "DataGrid Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "DataGrid" +helpviewer_keywords: + - "datasets [Windows Forms], binding to DataGrid control" + - "data binding [Windows Forms], DataGrid control" + - "columns [Windows Forms], DataGrid control" + - "data sources [Windows Forms], binding to DataGrid control" + - "tables [Windows Forms], binding to DataGrid control" + - "DataGrid control [Windows Forms], data binding" + - "DataGrid control [Windows Forms], about DataGrid control" + - "parent tables in DataGrid control" + - "tables [Windows Forms], displaying in DataGrid control" + - "data grids [Windows Forms], about data grids" + - "multiple tables in DataGrid control" + - "data [Windows Forms], resorting" + - "data [Windows Forms], navigating" + - "parent table navigation in DataGrid" + - "child tables [Windows Forms], dataGrid control" +ms.assetid: 85604bce-bc03-49d9-9030-dda8896c44b1 +--- +# DataGrid Control Overview (Windows Forms) + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + +The Windows Forms control displays data in a series of rows and columns. The simplest case is when the grid is bound to a data source with a single table that contains no relationships. In that case, the data appears in simple rows and columns, as in a spreadsheet. For more information about binding data to other controls, see [Data Binding and Windows Forms](../data-binding-and-windows-forms.md). + +If the is bound to data with multiple related tables, and if navigation is enabled on the grid, the grid will display expanders in each row. With an expander, the user can move from a parent table to a child table. Clicking a node displays the child table, and clicking a back button displays the original parent table. In this manner, the grid displays the hierarchical relationships between tables. + +The following screenshot shows a DataGrid bound to data with multiple tables: + +![A WinForms app showing a DataGrid bound to data with multiple tables.](./media/datagrid-control-overview-windows-forms/datagrid-bound-multiple-tables.gif) + +The can provide a user interface for a dataset, navigation between related tables, and rich formatting and editing capabilities. + +The display and manipulation of data are separate functions: The control handles the user interface, whereas data updates are handled by the Windows Forms data-binding architecture and by .NET Framework data providers. Therefore, multiple controls bound to the same data source will stay in sync. + +> [!NOTE] +> If you are familiar with the DataGrid control in Visual Basic 6.0, you will find some significant differences in the Windows Forms control. + +When the grid is bound to a , the columns and rows are automatically created, formatted, and filled. For more information, see [Data Binding and Windows Forms](../data-binding-and-windows-forms.md). Following the generation of the control, you can add, delete, rearrange, and format columns and rows depending on your needs. + +## Binding Data to the Control + +For the control to work, it should be bound to a data source using the and properties at design time or the method at run time. This binding points the to an instantiated data-source object, such as a or ). The control shows the results of actions that are performed on the data. Most data-specific actions are not performed through the , but instead through the data source. + +If the data in the bound dataset is updated through any mechanism, the control reflects the changes. If the data grid and its table styles and column styles have the `ReadOnly` property set to `false`, the data in the dataset can be updated through the control. + +Only one table can be shown in the at a time. If a parent-child relationship is defined between tables, the user can move between the related tables to select the table to be displayed in the control. For information about binding a control to an ADO.NET data source at either design time or run time, see [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md). + +Valid data sources for the include: + +- class + +- class + +- class + +- class + +If your source is a dataset, the dataset might be an object in the form or an object passed to the form by an XML Web service. You can bind to either typed or untyped datasets. + +You can also bind a control to additional structures if the objects in the structure, such as the elements in an array, expose public properties. The grid will display all the public properties of the elements in the structure. For example, if you bind the control to an array of customer objects, the grid will display all the public properties of those customer objects. In some instances, this means that although you can bind to the structure, the resulting bound structure might not have practical application. For example, you can bind to an array of integers, but because the `Integer` data type does not support a public property, the grid cannot display any data. + +You can bind to the following structures if their elements expose public properties: + +- Any component that implements the interface. This includes single-dimension arrays. + +- Any component that implements the interface. + +- Any component that implements the interface. + + For more information about possible data sources, see [Data Sources Supported by Windows Forms](../data-sources-supported-by-windows-forms.md). + +## Grid Display + +A common use of the control is to display a single table of data from a dataset. However, the control can also be used to display multiple tables, including related tables. The display of the grid is adjusted automatically according to the data source. The following table shows what is displayed for various configurations. + +|Contents of data set|What is displayed| +|--------------------------|-----------------------| +|Single table.|Table is displayed in a grid.| +|Multiple tables.|The grid can display a tree view that users can navigate to locate the table they want to display.| +|Multiple related tables.|The grid can display a tree view to select tables with, or you can specify that the grid display the parent table. Records in the parent table let users navigate to related child rows.| + +> [!NOTE] +> Tables in a dataset are related using a . Also see [Create relationships between datasets](/visualstudio/data-tools/relationships-in-datasets). + +When the control is displaying a table and the property is set to `true`, data can be resorted by clicking the column headers. The user can also add rows and edit cells. + +The relationships between a set of tables are displayed to users by using a parent/child structure of navigation. Parent tables are the highest level of data, and child tables are those data tables that are derived from the individual listings in the parent tables. Expanders are displayed in each parent row that contains a child table. Clicking an expander generates a list of Web-like links to the child tables. When the user selects a link, the child table is displayed. Clicking the show/hide parent rows icon (![Show/hide parent rows icon](./media/datagrid-control-overview-windows-forms/show-hide-parent-rows.gif)) will hide the information about the parent table or cause it to reappear if the user has previously hidden it. The user can click a back button to move back to the previously viewed table. + +## Columns and Rows + +The consists of a collection of objects that are contained in the control's property. A table style may contain a collection of objects that are contained in the property of the .. You can edit the and properties by using collection editors accessed through the **Properties** window. + +Any associated with the control can be accessed through the . The can be edited in the designer with the collection editor, or programmatically through the control's property. + +The following illustration shows the objects included in the DataGrid control: + +![Diagram that shows objects included in the DataGrid control.](./media/datagrid-control-overview-windows-forms/visual-basic-columns.gif) + +Table styles and column styles are synchronized with objects and objects by setting their `MappingName` properties to the appropriate and properties. When a that has no column styles is added to a control bound to a valid data source, and the property of that table style is set to a valid property, a collection of objects is created for that table style. For each found in the collection of the , a corresponding is added to the . is accessed through the property of the . Columns can be added or deleted from the grid using the or method on the . For more information, see [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) and [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md). + +A collection of column types extends the class with rich formatting and editing capabilities. All column types inherit from the base class. The class that is created depends on the property of the from which the is based. For example, a that has its property set to will be associated with the . The following table describes each of these column types. + +|Column Type|Description| +|-----------------|-----------------| +||Accepts and displays data as formatted or unformatted strings. Editing capabilities are the same as they are for editing data in a simple . Inherits from .| +||Accepts and displays `true`, `false`, and null values. Inherits from .| + +Double-clicking the right edge of a column resizes the column to display its full caption and widest entry. + +## Table Styles and Column Styles + +As soon as you have established the default format of the control, you can customize the colors that will be used when certain tables are displayed within the data grid. + +This is achieved by creating instances of the class. Table styles specify the formatting of specific tables, distinct from the default formatting of the control itself. Each table may have only one table style defined for it at a time. + +Sometimes, you will want to have a specific column look different from the rest of the columns of a particular data table. You can create a customized set of column styles by using the property. + +Column styles are related to columns in a dataset just like table styles are related to data tables. Just as each table may only have one table style defined for it at a time, so too can each column only have one column style defined for it, in a particular table style. This relationship is defined in the column's property. + +If you have created a table style without column styles added to it, Visual Studio will add default column styles when the form and grid are created at run time. However, if you have created a table style and added any column styles to it, Visual Studio will not create any column styles. Also, you will need to define column styles and assign them with the mapping name to have the columns that you want appear in the grid. + +Because you specify which columns are included in the data grid by assigning them a column style and no column style has been assigned to the columns, you can include columns of data in the dataset that are not displayed in the grid. However, because the data column is included in the dataset, you can programmatically edit the data that is not displayed. + +> [!NOTE] +> In general, create column styles and add them to the column styles collection before adding table styles to the table styles collection. When you add an empty table style to the collection, column styles are automatically generated for you. Consequently, an exception will be thrown if you try to add new column styles with duplicate values to the column styles collection. +> +> Sometimes, you will want to just tweak one column among many columns; for example, the dataset contains 50 columns and you only want 49 of them. In this case, it is easier to import all 50 columns and programmatically remove one, rather than programmatically adding each of the 49 individual columns you want. + +## Formatting + +Formatting that can be applied to the control includes border styles, gridline styles, fonts, caption properties, data alignment, and alternating background colors between rows. For more information, see [How to: Format the Windows Forms DataGrid Control](how-to-format-the-windows-forms-datagrid-control.md). + +## Events + +Besides the common control events such as , , and , the control supports events associated with editing and navigation within the grid. The property determines which cell is selected. The event is raised when the user navigates to a new cell. When the user navigates to a new table through parent/child relations, the event is raised. The event is raised when the user clicks the back button when the user is viewing a child table, and the event is raised when the show/hide parent rows icon is clicked. + +## See also + +- [DataGrid Control](datagrid-control-windows-forms.md) +- [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md) +- [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) +- [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) +- [How to: Format the Windows Forms DataGrid Control](how-to-format-the-windows-forms-datagrid-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagrid-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagrid-control-windows-forms.md new file mode 100644 index 0000000000..ed08e0c7fe --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagrid-control-windows-forms.md @@ -0,0 +1,77 @@ +--- +title: "DataGrid Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "datasets [Windows Forms], user interface" + - "DataGrid control [Windows Forms]" + - "datasets [Windows Forms], displaying in DataGrid control" + - "displaying data [Windows Forms], on forms" + - "data [Windows Forms], displaying on Windows Forms" +ms.assetid: 1d9d5683-43d2-42dd-b6c3-e43f4cf0de99 +--- +# DataGrid Control (Windows Forms) +> [!NOTE] +> The control replaces and adds functionality to the `DataGrid` control; however, the `DataGrid` control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + The Windows Forms `DataGrid` control provides a user interface to ADO.NET datasets, displaying tabular data and enabling updates to the data source. + + When the `DataGrid` control is set to a valid data source, the control is automatically populated, creating columns and rows based on the shape of the data. The `DataGrid` control can be used to display either a single table or the hierarchical relationships between a set of tables. + +## In This Section + [DataGrid Control Overview](datagrid-control-overview-windows-forms.md) + Describes the basic features of the `DataGrid` control. + + [How to: Add Tables and Columns to the Windows Forms DataGrid Control Using the Designer](add-tables-and-columns-to-wf-datagrid-control-using-the-designer.md) + Describes how to add tables and columns to the `DataGrid` control using the designer. + + [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) + Describes how to add tables and columns to the `DataGrid` control programmatically. + + [How to: Bind the Windows Forms DataGrid Control to a Data Source Using the Designer](bind-wf-datagrid-control-to-a-data-source-using-the-designer.md) + Describes how to bind an ADO.NET dataset to the `DataGrid` control using the designer. + + [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md) + Describes how to bind an ADO.NET dataset to the `DataGrid` control. + + [How to: Change Displayed Data at Run Time in the Windows Forms DataGrid Control](change-displayed-data-at-run-time-wf-datagrid-control.md) + Describes how to change data programmatically in the `DataGrid` control. + + [How to: Create Master-Details Lists with the Windows Forms DataGrid Control Using the Designer](create-master-details-lists-with-wf-datagrid-control-using-the-designer.md) + Describes how to display two tables, tied together with a parent/child relationship, in two separate `DataGrid` controls using the designer. + + How to: Create Master-Details Lists with the Windows Forms DataGrid Control + Describes how to display two tables, tied together with a parent/child relationship, in two separate `DataGrid` controls. + + [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) + Describes how to remove columns in the `DataGrid` control. + + [How to: Format the Windows Forms DataGrid Control Using the Designer](how-to-format-the-windows-forms-datagrid-control-using-the-designer.md) + Describes how to change the appearance-related properties of the `DataGrid` control using the designer. + + [How to: Format the Windows Forms DataGrid Control](how-to-format-the-windows-forms-datagrid-control.md) + Describes how to change the appearance-related properties of the `DataGrid` control. + + [Keyboard Shortcuts for the Windows Forms DataGrid Control](keyboard-shortcuts-for-the-windows-forms-datagrid-control.md) + Lists shortcuts for navigating through the `DataGrid` control. + + [How to: Respond to Clicks in the Windows Forms DataGrid Control](how-to-respond-to-clicks-in-the-windows-forms-datagrid-control.md) + Describes how to determine which cell a user has clicked in the `DataGrid` control. + + [How to: Validate Input with the Windows Forms DataGrid Control](how-to-validate-input-with-the-windows-forms-datagrid-control.md) + Describes how to validate input in the dataset bound to the `DataGrid` control. + +## Reference + + Provides an overview of the class. + + + Provides details about using this property to bind the control to data. + +## Related Sections + [Windows Forms Data Binding](../windows-forms-data-binding.md) + Provides links to topics on data binding in Windows Forms. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-architecture-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-architecture-windows-forms.md new file mode 100644 index 0000000000..eeebc7d35e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-architecture-windows-forms.md @@ -0,0 +1,137 @@ +--- +title: "DataGridView Control Architecture" +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], architecture" +ms.assetid: 1c6cabf0-02ee-4bbc-9574-b54bb7f5b19e +--- +# DataGridView Control Architecture (Windows Forms) +The control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data. These classes are all contained in the namespace, and they are all named with the "DataGridView" prefix. + +## Architecture Elements + The primary companion classes derive from . The following object model illustrates the inheritance hierarchy. + + ![Diagram that shows the DataGridViewElement Object Model hierarchy.](./media/datagridview-control-architecture-windows-forms/datagridviewelement-object-model.gif) + + The class provides a reference to the parent control and has a property, which holds a value that represents a combination of values from the enumeration. + + The following sections describe the companion classes in more detail. + +### DataGridViewElementStates + The enumeration contains the following values: + +- + +- + +- + +- + +- + +- + +- + + The values of this enumeration can be combined with the bitwise logical operators, so the property can express more than one state at once. For example, a can be simultaneously , , and . + +### Cells and Bands + The control comprises two fundamental kinds of objects: cells and bands. All cells derive from the base class. The two kinds of bands, and , both derive from the base class. + + The control interoperates with several classes, but the most commonly encountered are , , and . + +### DataGridViewCell + The cell is the fundamental unit of interaction for the . Display is centered on cells, and data entry is often performed through cells. You can access cells by using the collection of the class, and you can access the selected cells by using the collection of the control. The following object model illustrates this usage and shows the inheritance hierarchy. + + ![Diagram that shows the DataGridViewCell Object Model hierarchy.](./media/datagridview-control-architecture-windows-forms/datagridviewcell-object-model.gif) + + The type is an abstract base class, from which all cell types derive. and its derived types are not Windows Forms controls, but some host Windows Forms controls. Any editing functionality supported by a cell is typically handled by a hosted control. + + objects do not control their own appearance and painting features in the same way as Windows Forms controls. Instead, the is responsible for the appearance of its objects. You can significantly affect the appearance and behavior of cells by interacting with the control's properties and events. When you have special requirements for customizations that are beyond the capabilities of the control, you can implement your own class that derives from or one of its child classes. + + The following list shows the classes derived from : + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- Your custom cell types + +### DataGridViewColumn + The schema of the control's attached data store is expressed in the control's columns. You can access the control's columns by using the collection. You can access the selected columns by using the collection. The following object model illustrates this usage and shows the inheritance hierarchy. + + ![Diagram that shows the DataGridViewColumn Object Model hierarchy.](./media/datagridview-control-architecture-windows-forms/datagridviewcolumn-object-model.gif) + + Some of the key cell types have corresponding column types. These are derived from the base class. + + The following list shows the classes derived from : + +- + +- + +- + +- + +- + +- + +- Your custom column types + +### DataGridView Editing Controls + Cells that support advanced editing functionality typically use a hosted control that is derived from a Windows Forms control. These controls also implement the interface. The following object model illustrates the usage of these controls. + + ![Diagram showing the DataGridView Editing Control Object Model hierarchy.](./media/datagridview-control-architecture-windows-forms/datagridviewediting-object-model.gif) + + The following editing controls are provided with the control: + +- + +- + + For information about creating your own editing controls, see [How to: Host Controls in Windows Forms DataGridView Cells](how-to-host-controls-in-windows-forms-datagridview-cells.md). + + The following table illustrates the relationship among cell types, column types, and editing controls. + +|Cell type|Hosted control|Column type| +|---------------|--------------------|-----------------| +||n/a|| +||n/a|| +|||| +||n/a|| +||n/a|| +|||| + +### DataGridViewRow + The class displays a record's data fields from the data store to which the control is attached. You can access the control's rows by using the collection. You can access the selected rows by using the collection. The following object model illustrates this usage and shows the inheritance hierarchy. + + ![Diagram that shows the DataGridViewRow Object Model hierarchy.](./media/datagridview-control-architecture-windows-forms/datagridviewrow-object-model.gif) + + You can derive your own types from the class, although this will typically not be necessary. The control has several row-related events and properties for customizing the behavior of its objects. + + If you enable the control's property, a special row for adding new rows appears as the last row. This row is part of the collection, but it has special functionality that may require your attention. For more information, see [Using the Row for New Records in the Windows Forms DataGridView Control](using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md). + +## See also + +- [DataGridView Control Overview](datagridview-control-overview-windows-forms.md) +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) +- [Using the Row for New Records in the Windows Forms DataGridView Control](using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-code-directory-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-code-directory-windows-forms.md new file mode 100644 index 0000000000..6d1d042d7f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-code-directory-windows-forms.md @@ -0,0 +1,152 @@ +--- +title: "DataGridView Control Code Directory" +ms.date: "03/30/2017" +helpviewer_keywords: + - "data grids [Windows Forms], examples" + - "examples [Windows Forms], DataGridView control" + - "DataGridView control [Windows Forms], examples" + - "DataGridView control [Windows Forms], code directory" +ms.assetid: ea8bd66a-5ed6-491b-b9da-63873e275a0a +--- +# DataGridView Control Code Directory (Windows Forms) +This topic provides links to -related code examples available in the documentation. + +> [!NOTE] +> A link always jumps to the top of the topic in which the code example is found. + + Additional code examples are available in the class library reference documentation. For a list of the principal classes and interfaces associated with the control, see the table in [DataGridView Control Technology Summary](datagridview-control-technology-summary-windows-forms.md). + +## CodeList + +## Unbound Data Examples + +- [How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control](unbound-column-to-a-data-bound-datagridview.md) + +- [How to: Create an Unbound Windows Forms DataGridView Control](how-to-create-an-unbound-windows-forms-datagridview-control.md) + +- [Walkthrough: Creating an Unbound Windows Forms DataGridView Control](walkthrough-creating-an-unbound-windows-forms-datagridview-control.md) + +## Data Binding Examples + +- [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md) + +- [How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control](autogenerate-columns-in-a-data-bound-wf-datagridview-control.md) + +- [How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control](remove-autogenerated-columns-from-a-wf-datagridview-control.md) + +- [How to: Bind Objects to Windows Forms DataGridView Controls](how-to-bind-objects-to-windows-forms-datagridview-controls.md) + +- [How to: Access Objects Bound to Windows Forms DataGridView Rows](how-to-access-objects-bound-to-windows-forms-datagridview-rows.md) + +- [How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls](create-a-master-detail-form-using-two-datagridviews.md) + +- [Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls](creating-a-master-detail-form-using-two-datagridviews.md) + +## Data Formatting Examples + +- [How to: Format Data in the Windows Forms DataGridView Control](how-to-format-data-in-the-windows-forms-datagridview-control.md) + +- [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md) + +## Data Validation Examples + +- [How to: Validate Data in the Windows Forms DataGridView Control](how-to-validate-data-in-the-windows-forms-datagridview-control.md) + +- [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md) + +- [How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control](handle-errors-that-occur-during-data-entry-in-the-datagrid.md) + +- [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md) + +## Appearance Customization Examples + +- [How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control](change-the-border-and-gridline-styles-in-the-datagrid.md) + +- [How to: Set Font and Color Styles in the Windows Forms DataGridView Control](how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md) + +- [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md) + +- [How to: Use the Row Template to Customize Rows in the Windows Forms DataGridView Control](use-the-row-template-to-customize-rows-in-the-datagrid.md) + +- [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control](how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md) + +## Behavior Customization Examples + +- [How to: Specify the Edit Mode for the Windows Forms DataGridView Control](how-to-specify-the-edit-mode-for-the-windows-forms-datagridview-control.md) + +- [How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control](specify-default-values-for-new-rows-in-the-datagrid.md) + +- [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md) + +- [How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control](perform-a-custom-action-based-on-changes-in-a-cell-of-a-datagrid.md) + +- [How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control](enable-users-to-copy-multiple-cells-to-the-clipboard-datagridview.md) + +- [How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control](add-tooltips-to-individual-cells-in-a-wf-datagridview-control.md) + +- [How to: Display Images in Cells of the Windows Forms DataGridView Control](how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md) + +- [How to: Customize Sorting in the Windows Forms DataGridView Control](how-to-customize-sorting-in-the-windows-forms-datagridview-control.md) + +## Column Manipulation Examples + +- [How to: Freeze Columns in the Windows Forms DataGridView Control](how-to-freeze-columns-in-the-windows-forms-datagridview-control.md) + +- [How to: Enable Column Reordering in the Windows Forms DataGridView Control](how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md) + +- [How to: Change the Order of Columns in the Windows Forms DataGridView Control](how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md) + +- [How to: Hide Columns in the Windows Forms DataGridView Control](how-to-hide-columns-in-the-windows-forms-datagridview-control.md) + +- [How to: Hide Column Headers in the Windows Forms DataGridView Control](how-to-hide-column-headers-in-the-windows-forms-datagridview-control.md) + +- [How to: Make Columns Read-Only in the Windows Forms DataGridView Control](how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md) + +- [How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control](set-the-sort-modes-for-columns-wf-datagridview-control.md) + +- [How to: Work with Image Columns in the Windows Forms DataGridView Control](how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md) + +- [How to: Manipulate Columns in the Windows Forms DataGridView Control](how-to-manipulate-columns-in-the-windows-forms-datagridview-control.md) + +## Row and Column Sizing Examples + +- [Column Fill Mode in the Windows Forms DataGridView Control](column-fill-mode-in-the-windows-forms-datagridview-control.md) + +- [How to: Set the Sizing Modes of the Windows Forms DataGridView Control](how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md) + +- [How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control](programmatically-resize-cells-to-fit-content-in-the-datagrid.md) + +- [How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control](automatically-resize-cells-when-content-changes-in-the-datagrid.md) + +## Selection Examples + +- [How to: Set the Selection Mode of the Windows Forms DataGridView Control](how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md) + +- [How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control](selected-cells-rows-and-columns-datagridview.md) + +- [How to: Get and Set the Current Cell in the Windows Forms DataGridView Control](get-and-set-the-current-cell-wf-datagridview-control.md) + +## Advanced Customization Examples + +- [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) + +- [How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control](customize-the-appearance-of-rows-in-the-datagrid.md) + +- [How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance](customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md) + +- [How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control](disable-buttons-in-a-button-column-in-the-datagrid.md) + +- [How to: Host Controls in Windows Forms DataGridView Cells](how-to-host-controls-in-windows-forms-datagridview-cells.md) + +## Advanced Data Examples + +- [How to: Implement Virtual Mode in the Windows Forms DataGridView Control](how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md) + +- [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md) + +- [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md) + +## See also + +- +- [DataGridView Control Overview](datagridview-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-overview-windows-forms.md new file mode 100644 index 0000000000..95022bd8ee --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-overview-windows-forms.md @@ -0,0 +1,82 @@ +--- +title: "DataGridView Control Overview" +description: Learn how to use the Windows Forms DataGridView control to display and edit tabular data from many different kinds of data sources. +ms.date: "03/30/2017" +f1_keywords: + - "DataGridView" +helpviewer_keywords: + - "DataGridView control [Windows Forms], about DataGridView control" + - "grid controls [Windows Forms]" + - "tables [Windows Forms], displaying in DataGridView control" + - "tables [Windows Forms], binding to DataGridView control" + - "columns [Windows Forms], DataGridView control" + - "bound controls [Windows Forms], dataGridView control" + - "datasets [Windows Forms], binding to DataGridView control" + - "data grids [Windows Forms], about data grids" + - "data [Windows Forms], resorting" + - "data [Windows Forms], navigating" + - "grids [Windows Forms]" + - "data binding [Windows Forms], DataGridView control" + - "data sources [Windows Forms], binding to DataGridView control" + - "DataGridView control [Windows Forms], data binding" +ms.assetid: 0a45c661-89dc-4390-9cc6-c47eee501488 +--- +# DataGridView Control Overview (Windows Forms) +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + With the control, you can display and edit tabular data from many different kinds of data sources. + + Binding data to the control is straightforward and intuitive, and in many cases it is as simple as setting the property. When you bind to a data source that contains multiple lists or tables, set the property to a string that specifies the list or table to bind to. + + The control supports the standard Windows Forms data binding model, so it will bind to instances of classes described in the following list: + +- Any class that implements the interface, including one-dimensional arrays. + +- Any class that implements the interface, such as the and classes. + +- Any class that implements the interface, such as the class. + +- Any class that implements the interface, such as the class. + + The control supports data binding to the public properties of the objects returned by these interfaces or to the properties collection returned by an interface, if implemented on the returned objects. + + Typically, you will bind to a component and bind the component to another data source or populate it with business objects. The component is the preferred data source because it can bind to a wide variety of data sources and can resolve many data binding issues automatically. For more information, see [BindingSource Component](bindingsource-component.md). + + The control can also be used in *unbound* mode, with no underlying data store. For a code example that uses an unbound control, see [Walkthrough: Creating an Unbound Windows Forms DataGridView Control](walkthrough-creating-an-unbound-windows-forms-datagridview-control.md). + + The control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. When you want your Windows Forms application to display tabular data, consider using the control before others (for example, ). If you are displaying a small grid of read-only values, or if you are enabling a user to edit a table with millions of records, the control will provide you with a readily programmable, memory-efficient solution. + +## In This Section + [DataGridView Control Technology Summary](datagridview-control-technology-summary-windows-forms.md) + Summarizes control concepts and the use of related classes. + + [DataGridView Control Architecture](datagridview-control-architecture-windows-forms.md) + Describes the architecture of the control, explaining its type hierarchy and inheritance structure. + + [DataGridView Control Scenarios](datagridview-control-scenarios-windows-forms.md) + Describes the most common scenarios in which controls are used. + + [DataGridView Control Code Directory](datagridview-control-code-directory-windows-forms.md) + Provides links to code examples in the documentation for various tasks. These examples are categorized by task type. + +## Related Sections + [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) + Discusses the column types in the Windows Forms control used to display information and allow users to modify or add information. + + [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to populate the control with data either manually, or from an external data source. + + [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) + Provides topics that describe custom painting cells and rows, and creating derived cell, column, and row types. + + [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to use the control efficiently to avoid performance problems when working with large amounts of data. + +## See also + +- +- +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Default Functionality in the Windows Forms DataGridView Control](default-functionality-in-the-windows-forms-datagridview-control.md) +- [Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control](default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-scenarios-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-scenarios-windows-forms.md new file mode 100644 index 0000000000..27d57e5d53 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-scenarios-windows-forms.md @@ -0,0 +1,86 @@ +--- +title: "DataGridView Control Scenarios" +ms.date: "03/30/2017" +helpviewer_keywords: + - "data [Windows Forms], displaying in tabular format" + - "data grids [Windows Forms], about data grids" + - "DataGridView control [Windows Forms], scenarios" +ms.assetid: 09a5fd05-3447-47ec-a4ec-6082a2b7f0dd +--- +# DataGridView Control Scenarios (Windows Forms) +With the control, you can display tabular data from a variety of data sources. For simple uses, you can manually populate a and manipulate the data directly through the control. Typically, however, you will store your data in an external data source and bind the control to it through a component. + + This topic describes some of the common scenarios that involve the control. + +## Scenario 1: Displaying Small Amounts of Data + You do not have to store your data in an external data source to display it in the control. If you are working with a small amount of data, you can populate the control yourself and manipulate the data through the control. This is called *unbound mode*. For more information, see [How to: Create an Unbound Windows Forms DataGridView Control](how-to-create-an-unbound-windows-forms-datagridview-control.md). + +### Scenario Key Points + +- In unbound mode, you populate the control manually. + +- Unbound mode is particularly suited for small amounts of read-only data. + +- Unbound mode is also suited for spreadsheet-like or sparsely populated tables. + +## Scenario 2: Viewing and Updating Data Stored in an External Data Source + You can use the control as a user interface (UI) through which users can access data kept in a data source such as a database table or a collection of business objects. For more information, see [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md). + +### Scenario Key Points + +- Bound mode lets you connect to a data source, automatically generate columns based on the data source properties or database columns, and automatically populate the control. + +- Bound mode is suited for heavy user interaction with data. Data can be formatted for display, and user-specified data can be parsed into the format expected by the data source. Data entry formatting errors and database constraint errors can be detected so that users can be warned and erroneous cells can be corrected. + +- Additional functionality such as column sorting, freezing, and reordering enable users to view data in the way most convenient for their workflow. + +- Clipboard support enables users to copy data from your application into other applications. + +## Scenario 3: Advanced Data + If you have special needs that the standard data binding model does not address, you can manage the interaction between the control and your data by implementing *virtual mode*. Implementing virtual mode means implementing one or more event handlers that let the control request information about cells as the information is needed. + + For example, if you work with large amounts of data, you may want to implement virtual mode to ensure optimal efficiency. Virtual mode is also useful for maintaining the values of unbound columns that you display along with columns retrieved from another data source. + + For more information about virtual mode, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +### Scenario Key Points + +- Virtual mode is suited for displaying very large amounts of data when you need to fine-tune performance. + +## Scenario 4: Automatically Resizing Rows and Columns + When you display data that is regularly updated, you can automatically resize rows and columns to ensure that all content is visible. The control provides several options that let you enable or disable manual resizing, resize programmatically at specific times, or resize automatically whenever content changes. For more information, see [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md). + +### Scenario Key Points + +- Manual resizing enables users to adjust cell heights and widths. + +- Automatic resizing enables you to maintain cell sizes so that cell content is never clipped. + +- Programmatic resizing enables you to resize cells at specific times to avoid the performance penalty of continuous automatic resizing. + +## Scenario 5: Simple Customization + The control provides many ways for you to alter its basic appearance and behavior. For more information, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + +### Scenario Key Points + +- objects let you provide color, font, formatting, and positioning information at multiple levels and for individual elements of the control. + +- Cell styles can be layered and shared by multiple elements, letting you reuse code. + +## Scenario 6: Advanced Customization + The control provides many ways for you to customize its appearance and behavior. + +### Scenario Key Points + +- You can provide your own cell painting code. For more information, see [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md). + +- You can provide your own row painting. This is useful, for example, to create rows with content that spans multiple columns. For more information, see [How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control](customize-the-appearance-of-rows-in-the-datagrid.md). + +- You can implement your own cell and column classes to customize cell appearance. For more information, see [How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance](customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md). + +- You can implement your own cell and column classes to host controls other than the ones provided by the built-in column types. For more information, see [How to: Host Controls in Windows Forms DataGridView Cells](how-to-host-controls-in-windows-forms-datagridview-cells.md). + +## See also + +- +- [DataGridView Control Overview](datagridview-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-technology-summary-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-technology-summary-windows-forms.md new file mode 100644 index 0000000000..a55983ed28 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-technology-summary-windows-forms.md @@ -0,0 +1,61 @@ +--- +title: "DataGridView Control Technology Summary" +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], about DataGridView control" + - "data grids [Windows Forms], about data grids" +ms.assetid: 094498c3-a126-4a3f-83fe-f69e96c7717b +--- +# DataGridView Control Technology Summary (Windows Forms) +This topic summarizes information about the `DataGridView` control and the classes that support its use. + + Displaying data in a tabular format is a task you are likely to perform frequently. The `DataGridView` control is designed to be a complete solution for presenting data in a grid. + +## Keywords + DataGridView, BindingSource, table, cell, data binding, virtual mode + +## Namespaces + + + + +## Related Technologies + `BindingSource` + +## Background + User interface (UI) designers frequently find it necessary to display tabular data to users. The .NET Framework provides several ways to show data in a table or grid. The `DataGridView` control represents the latest evolution of this technology for Windows Forms applications. + + The `DataGridView` control can display rows of data from a data store. Many types of data stores are supported. The data store can hold simple, untyped data, such as a one-dimensional array, or it can hold typed data, such as a . For more information, see [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md). + + The `DataGridView` control provides a powerful and flexible way to display data in a tabular format. You can use the control to show read-only or editable views of small to very large sets of data. + + You can extend the `DataGridView` control in several ways to build custom behavior into your applications. For example, you can programmatically specify your own sorting algorithms, and you can create your own types of cells. You can easily customize the appearance of the `DataGridView` control by choosing among several properties. Many types of data stores can be used as a data source, or the `DataGridView` control can operate without a data source bound to it. + +## Implementing DataGridView Classes + There are several ways for you to take advantage of the `DataGridView` control's extensibility features. You can customize many aspects of the control through events and properties, but some customizations require you to create new classes derived from existing `DataGridView` classes. + + The most typically used base classes are `DataGridViewCell` and `DataGridViewColumn`. You can derive your own cell class from `DataGridViewCell` or any of its child classes. Although you can add any cell type to any column, you will typically also derive a companion column class from `DataGridViewColumn` that hosts cells of your custom cell type by default. + + You can implement the `IDataGridViewEditingCell` interface in your derived cell class to create a cell type that has editing functionality but does not host a control in editing mode. To create a control that you can host in a cell in editing mode, you can implement the `IDataGridViewEditingControl` interface in a class derived from . + + For more information, see [How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance](customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md) and [How to: Host Controls in Windows Forms DataGridView Cells](how-to-host-controls-in-windows-forms-datagridview-cells.md). + +## DataGridView Classes at a Glance + + +|Technology Area|Classes/interfaces/configuration elements| +|---------------------|-------------------------------------------------| +|Data Binding|| +|Data Presentation|

and derived classes

and derived classes

and derived classes

| +| Extensibility| and derived classes

and derived classes



| + +## What's New + The control is designed to be a complete solution for displaying tabular data with Windows Forms. You should consider using the control before other solutions, such as , when you are authoring a new application. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + The control can work in close conjunction with the component. This component is designed to be the primary data source of a form. It can manage the interaction between a control and its data source, regardless of the data source type. + +## See also + +- [DataGridView Control Overview](datagridview-control-overview-windows-forms.md) +- [DataGridView Control Architecture](datagridview-control-architecture-windows-forms.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-windows-forms.md new file mode 100644 index 0000000000..daced34aa7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datagridview-control-windows-forms.md @@ -0,0 +1,82 @@ +--- +title: "DataGridView Control" +description: Learn how to use the `DataGridView` control to show read-only views of a small amount of data, or scale it to show editable views of very large sets of data. +ms.date: "03/30/2017" +helpviewer_keywords: + - "tables [Windows Forms]" + - "data grids [Windows Forms" + - "data [Windows Forms], displaying in tabular format" + - "grid controls [Windows Forms]" + - "datasets [Windows Forms], user interface" + - "Windows Forms, displaying data" + - "data presentation" + - "tabular data [Windows Forms], displaying on Windows Forms" + - "datasets [Windows Forms], displaying in DataGridView control" + - "DataGridView control [Windows Forms]" +ms.assetid: dbee73f2-bba6-4874-9389-cd21d44309be +--- +# DataGridView Control (Windows Forms) +The `DataGridView` control provides a powerful and flexible way to display data in a tabular format. You can use the `DataGridView` control to show read-only views of a small amount of data, or you can scale it to show editable views of very large sets of data. + + You can extend the `DataGridView` control in a number of ways to build custom behaviors into your applications. For example, you can programmatically specify your own sorting algorithms, and you can create your own types of cells. You can easily customize the appearance of the `DataGridView` control by choosing among several properties. Many types of data stores can be used as a data source, or the `DataGridView` control can operate with no data source bound to it. + + The topics in this section describe the concepts and techniques that you can use to build `DataGridView` features into your applications. + +## In This Section + [DataGridView Control Overview](datagridview-control-overview-windows-forms.md) + Provides topics that describe the architecture and core concepts of the Windows Forms `DataGridView` control. + + [Default Functionality in the Windows Forms DataGridView Control](default-functionality-in-the-windows-forms-datagridview-control.md) + Describes the default appearance and behavior of the Windows Forms `DataGridView` control when it is bound to a data source. + + [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) + Describes the column types in the Windows Forms `DataGridView` control used to display data and allow users to modify or add data. + + [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) + Provides topics that describe commonly-used cell, row, and column properties. + + [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to modify the basic appearance of the control and the display formatting of cell data. + + [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to populate the control with data either manually, or from an external data source. + + [Resizing Columns and Rows in the Windows Forms DataGridView Control](resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how the size of rows and columns can be adjusted automatically to fit cell content or to fit the available width of the control. + + [Sorting Data in the Windows Forms DataGridView Control](sorting-data-in-the-windows-forms-datagridview-control.md) + Provides topics that describe the sorting features in the control. + + [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to change the way users add and modify data in the control. + + [Selection and Clipboard Use with the Windows Forms DataGridView Control](selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md) + Provides topics that describe the cell, row, and column selection features in the control. + + [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) + Provides topics that describe how to program with cell, row, and column objects. + + [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) + Provides topics that describe custom painting `DataGridView` cells and rows, and creating derived cell, column, and row types. + + [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to use the control efficiently to avoid performance problems when working with large amounts of data. + + [Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control](default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md) + Describes how users can interact with the `DataGridView` control through a keyboard and a mouse. + + [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md) + Describes how the `DataGridView` control improves upon and replaces the control. + + Also see [Using the Designer with the Windows Forms DataGridView Control](using-the-designer-with-the-windows-forms-datagridview-control.md). + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the component. The control and the component are designed to work closely together. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datetimepicker-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datetimepicker-control-overview-windows-forms.md new file mode 100644 index 0000000000..da9763a40a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datetimepicker-control-overview-windows-forms.md @@ -0,0 +1,24 @@ +--- +title: "DateTimePicker Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "DateTimePicker" +helpviewer_keywords: + - "DateTimePicker control [Windows Forms], about" + - "date and time picker controls" +ms.assetid: 501af106-e9fc-4efc-b9b3-c9d8dcaf8c5c +--- +# DateTimePicker Control Overview (Windows Forms) +The Windows Forms control allows the user to select a single item from a list of dates or times. When used to represent a date, it appears in two parts: a drop-down list with a date represented in text, and a grid that appears when you click on the down-arrow next to the list. The grid looks like the control, which can be used for selecting multiple dates. For more information on the control, see [MonthCalendar Control Overview](monthcalendar-control-overview-windows-forms.md). + +## Key Properties + If you wish the to appear as a control for picking or editing times instead of dates, set the property to `true` and the property to . For more information see [How to: Display Time with the DateTimePicker Control](how-to-display-time-with-the-datetimepicker-control.md). + + When the property is set to `true`, a check box is displayed next to the selected date in the control. When the check box is checked, the selected date-time value can be updated. When the check box is empty, the value appears unavailable. + + The control's and properties determine the range of dates and times. The property contains the current date and time the control is set to. For details, see [How to: Set and Return Dates with the Windows Forms DateTimePicker Control](how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md). The values can be displayed in four formats, which are set by the property: , , , or . If a custom format is selected, you must set the property to an appropriate string. For details, see [How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control](display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md). + +## See also + +- [How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control](display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md) +- [How to: Set and Return Dates with the Windows Forms DateTimePicker Control](how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/datetimepicker-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/datetimepicker-control-windows-forms.md new file mode 100644 index 0000000000..d3a5fc75c8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/datetimepicker-control-windows-forms.md @@ -0,0 +1,40 @@ +--- +title: "DateTimePicker Control" +description: Learn to use the Windows Forms DateTimePicker control to allow the user to select a single item from a list of dates or times. +ms.date: "03/30/2017" +helpviewer_keywords: + - "dates [Windows Forms], choosing from a list" + - "dates [Windows Forms], Windows Forms controls" + - "DateTimePicker control [Windows Forms]" + - "date and time picker controls" +ms.assetid: 1dac1fbd-8f67-4910-9ccb-2c5462d0d855 +--- +# DateTimePicker Control (Windows Forms) +The Windows Forms `DateTimePicker` control allows the user to select a single item from a list of dates or times. When used to represent a date, it appears in two parts: a drop-down list with a date represented in text, and a grid that appears when you click on the down-arrow next to the list. + +## In This Section + [DateTimePicker Control Overview](datetimepicker-control-overview-windows-forms.md) + Introduces the general concepts of the `DateTimePicker` control, which allows users to select a single item from a list of dates or times. + + [How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control](display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md) + Explains how to use format strings to display dates in a preferred format. + + [How to: Set and Return Dates with the Windows Forms DateTimePicker Control](how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md) + Provides steps to set the date in the control and to access the date the user has selected. + + [How to: Display Time with the DateTimePicker Control](how-to-display-time-with-the-datetimepicker-control.md) + Shows steps to for a `DateTimePicker` to display times only. + +## Reference + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [MonthCalendar Control](monthcalendar-control-windows-forms.md) + Presents an intuitive graphical interface for users to view and set date information. diff --git a/dotnet-desktop-guide/framework/winforms/controls/default-cell-styles-datagridview.md b/dotnet-desktop-guide/framework/winforms/controls/default-cell-styles-datagridview.md new file mode 100644 index 0000000000..da7130be85 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/default-cell-styles-datagridview.md @@ -0,0 +1,65 @@ +--- +title: Set Default Cell Styles and Data Formats for DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], cell styles" + - "cells [Windows Forms], setting styles" + - "data formats" + - "data [Windows Forms], setting formats" +ms.assetid: fc6da49f-8942-41da-b49f-b2afc38cc656 +--- +# How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer + +The control lets you specify default cell styles and cell data formats for the entire control, for specific columns, for row and column headers, and for alternating rows to create a ledger effect. Default styles set for the entire control are overridden by default styles set for columns and alternating rows. Additionally, styles that you set in code for individual rows and cells override the default styles. + +For more information about cell styles, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). To set styles for alternating rows, see [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer](set-alternating-row-styles-for-the-datagrid-using-the-designer.md). + +You can also set styles using the property to affect all rows that will be added to the control. For more information about the row template, see [How to: Use the Row Template to Customize Rows in the Windows Forms DataGridView Control](use-the-row-template-to-customize-rows-in-the-datagrid.md). + +The following procedures require a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To set default styles for all cells in the control + +1. Select the control in the designer. + +2. In the **Properties** window, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the , , or property. The **CellStyle Builder** dialog box appears. + +3. Define the style by setting the properties, using the **Preview** pane to confirm your choices. + +> [!NOTE] +> If visual styles are enabled, the row and column headers (except for the ) are automatically styled by the current theme, overriding the and property values. +> +> You can set cell styles for multiple selected controls using the designer, but only if they have identical values for the cell style property you want to modify. If any cell styles differ for that property, the **Properties** windows of the **CellStyle Builder** dialog box will be blank. + +### To set default styles for cells in individual columns + +1. Right-click the control in the designer and choose **Edit Columns**. + +2. Select a column from the **Selected Columns** list. + +3. In the **Column Properties** grid, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property. The **CellStyle Builder** dialog box appears. + +4. Define the style by setting the properties, using the **Preview** pane to confirm your choices. + +### To format data in cells + +1. Use one of the preceding procedures to display a **CellStyle Builder** dialog box related to a default cell style property. + +2. In the **CellStyle Builder** dialog box, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property. The **Format String** dialog box appears. + +3. Select a format type, then modify the details of the type (such as the number of decimal places to display), using the **Sample** box to confirm your choices. + +4. If you are binding the control to a data source that is likely to contain null values, fill in the **Null Value** text box. This value is displayed when the cell value is equal to a null reference (`Nothing` in Visual Basic) or . + +## See also + +- +- +- +- +- +- +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer](set-alternating-row-styles-for-the-datagrid-using-the-designer.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/default-functionality-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/default-functionality-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..bfbe2476d1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/default-functionality-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,46 @@ +--- +title: Default Functionality in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "data grids [Windows Forms], default functionality in DataGridView control" + - "DataGridView control [Windows Forms], default functionality" +ms.assetid: 4405f697-cad1-4839-9bcd-8ddb09d9f00e +--- +# Default Functionality in the Windows Forms DataGridView Control +The Windows Forms control provides users with a significant amount of default functionality. + +## Default Functionality + By default, a control: + +- Automatically displays column headers and row headers that remain visible as the table scrolls vertically. + +- Has a row header that contains a selection indicator for the current row. + +- Has a selection rectangle in the first cell. + +- Has columns that can be automatically resized when the user double-clicks the column dividers. + +- Automatically supports visual styles on Windows XP and the Windows Server 2003 family when the method is called from the application's `Main` method. + + Additionally, the contents of a control can be edited by default: + +- If the user double-clicks or presses F2 in a cell, the control automatically puts the cell into edit mode and updates the contents of the cell as the user types. + +- If the user scrolls to the end of the grid, the user will see that a row for adding new records is present. When the user clicks this row, a new row is added to the control, with default values. When the user presses ESC, this new row disappears. + +- If the user clicks a row header, the whole row is selected. + + When you bind a control to a data source by setting its property, the control: + +- Automatically uses the names of the data source's columns as the column header text. + +- Is populated with the contents of the data source. columns are automatically created for each column in the data source. + +- Creates a row for each visible row in the table. + +- Automatically sorts the rows based on the underlying data when the user clicks a column header. + +## See also + +- +- [DataGridView Control](datagridview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..338457b2cf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,114 @@ +--- +title: Default keyboard and mouse handling in DataGridView control +ms.date: "02/13/2018" +helpviewer_keywords: + - "data grids [Windows Forms], mouse handling" + - "DataGridView control [Windows Forms], navigation keys" + - "keyboards [Windows Forms], default handling in DataGridView control" + - "DataGridView control [Windows Forms], keyboard handling" + - "mouse [Windows Forms], default handling in DataGridView control" + - "DataGridView control [Windows Forms], mouse handling" + - "navigation keys [Windows Forms], DataGridView control" +ms.assetid: 4519b928-bfc8-4e8b-bb9c-b1e76a0ca552 +--- +# Default keyboard and mouse handling in the Windows Forms DataGridView control + +The following tables describe how users can interact with the control through a keyboard and a mouse. + +> [!NOTE] +> To customize keyboard behavior, you can handle standard keyboard events such as . In edit mode, however, the hosted editing control receives the keyboard input and the keyboard events do not occur for the control. To handle editing control events, attach your handlers to the editing control in an event handler. Alternatively, you can customize keyboard behavior in a subclass by overriding the and methods. + +## Default keyboard handling + +### Basic navigation and entry keys + +|Key or key combination|Description| +|----------------------------|-----------------| +|DOWN ARROW|Moves the focus to the cell directly below the current cell. If the focus is in the last row, does nothing.| +|LEFT ARROW|Moves the focus to the previous cell in the row. If the focus is in the first cell in the row, does nothing.| +|RIGHT ARROW|Moves the focus to the next cell in the row. If the focus is in the last cell in the row, does nothing.| +|UP ARROW|Moves the focus to the cell directly above the current cell. If the focus is in the first row, does nothing.| +|HOME|Moves the focus to the first cell in the current row.| +|END|Moves the focus to the last cell in the current row.| +|PAGE DOWN|Scrolls the control downward by the number of rows that are fully displayed. Moves the focus to the last fully displayed row without changing columns.| +|PAGE UP|Scrolls the control upward by the number of rows that are fully displayed. Moves focus to the first displayed row without changing columns.| +|TAB|If the property value is `false`, moves the focus to the next cell in the current row. If the focus is already in the last cell of the row, moves the focus to the first cell in the next row. If the focus is in the last cell in the control, moves the focus to the next control in the tab order of the parent container.

If the property value is `true`, moves the focus to the next control in the tab order of the parent container.| +|SHIFT+TAB|If the property value is `false`, moves the focus to the previous cell in the current row. If the focus is already in the first cell of the row, moves the focus to the last cell in the previous row. If the focus is in the first cell in the control, moves the focus to the previous control in the tab order of the parent container.

If the property value is `true`, moves the focus to the previous control in the tab order of the parent container.| +|CTRL+TAB|If the property value is `false`, moves the focus to the next control in the tab order of the parent container.

If the property value is `true`, moves the focus to the next cell in the current row. If the focus is already in the last cell of the row, moves the focus to the first cell in the next row. If the focus is in the last cell in the control, moves the focus to the next control in the tab order of the parent container.| +|CTRL+SHIFT+TAB|If the property value is `false`, moves the focus to the previous control in the tab order of the parent container.

If the property value is `true`, moves the focus to the previous cell in the current row. If the focus is already in the first cell of the row, moves the focus to the last cell in the previous row. If the focus is in the first cell in the control, moves the focus to the previous control in the tab order of the parent container.| +|CTRL+ARROW|Moves the focus to the farthest cell in the direction of the arrow.| +|CTRL+HOME|Moves the focus to the first cell in the control.| +|CTRL+END|Moves the focus to the last cell in the control.| +|CTRL+PAGE DOWN/UP|Same as PAGE DOWN or PAGE UP.| +|F2|Puts the current cell into cell edit mode if the property value is or .| +|F3|Sorts the current column if the property value is . It's the same as clicking the current column header. Available since .NET Framework 4.7.2. To enable this feature, applications must target .NET Framework 4.7.2 or later versions or explicitly opt into accessibility improvements using AppContext switches.| +|F4|If the current cell is a , puts the cell into edit mode and displays the drop-down list.| +|ALT+UP/DOWN ARROW|If the current cell is a , puts the cell into edit mode and displays the drop-down list.| +|SPACE|If the current cell is a , , or , raises the and events. If the current cell is a , also presses the button. If the current cell is a , also changes the check state.| +|ENTER|Commits any changes to the current cell and row and moves the focus to the cell directly below the current cell. If the focus is in the last row, commits any changes without moving the focus.| +|ESC|If the control is in edit mode, cancels the edit. If the control is not in edit mode, reverts any changes that have been made to the current row if the control is bound to a data source that supports editing or virtual mode has been implemented with row-level commit scope.| +|BACKSPACE|Deletes the character before the insertion point when editing a cell.| +|DELETE|Deletes the character after the insertion point when editing a cell.| +|CTRL+ENTER|Commits any changes to the current cell without moving the focus. Also commits any changes to the current row if the control is bound to a data source that supports editing or virtual mode has been implemented with row-level commit scope.| +|CTRL+0|Enters a value into the current cell if the cell can be edited. By default, the display value for a cell value is the value of the property of the in effect for the current cell.| + +### Selection keys + + If the property is set to `false` and the property is set to , changing the current cell by using the navigation keys changes the selection to the new cell. The SHIFT, CTRL, and ALT keys do not affect this behavior. + + If the is set to or , the same behavior occurs but with the following additions. + +|Key or key combination|Description| +|----------------------------|-----------------| +|SHIFT+SPACEBAR|Selects the full row or column (the same as clicking the row or column header).| +|navigation key (arrow key, PAGE UP/DOWN, HOME, END)|If a full row or column is selected, changing the current cell to a new row or column moves the selection to the full new row or column (depending on the selection mode).| + + If is set to `false` and is set to or , changing the current cell to a new row or column by using the keyboard moves the selection to the full new row or column. The SHIFT, CTRL, and ALT keys do not affect this behavior. + + If is set to `true`, the navigation behavior does not change, but navigating with the keyboard while pressing SHIFT (including CTRL+SHIFT) will modify a multi-cell selection. Before navigation begins, the control marks the current cell as an anchor cell. When you navigate while pressing SHIFT, the selection includes all cells between the anchor cell and the current cell. Other cells in the control will remain selected if they were already selected, but they may become unselected if the keyboard navigation temporarily puts them between the anchor cell and the current cell. + + If is set to `true` and is set to or , the behavior of the anchor cell and current cell is the same, but only full rows or columns become selected or unselected. + +## Default mouse handling + +### Basic mouse handling + +> [!NOTE] +> Clicking a cell with the left mouse button always changes the current cell. Clicking a cell with the right mouse button opens a shortcut menu, when one is available. + +|Mouse action|Description| +|------------------|-----------------| +|Left mouse button down|Makes the clicked cell the current cell, and raises the event.| +|Left mouse button up|Raises the event| +|Left mouse button click|Raises the and events| +|Left mouse button down, and drag on a column header cell|If the property is `true`, moves the column so that it can be dropped into a new position.| + +### Mouse selection + + No selection behavior is associated with the middle mouse button or the mouse wheel. + + If the property is set to `false` and the property is set to , the following behavior occurs. + +|Mouse action|Description| +|------------------|-----------------| +|Click left mouse button|Selects only the current cell if the user clicks a cell. No selection behavior if the user clicks a row or column header.| +|Click right mouse button|Displays a shortcut menu if one is available.| + + The same behavior occurs when the is set to or , except that, depending on the selection mode, clicking a row or column header will select the full row or column and set the current cell to the first cell in the row or column. + + If is set to or , clicking any cell in a row or column will select the full row or column. + + If is set to `true`, clicking a cell while pressing CTRL or SHIFT will modify a multi-cell selection. + + When you click a cell while pressing CTRL, the cell will change its selection state while all other cells retain their current selection state. + + When you click a cell or a series of cells while pressing SHIFT, the selection includes all cells between the current cell and an anchor cell located at the position of the current cell before the first click. When you click and drag the pointer across multiple cells, the anchor cell is the cell clicked at the beginning of the drag operation. Subsequent clicks while pressing SHIFT change the current cell, but not the anchor cell. Other cells in the control will remain selected if they were already selected, but they may become unselected if mouse navigation temporarily puts them between the anchor cell and the current cell. + + If is set to `true` and is set to or , clicking a row or column header (depending on the selection mode) while pressing SHIFT will modify an existing selection of full rows or columns if such a selection exists. Otherwise, it will clear the selection and start a new selection of full rows or columns. Clicking a row or column header while pressing CTRL, however, will add or remove the clicked row or column from the current selection without otherwise modifying the current selection. + + If is set to `true` and is set to or , clicking a cell while pressing SHIFT or CTRL behaves the same way except that only full rows and columns are affected. + +## See also + +- +- [DataGridView Control](datagridview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/defining-a-property-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/defining-a-property-in-windows-forms-controls.md new file mode 100644 index 0000000000..29128bd64f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/defining-a-property-in-windows-forms-controls.md @@ -0,0 +1,122 @@ +--- +title: Define control properties +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "properties [Windows Forms], defining in code" + - "custom controls [Windows Forms], defining properties in code" +ms.assetid: c2eb8277-a842-4d99-89a9-647b901a0434 +--- +# Defining a Property in Windows Forms Controls +For an overview of properties, see [Properties Overview](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/65zdfbdt(v=vs.120)). There are a few important considerations when defining a property: + +- You must apply attributes to the properties you define. Attributes specify how the designer should display a property. For details, see [Design-Time Attributes for Components](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/tk67c2t8(v=vs.120)). + +- If changing the property affects the visual display of the control, call the method (that your control inherits from ) from the `set` accessor. in turn calls the method, which redraws the control. Multiple calls to result in a single call to for efficiency. + +- The .NET Framework class library provides type converters for common data types such as integers, decimal numbers, Boolean values, and others. The purpose of a type converter is generally to provide string-to-value conversion (from string data to other data types). Common data types are associated with default type converters that convert values into strings and strings into the appropriate data types. If you define a property that is a custom (that is, nonstandard) data type, you will have to apply an attribute that specifies the type converter to associate with that property. You can also use an attribute to associate a custom UI type editor with a property. A UI type editor provides a user interface for editing a property or data type. A color picker is an example of a UI type editor. Examples of attributes are given at the end of this topic. + + > [!NOTE] + > If a type converter or a UI type editor is not available for your custom property, you can implement one as described in [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)). + + The following code fragment defines a custom property named `EndColor` for the custom control `FlashTrackBar`. + +```vb +Public Class FlashTrackBar + Inherits Control + ... + ' Private data member that backs the EndColor property. + Private _endColor As Color = Color.LimeGreen + + ' The Category attribute tells the designer to display + ' it in the Flash grouping. + ' The Description attribute provides a description of + ' the property. + _ + Public Property EndColor() As Color + ' The public property EndColor accesses _endColor. + Get + Return _endColor + End Get + Set + _endColor = value + If Not (baseBackground Is Nothing) And showGradient Then + baseBackground.Dispose() + baseBackground = Nothing + End If + ' The Invalidate method calls the OnPaint method, which redraws + ' the control. + Invalidate() + End Set + End Property + ... +End Class +``` + +```csharp +public class FlashTrackBar : Control { + ... + // Private data member that backs the EndColor property. + private Color endColor = Color.LimeGreen; + // The Category attribute tells the designer to display + // it in the Flash grouping. + // The Description attribute provides a description of + // the property. + [ + Category("Flash"), + Description("The ending color of the bar.") + ] + // The public property EndColor accesses endColor. + public Color EndColor { + get { + return endColor; + } + set { + endColor = value; + if (baseBackground != null && showGradient) { + baseBackground.Dispose(); + baseBackground = null; + } + // The Invalidate method calls the OnPaint method, which redraws + // the control. + Invalidate(); + } + } + ... +} +``` + + The following code fragment associates a type converter and a UI type editor with the property `Value`. In this case `Value` is an integer and has a default type converter, but the attribute applies a custom type converter (`FlashTrackBarValueConverter`) that enables the designer to display it as a percentage. The UI type editor, `FlashTrackBarValueEditor`, allows the percentage to be displayed visually. This example also shows that the type converter or editor specified by the or attribute overrides the default converter. + +```vb + _ +Public ReadOnly Property Value() As Integer +... +End Property +``` + +```csharp +[ +Category("Flash"), +TypeConverter(typeof(FlashTrackBarValueConverter)), +Editor(typeof(FlashTrackBarValueEditor), typeof(UITypeEditor)), +Description("The current value of the track bar. You can enter an actual value or a percentage.") +] +public int Value { +... +} +``` + +## See also + +- [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) +- [Defining Default Values with the ShouldSerialize and Reset Methods](defining-default-values-with-the-shouldserialize-and-reset-methods.md) +- [Property-Changed Events](property-changed-events.md) +- [Attributes in Windows Forms Controls](attributes-in-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/defining-an-event-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/defining-an-event-in-windows-forms-controls.md new file mode 100644 index 0000000000..ffb3686fa6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/defining-an-event-in-windows-forms-controls.md @@ -0,0 +1,76 @@ +--- +title: Define an event in controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "events [Windows Forms], defining within Windows Forms custom controls" + - "custom controls [Windows Forms], events using code" +ms.assetid: d89f1096-8061-42e2-a855-a1f053f1940a +--- +# Defining an Event in Windows Forms Controls +For details about defining custom events, see [Events](https://docs.microsoft.com/dotnet/standard/events/index). If you define an event that does not have any associated data, use the base type for event data, , and use as the event delegate. All that remains to do is to define an event member and a protected `On`*EventName* method that raises the event. + + The following code fragment shows how the `FlashTrackBar` custom control defines a custom event, `ValueChanged`. For the complete code for the `FlashTrackBar` sample, see the [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + +```vb +Option Explicit +Option Strict + +Imports System +Imports System.Windows.Forms +Imports System.Drawing + +Public Class FlashTrackBar + Inherits Control + + ' The event does not have any data, so EventHandler is adequate + ' as the event delegate. + ' Define the event member using the event keyword. + ' In this case, for efficiency, the event is defined + ' using the event property construct. + Public Event ValueChanged As EventHandler + ' The protected method that raises the ValueChanged + ' event when the value has actually + ' changed. Derived controls can override this method. + Protected Overridable Sub OnValueChanged(e As EventArgs) + RaiseEvent ValueChanged(Me, e) + End Sub +End Class +``` + +```csharp +using System; +using System.Windows.Forms; +using System.Drawing; + +public class FlashTrackBar : Control { + // The event does not have any data, so EventHandler is adequate + // as the event delegate. + private EventHandler onValueChanged; + // Define the event member using the event keyword. + // In this case, for efficiency, the event is defined + // using the event property construct. + public event EventHandler ValueChanged { + add { + onValueChanged += value; + } + remove { + onValueChanged -= value; + } + } + // The protected method that raises the ValueChanged + // event when the value has actually + // changed. Derived controls can override this method. + protected virtual void OnValueChanged(EventArgs e) + { + onValueChanged?.Invoke(this, e); + } +} +``` + +## See also + +- [Events in Windows Forms Controls](events-in-windows-forms-controls.md) +- [Events](https://docs.microsoft.com/dotnet/standard/events/index) diff --git a/dotnet-desktop-guide/framework/winforms/controls/defining-default-values-with-the-shouldserialize-and-reset-methods.md b/dotnet-desktop-guide/framework/winforms/controls/defining-default-values-with-the-shouldserialize-and-reset-methods.md new file mode 100644 index 0000000000..5d4fa8c426 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/defining-default-values-with-the-shouldserialize-and-reset-methods.md @@ -0,0 +1,143 @@ +--- +title: "Defining Default Values with the ShouldSerialize and Reset Methods" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], property methods" + - "ShouldPersist method" +ms.assetid: 7b6c5e00-3771-46b4-9142-5a80d5864a5e +--- +# Defining Default Values with the ShouldSerialize and Reset Methods +`ShouldSerialize` and `Reset` are optional methods that you can provide for a property, if the property does not a have simple default value. If the property has a simple default value, you should apply the and supply the default value to the attribute class constructor instead. Either of these mechanisms enables the following features in the designer: + +- The property provides visual indication in the property browser if it has been modified from its default value. + +- The user can right-click on the property and choose **Reset** to restore the property to its default value. + +- The designer generates more efficient code. + + > [!NOTE] + > Either apply the or provide `Reset`*PropertyName* and `ShouldSerialize`*PropertyName* methods. Do not use both. + + The `Reset`*PropertyName* method sets a property to its default value, as shown in the following code fragment. + +```vb +Public Sub ResetMyFont() + MyFont = Nothing +End Sub +``` + +```csharp +public void ResetMyFont() { + MyFont = null; +} +``` + +> [!NOTE] +> If a property does not have a `Reset` method, is not marked with a , and does not have a default value supplied in its declaration, the `Reset` option for that property is disabled in the shortcut menu of the **Properties** window of the Windows Forms Designer in Visual Studio. + + Designers such as Visual Studio use the `ShouldSerialize`*PropertyName* method to check whether a property has changed from its default value and write code into the form only if a property is changed, thus allowing for more efficient code generation. For example: + +```vb +'Returns true if the font has changed; otherwise, returns false. +' The designer writes code to the form only if true is returned. +Public Function ShouldSerializeMyFont() As Boolean + Return Not (thefont Is Nothing) +End Function +``` + +```csharp +// Returns true if the font has changed; otherwise, returns false. +// The designer writes code to the form only if true is returned. +public bool ShouldSerializeMyFont() { + return thefont != null; +} +``` + + A complete code example follows. + +```vb +Option Explicit +Option Strict + +Imports System.Drawing +Imports System.Windows.Forms + +Public Class MyControl + Inherits Control + + ' Declare an instance of the Font class + ' and set its default value to Nothing. + Private thefont As Font = Nothing + + ' The MyFont property. + Public Property MyFont() As Font + ' Note that the Font property never + ' returns null. + Get + If Not (thefont Is Nothing) Then + Return thefont + End If + If Not (Parent Is Nothing) Then + Return Parent.Font + End If + Return Control.DefaultFont + End Get + Set + thefont = value + End Set + End Property + + Public Function ShouldSerializeMyFont() As Boolean + Return Not (thefont Is Nothing) + End Function + + Public Sub ResetMyFont() + MyFont = Nothing + End Sub +End Class +``` + +```csharp +using System; +using System.Drawing; +using System.Windows.Forms; + +public class MyControl : Control { + // Declare an instance of the Font class + // and set its default value to null. + private Font thefont = null; + + // The MyFont property. + public Font MyFont { + // Note that the MyFont property never + // returns null. + get { + if (thefont != null) return thefont; + if (Parent != null) return Parent.Font; + return Control.DefaultFont; + } + set { + thefont = value; + } + } + + public bool ShouldSerializeMyFont() { + return thefont != null; + } + + public void ResetMyFont() { + MyFont = null; + } +} +``` + + In this case, even when the value of the private variable accessed by the `MyFont` property is `null`, the property browser does not display `null`; instead, it displays the property of the parent, if it is not `null`, or the default value defined in . Thus the default value for `MyFont` cannot be simply set, and a cannot be applied to this property. Instead, the `ShouldSerialize` and `Reset` methods must be implemented for the `MyFont` property. + +## See also + +- [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) +- [Defining a Property](defining-a-property-in-windows-forms-controls.md) +- [Property-Changed Events](property-changed-events.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/design-time-errors-in-the-windows-forms-designer.md b/dotnet-desktop-guide/framework/winforms/controls/design-time-errors-in-the-windows-forms-designer.md new file mode 100644 index 0000000000..db11dd088e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/design-time-errors-in-the-windows-forms-designer.md @@ -0,0 +1,407 @@ +--- +title: Design-time errors in the Windows Forms Designer +titleSuffix: "" +description: Learn about the errors that occur when the Windows Forms Designer fails to load due to an error in your code, in a third-party component, or elsewhere. +ms.date: 09/09/2019 +f1_keywords: + - "DTELErrorList" + - "WhyDTELPage" +helpviewer_keywords: + - "errors [Windows Forms Designer]" + - "design-time errors [Windows Forms Designer]" +ms.assetid: ad408380-825a-46d8-9a4a-531b130b88ce +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Windows Forms Designer error page + +If the Windows Forms Designer fails to load due to an error in your code, in a third-party component, or elsewhere, you'll see an error page instead of the designer. This error page does not necessarily signify a bug in the designer. The bug may be somewhere in the code-behind page that's named \.Designer.cs. Errors appear in collapsible, yellow bars with a link to jump to the location of the error on the code page. + +![Windows Forms Designer error page](media/windows-forms-designer-error-page-collapsed.png) + +You can choose to ignore the errors and continue loading the designer by clicking **Ignore and Continue**. This action may result in unexpected behavior, for example, controls may not appear on the design surface. + +## Instances of this error + +When the yellow error bar is expanded, each instance of the error is listed. Many error types include an exact location in the following format: *[Project Name]* *[Form Name]* Line:*[Line Number]* Column:*[Column Number]*. If a call stack is associated with the error, you can click the **Show Call Stack** link to see it. Examining the call stack may further help you resolve the error. + +![Windows Forms Designer expanded error](media/windows-forms-designer-error-page-expanded.png) + +> [!NOTE] +> +> - For Visual Basic apps, the design-time error page does not display more than one error, but it may display multiple instances of the same error. +> - For C++ apps, errors don't have code location links. + +## Help with this error + +If a help topic for the error is available, click the **MSDN Help** link to navigate directly to the help page on docs.microsoft.com. + +## Forum posts about this error + +Click the **Search the MSDN Forums for posts related to this error** link to navigate to the Microsoft Developer Network forums. You may want to specifically search the [Windows Forms Designer](https://social.msdn.microsoft.com/Forums/windows/home?forum=winformsdesigner) or [Windows Forms](https://social.msdn.microsoft.com/Forums/windows/home?category=windowsforms) forums. + +## Design-time errors + +This section lists some of the errors you may encounter. + +### '\' is not a valid identifier + +This error indicates that a field, method, event, or object is improperly named. + +### '\' already exists in '\' + +Error message: "'\' already exists in '\'. Please enter a unique name." + +You've specified a name for an inherited form that already exists in the project. To correct this error, give the inherited form a unique name. + +### '\' is not a toolbox category + +A third-party designer has tried to access a tab on the Toolbox that does not exist. Contact the component vendor. + +### A requested language parser is not installed + +Error message: "A requested language parser is not installed. The language parser name is '{0}'." + +Visual Studio attempted to a load a designer that's registered for the file type but could not. This is most likely because of an error that occurred during setup. Contact the vendor of the language you're using for a fix. + +### A service required for generating and parsing source code is missing + +This is a problem with a third-party component. Contact the component vendor. + +### An exception occurred while trying to create an instance of '\' + +Error message: "An exception occurred while trying to create an instance of '\'. The exception was "\". + +A third-party designer requested that Visual Studio create an object, but the object raised an error. Contact the component vendor. + +### Another editor has '\' open in an incompatible mode + +Error message: "Another editor has '\' open in an incompatible mode. Please close the editor and try this operation again." + +This error arises if you try to open a file that is already opened in another editor. The editor that already has the file open is shown. To correct this error, close the editor that has the file open, and try again. + +### Another editor has made changes to '\' + +Close and reopen the designer for the changes to take effect. Normally, Visual Studio automatically reloads a designer after changes are made. However, other designers, such as third-party component designers, may not support reload behavior. In this case, Visual Studio prompts you to close and reopen the designer manually. + +### Another editor has the file open in an incompatible mode + +Error message: "Another editor has the file open in an incompatible mode. Please close the editor and try this operation again." + +This message is similar to "Another editor has '\' open in an incompatible mode", but Visual Studio is unable to determine the file name. To correct this error, close the editor that has the file open, and try again. + +### Array rank '\' is too high + +Visual Studio only supports single-dimension arrays in the code block that's parsed by the designer. Multidimensional arrays are valid outside this area. + +### Assembly '\' could not be opened + +Error message: "Assembly '\' could not be opened. Verify that the file still exists." + +This error message arises when you try to open a file that could not be opened. Verify that the file exists and is a valid assembly. + +### Bad element type. This serializer expects an element of type '\' + +This is a problem with a third-party component. Contact the component vendor. + +### Cannot access the Visual Studio Toolbox at this time + +Visual Studio made a call to the Toolbox, which was not available. If you see this error, If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### Cannot bind an event handler to the '\' event because it is read-only + +This error most often arises when you've tried to connect an event to a control that's inherited from a base class. If the control's member variable is private, Visual Studio cannot connect the event to the method. Privately inherited controls cannot have additional events bound to them. + +### Cannot create a method name for the requested component because it is not a member of the design container + +Visual Studio has tried to add an event handler to a component that does not have a member variable in the designer. Contact the component vendor. + +### Cannot name the object '\' because it is already named '\' + +This is an internal error in the Visual Studio serializer. It indicates that the serializer has tried to name an object twice, which is not supported. If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### Cannot remove or destroy inherited component '\' + +Inherited controls are under the ownership of their inheriting class. Changes to the inherited control must be made in the class from which the control originates. Thus, you cannot rename or destroy it. + +### Category '\' does not have a tool for class '\' + +The designer tried to reference a class on a particular Toolbox tab, but the class does not exist. Contact the component vendor. + +### Class '\' has no matching constructor + +A third-party designer has asked Visual Studio to create an object with particular parameters in the constructor that does not exist. Contact the component vendor. + +### Code generation for property '\' failed + +This is a generic wrapper for an error. The error string that accompanies this message will give more details about the error message and have a link to a more specific help topic. To correct this error, address the error specified in the error message appended to this error. + +### Component '\' did not call Container.Add() in its constructor + +This is an error in the component you just loaded or placed on the form. It indicates that the component did not add itself to its container control (whether that is another control or a form). The designer will continue to work, but there may be problems with the component at run time. + +To correct the error, contact the component vendor. Or, if it is a component you created, call the `IContainer.Add` method in the component's constructor. + +### Component name cannot be empty + +This error arises when you try to rename a component to an empty value. + +### Could not access the variable '\' because it has not been initialized yet + +This error can arise because of two scenarios. Either a third-party component vendor has a problem with a control or component they have distributed, or the code you have written has recursive dependencies between components. + +To correct this error, ensure that your code does not have a recursive dependency. If it is free of such problems, note the exact text of the error message and contact the component vendor. + +### Could not find type '\' + +Error message: "Could not find type '\'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built." + +This error occurred because a reference was not found. Make sure the type indicated in the error message is referenced, and that any assemblies that the type requires are also referenced. Often, the problem is that a control in the solution has not been built. To build, select **Build Solution** from the **Build** menu. Otherwise, if the control has already been built, add a reference manually from the right-click menu of the **References** or **Dependencies** folder in Solution Explorer. + +### Could not load type '\' + +Error message: "Could not load type '\'. Please make sure that the assembly containing this type is added to the project references." + +Visual Studio attempted to wire up an event-handling method and could not find one or more parameter types for the method. This is usually caused by a missing reference. To correct this error, add the reference containing the type to the project and try again. + +### Could not locate the project item templates for inherited components + +The templates for inherited forms in Visual Studio are not available. If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### Delegate class '\' has no invoke method. Is this class a delegate? + +Visual Studio has tried to create an event handler, but there is something wrong with the event type. This can happen if the event was created by a non-CLS-compliant language. Contact the component vendor. + +### Duplicate declaration of member '\' + +This error arises because a member variable has been declared twice (for example, two controls named `Button1` are declared in the code). Names must be unique across inherited forms. Additionally, names cannot differ only by case. + +### Error reading resources from the resource file for the culture '\' + +This error can occur if there is a bad .resx file in the project. + +To correct this error: + +1. Click the **Show All Files** button in Solution Explorer to view the .resx files associated with the solution. +2. Load the .resx file in the XML Editor by right-clicking the .resx file and choosing **Open**. +3. Edit the .resx file manually to address the errors. + +### Error reading resources from the resource file for the default culture '\' + +This error can occur if there is a bad .resx file in the project for the default culture. + +To correct this error: + +1. Click the **Show All Files** button in Solution Explorer to view the .resx files associated with the solution. +2. Load the .resx file in the XML Editor by right-clicking the .resx file and choosing **Open**. +3. Edit the .resx file manually to address the errors. + +### Failed to parse method '\' + +Error message: "Failed to parse method '\'. The parser reported the following error: '\'. Please look in the Task List for potential errors." + +This is a general error message for problems that arise during parsing. These errors are often due to syntax errors. See the Task List for specific messages related to the error. + +### Invalid component name: '\' + +You've tried to rename a component to an invalid value for that language. To correct this error, name the component such that it complies with the naming rules for that language. + +### The type '\' is made of several partial classes in the same file + +When you define a class in multiple files by using the [partial](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/partial-type) keyword, you can only have one partial definition in each file. + +To correct this error, remove all but one of the partial definitions of your class from the file. + +### The assembly '\' could not be found + +Error message: "The assembly '\' could not be found. Ensure that the assembly is referenced. If the assembly is part of the current development project, ensure that the project has been built." + +This error is similar to "The type '\' could not be found", but this error usually happens because of a metadata attribute. To correct this error, check that all assemblies used by attributes are referenced. + +### The assembly name '\' is invalid + +A component has requested a particular assembly, but the name provided by the component is not a valid assembly name. Contact the component vendor. + +### The base class '\' cannot be designed + +Visual Studio loaded the class, but the class cannot be designed because the implementer of the class did not provide a designer. If the class supports a designer, make sure there are no problems that would cause issues with displaying it in a designer, such as compiler errors. Also, make sure that all references to the class are correct and all class names are correctly spelled. Otherwise, if the class is not designable, edit it in Code view. + +### The base class '\' could not be loaded + +The class is not referenced in the project, so Visual Studio can't load it. To correct this error, add a reference to the class in the project, and close and reopen the Windows Forms Designer window. + +### The class '\' cannot be designed in this version of Visual Studio + +The designer for this control or component does not support the same types that Visual Studio does. Contact the component vendor. + +### The class name is not a valid identifier for this language + +The source code being created by the user has a class name that is not valid for the language being used. To correct this error, name the class such that it conforms to the language requirements. + +### The component cannot be added because it contains a circular reference to '\' + +You cannot add a control or component to itself. Another situation where this might occur is if there is code in the InitializeComponent method of a form (for example, Form1) that creates another instance of Form1. + +### The designer cannot be modified at this time + +This error occurs when the file in the editor is marked as read-only. Ensure that the file is not marked read-only and the application is not running. + +### The designer could not be shown for this file because none of the classes within it can be designed + +This error occurs when Visual Studio cannot find a base class that satisfies designer requirements. Forms and controls must derive from a base class that supports designers. If you're deriving from an inherited form or control, make sure the project has been built. + +### The designer for base class '\' is not installed + +Visual Studio could not load the designer for the class. If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### The designer must create an instance of type '\', but it can't because the type is declared as abstract + +This error occurred because the base class of the object being passed to the designer is [abstract](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/abstract), which is not allowed. + +### The file could not be loaded in the designer + +The base class of this file does not support any designers. As a workaround, use Code view to work on the file. Right-click the file in Solution Explorer and choose **View Code**. + +### The language for this file does not support the necessary code parsing and generation services + +Error message: "The language for this file does not support the necessary code parsing and generation services. Please ensure the file you are opening is a member of a project and then try to open the file again." + +This error most likely resulted from opening a file that's in a project that does not support designers. + +### The language parser class '\' is not implemented properly + +Error message: "The language parser class '\' is not implemented properly. Contact the vendor for an updated parser module." + +The language in use has registered a designer class that doesn't derive from the correct base class. Contact the vendor of the language you're using. + +### The name '\' is already used by another object + +This is an internal error in the Visual Studio serializer. If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### The object '\' does not implement the IComponent interface + +Visual Studio tried to create a component, but the object created does not implement the interface. Contact the component vendor for a fix. + +### The object '\' returned null for the property '\' but this is not allowed + +There are some .NET properties that should always return an object. For example, the **Controls** collection of a form should always return an object, even when there are no controls in it. + +To correct this error, ensure that the property specified in the error is not null. + +### The serialization data object is not of the proper type + +A data object offered by the serializer is not an instance of a type that matches the current serializer being used. Contact the component vendor. + +### The service '\' is required, but could not be located + +Error message: "The service '\' is required, but could not be located. There may be a problem with your Visual Studio installation." + +A service required by Visual Studio is unavailable. If you were trying to load a project that does not support that designer, use the Code Editor to make the changes you require. Otherwise, If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### The service instance must derive from or implement '\' + +This error indicates that a component or component designer has called the **AddService** method, which requires an interface and object, but the object specified does not implement the interface specified. Contact the component vendor. + +### The text in the code window could not be modified + +Error message: "The text in the code window could not be modified. Check that the file is not read-only and there is sufficient disk space." + +This error occurs when Visual Studio is unable to edit a file due to disk space or memory problems, or the file is marked read-only. + +### The Toolbox enumerator object only supports retrieving one item at a time + +If you see this error, If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### The Toolbox item for '\' could not be retrieved from the Toolbox + +Error message: "The Toolbox item for '\' could not be retrieved from the Toolbox. Make sure the assembly that contains the Toolbox item is correctly installed. The Toolbox item raised the following error: \." + +The component in question threw an exception when Visual Studio accessed it. Contact the component vendor. + +### The Toolbox item for '\' could not be retrieved from the Toolbox + +Error message: "The Toolbox item for '\' could not be retrieved from the Toolbox. Try removing the item from the Toolbox and adding it back." + +This error occurs if the data within the Toolbox item becomes corrupted or the version of the component has changed. Try removing the item from the Toolbox and adding it back again. + +### The type '\' could not be found + +Error message: "The type '\' could not be found. Ensure that the assembly containing the type is referenced. If the assembly is part of the current development project, ensure that the project has been built." + +While loading the designer, Visual Studio failed to find a type. Ensure that the assembly containing the type is referenced. If the assembly is part of the current development project, ensure that the project has been built. + +### The type resolution service may only be called from the main application thread + +Visual Studio attempted to access required resources from the wrong thread. This error is displayed when the code used to create the designer has called the type resolution service from a thread other than the main application thread. To correct this error, call the service from the correct thread or contact the component vendor. + +### The variable '\' is either undeclared or was never assigned + +The source code has a reference to a variable, such as **Button1**, that isn't declared or assigned. If the variable has not been assigned, this message appears as a warning, not an error. + +### There is already a command handler for the menu command '\' + +This error arises if a third-party designer adds a command that already has a handler to the command table. Contact the component vendor. + +### There is already a component named '\' + +Error message: "There is already a component named '\'. Components must have unique names, and names must not be case-sensitive. A name also cannot conflict with the name of any component in an inherited class." + +This error message arises when there has been a change to the name of a component in the Properties window. To correct this error, ensure that all component names are unique, are not case-sensitive, and do not conflict with the names of any components in the inherited classes. + +### There is already a Toolbox item creator registered for the format '\' + +A third-party component made a callback to an item on a Toolbox tab, but the item already contained a callback. Contact the component vendor. + +### This language engine does not support a CodeModel with which to load a designer + +This message is similar to "The language for this file does not support the necessary code parsing and generation services", but this message involves an internal registration problem. If you see this error, If you see this error, please log an issue by using [Report a Problem](/visualstudio/ide/how-to-report-a-problem-with-visual-studio). + +### Type '\' does not have a constructor with parameters of types '\' + +Visual Studio could not find a [constructor](https://docs.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/constructors) that had matching parameters. This may be the result of supplying a constructor with types other than those that are required. For example, a **Point** constructor might take two integers. If you provided floats, this error is raised. + +To correct this error, use a different constructor or explicitly cast the parameter types such that they match those provided by the constructor. + +### Unable to add reference '\' to the current application + +Error message: "Unable to add reference '\' to the current application. Check that a different version of '\' is not already referenced." + +Visual Studio is unable to add a reference. To correct this error, check that a different version of the reference is not already referenced. + +### Unable to check out the current file + +Error message: "Unable to check out the current file. The file may be locked, or you may need to check out the file manually." + +This error arises when you change a file that's currently checked in to source-code control. Usually, Visual Studio presents the file checkout dialog box so that the user can check out the file. This time, the file was not checked out, perhaps because of a merge conflict during checkout. To correct this error, ensure that the file is not locked, and then try to check out the file manually. + +### Unable to find page named '\' + +This error arises when a component designer requests access to a page from the Options dialog box by using a name that does not exist. Contact the component vendor. + +### Unable to find property '\' on page '\' + +This error arises when a component designer requests access to a particular value on a page from the Options dialog box, but that value does not exist. Contact the component vendor. + +### Visual Studio cannot open a designer for the file because the class within it does not inherit from a class that can be visually designed + +Visual Studio loaded the class, but the designer for that class could not be loaded. Visual Studio requires that designers use the first class in a file. To correct this error, move the class code so that it is the first class in the file, and then load the designer again. + +### Visual Studio cannot save or load instances of the type '\' + +This is a problem with a third-party component. Contact the component vendor. + +### Visual Studio is unable to open '\' in Design view + +Error message: "Visual Studio is unable to open '\' in Design view. No parser is installed for the file type." + +This error indicates that the language of the project does not support a designer and arises when you attempt to open a file in the Open File dialog box or from Solution Explorer. Instead, edit the file in Code view. + +### Visual Studio was unable to find a designer for classes of type '\' + +Visual Studio loaded the class, but the class cannot be designed. Instead, edit the class in Code view by right-clicking the class and choosing **View Code**. + +## See also + +- [Develop Windows Forms controls using the designer](developing-windows-forms-controls-at-design-time.md) +- [Windows Forms Designer forum](https://social.msdn.microsoft.com/Forums/windows/home?forum=winformsdesigner) diff --git a/dotnet-desktop-guide/framework/winforms/controls/designate-a-wf-button-as-the-accept-button-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/designate-a-wf-button-as-the-accept-button-using-the-designer.md new file mode 100644 index 0000000000..02e83112e4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/designate-a-wf-button-as-the-accept-button-using-the-designer.md @@ -0,0 +1,27 @@ +--- +title: Designate a Button as the Accept Button Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "buttons [Windows Forms], default on Windows Forms" + - "Accept button on Windows Forms" + - "Button control [Windows Forms], designating as default" + - "Windows Forms controls, default button on form" +ms.assetid: a1da0590-755f-49f2-aca7-609fac6351bf +--- +# How to: Designate a Windows Forms Button as the Accept Button Using the Designer +On any Windows Form, you can designate a control to be the accept button, also known as the default button. Whenever the user presses the ENTER key, the default button is clicked regardless of which other control on the form has the focus. The exceptions to this are when the control with focus is another button — in that case, the button with the focus will be clicked — or a multiline text box, or a custom control that traps the ENTER key. + +## To designate the accept button + +1. Select the form on which the button resides. + +2. In the **Properties** window, set the form's property to the control's name. + +## See also + +- +- [Button Control Overview](button-control-overview-windows-forms.md) +- [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [How to: Designate a Windows Forms Button as the Cancel Button Using the Designer](designate-a-wf-button-as-the-cancel-button-using-the-designer.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/designate-a-wf-button-as-the-cancel-button-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/designate-a-wf-button-as-the-cancel-button-using-the-designer.md new file mode 100644 index 0000000000..fd5b4387fb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/designate-a-wf-button-as-the-cancel-button-using-the-designer.md @@ -0,0 +1,25 @@ +--- +title: Designate a Button as the Cancel Button Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "buttons [Windows Forms], cancel buttons" + - "Button control [Windows Forms], designating as cancel button" +ms.assetid: 30e77d9c-d565-4ab5-a84a-62c043af8822 +--- +# How to: Designate a Windows Forms Button as the Cancel Button Using the Designer +On any Windows Form, you can designate a control to be the cancel button. A cancel button is clicked whenever the user presses the ESC key, regardless of which other control on the form has the focus. Such a button is usually programmed to enable the user to quickly exit an operation without committing to any action. + +## To designate the cancel button + +1. Select the form on which the button resides. + +2. In the **Properties** window, set the form's property to the control's name. + +## See also + +- +- [Button Control Overview](button-control-overview-windows-forms.md) +- [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [How to: Designate a Windows Forms Button as the Accept Button Using the Designer](designate-a-wf-button-as-the-accept-button-using-the-designer.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/determine-when-formatting-attributes-change-wf-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/determine-when-formatting-attributes-change-wf-richtextbox-control.md new file mode 100644 index 0000000000..1c3227506c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/determine-when-formatting-attributes-change-wf-richtextbox-control.md @@ -0,0 +1,82 @@ +--- +title: Determine When Formatting Attributes Change in RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], text boxes" + - "RichTextBox control [Windows Forms], determining font changes" + - "text boxes [Windows Forms], determining font changes" + - "SelChange event" +ms.assetid: bdfed015-f77a-41e5-b38f-f8629b2fa166 +--- +# How to: Determine When Formatting Attributes Change in the Windows Forms RichTextBox Control +A common use of the Windows Forms control is formatting text with attributes such as font options or paragraph styles. Your application may need to keep track of any changes in text formatting for the purpose of displaying a toolbar, as in many word-processing applications. + +### To respond to changes in formatting attributes + +1. Write code in the event handler to perform an appropriate action depending on the value of the attribute. The following example changes the appearance of a toolbar button depending on the value of the property. The toolbar button will only be updated when the insertion point is moved in the control. + + The example below assumes a form with a control and a control that contains a toolbar button. For more information about toolbars and toolbar buttons, see [How to: Add Buttons to a ToolBar Control](how-to-add-buttons-to-a-toolbar-control.md). + + ```vb + ' The following code assumes the existence of a toolbar control + ' with at least one toolbar button. + Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged + If RichTextBox1.SelectionBullet = True Then + ' Bullet button on toolbar should appear pressed + ToolBarButton1.Pushed = True + Else + ' Bullet button on toolbar should appear unpressed + ToolBarButton1.Pushed = False + End If + End Sub + ``` + + ```csharp + // The following code assumes the existence of a toolbar control + // with at least one toolbar button. + private void richTextBox1_SelectionChanged(object sender, + System.EventArgs e) + { + if (richTextBox1.SelectionBullet == true) + { + // Bullet button on toolbar should appear pressed + toolBarButton1.Pushed = true; + } + else + { + // Bullet button on toolbar should appear unpressed + toolBarButton1.Pushed = false; + } + } + ``` + + ```cpp + // The following code assumes the existence of a toolbar control + // with at least one toolbar button. + private: + System::Void richTextBox1_SelectionChanged( + System::Object ^ sender, System::EventArgs ^ e) + { + if (richTextBox1->SelectionBullet == true) + { + // Bullet button on toolbar should appear pressed + toolBarButton1->Pushed = true; + } + else + { + // Bullet button on toolbar should appear unpressed + toolBarButton1->Pushed = false; + } + } + ``` + +## See also + +- +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/determine-which-panel-wf-statusbar-control-was-clicked.md b/dotnet-desktop-guide/framework/winforms/controls/determine-which-panel-wf-statusbar-control-was-clicked.md new file mode 100644 index 0000000000..88e7211fa5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/determine-which-panel-wf-statusbar-control-was-clicked.md @@ -0,0 +1,96 @@ +--- +title: Determine Which Panel in StatusBar Control Was Clicked +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "status bars [Windows Forms], determining panel clicked" + - "panels [Windows Forms], determining clicked" + - "StatusBar control [Windows Forms], coding panel click events" + - "StatusBar control [Windows Forms], determining panel clicked" + - "PanelClick event [Windows Forms], determining panel clicked" + - "Panel control [Windows Forms], determining click" +ms.assetid: d14c6092-04b2-4a07-8ddf-0dd11277ff5f +--- +# How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked +> [!IMPORTANT] +> The and controls replace and add functionality to the and controls; however, the and controls are retained for both backward compatibility and future use, if you choose. + + To program the [StatusBar Control](statusbar-control-windows-forms.md) control to respond to user clicks, use a case statement within the event. The event contains an argument (the panel argument), which contains a reference to the clicked . Using this reference, you can determine the index of the clicked panel, and program accordingly. + +> [!NOTE] +> Ensure that the control's property is set to `true`. + +### To determine which panel was clicked + +1. In the event handler, use a `Select Case` (in Visual Basic) or `switch case` (Visual C# or Visual C++) statement to determine which panel was clicked by examining the index of the clicked panel in the event arguments. + + The following code example requires the presence, on the form, of a control, `StatusBar1`, and two objects, `StatusBarPanel1` and `StatusBarPanel2`. + + ```vb + Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.StatusBarPanelClickEventArgs) Handles StatusBar1.PanelClick + Select Case StatusBar1.Panels.IndexOf(e.StatusBarPanel) + Case 0 + MessageBox.Show("You have clicked Panel One.") + Case 1 + MessageBox.Show("You have clicked Panel Two.") + End Select + End Sub + ``` + + ```csharp + private void statusBar1_PanelClick(object sender, + System.Windows.Forms.StatusBarPanelClickEventArgs e) + { + switch (statusBar1.Panels.IndexOf(e.StatusBarPanel)) + { + case 0 : + MessageBox.Show("You have clicked Panel One."); + break; + case 1 : + MessageBox.Show("You have clicked Panel Two."); + break; + } + } + ``` + + ```cpp + private: + void statusBar1_PanelClick(System::Object ^ sender, + System::Windows::Forms::StatusBarPanelClickEventArgs ^ e) + { + switch (statusBar1->Panels->IndexOf(e->StatusBarPanel)) + { + case 0 : + MessageBox::Show("You have clicked Panel One."); + break; + case 1 : + MessageBox::Show("You have clicked Panel Two."); + break; + } + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.statusBar1.PanelClick += new + System.Windows.Forms.StatusBarPanelClickEventHandler + (this.statusBar1_PanelClick); + ``` + + ```cpp + this->statusBar1->PanelClick += gcnew + System::Windows::Forms::StatusBarPanelClickEventHandler + (this, &Form1::statusBar1_PanelClick); + ``` + +## See also + +- +- +- [How to: Set the Size of Status-Bar Panels](how-to-set-the-size-of-status-bar-panels.md) +- [Walkthrough: Updating Status Bar Information at Run Time](walkthrough-updating-status-bar-information-at-run-time.md) +- [StatusBar Control Overview](statusbar-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/developing-a-composite-windows-forms-control.md b/dotnet-desktop-guide/framework/winforms/controls/developing-a-composite-windows-forms-control.md new file mode 100644 index 0000000000..81df46cdf5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/developing-a-composite-windows-forms-control.md @@ -0,0 +1,51 @@ +--- +title: Develop a Composite Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], composite controls" + - "composite controls [Windows Forms]" + - "composite controls [Windows Forms], Windows Forms" + - "controls [Windows Forms], composite" +ms.assetid: d086f2a3-baa3-4e09-b40c-a5bb3cfc51a6 +--- +# Develop a composite Windows Forms control + +You can develop a composite Windows Forms control by combining other Windows Forms controls. Composite controls that derive from are called user controls. The base class, , provides keyboard routing for the child controls, thus ensuring that child controls can receive focus. For an example of a user control, see the sample in [How to: Apply Attributes in Windows Forms Controls](how-to-apply-attributes-in-windows-forms-controls.md). + +The Windows Forms designer in Visual Studio provides rich design-time support for authoring user controls. + +- [How to: Display a Control in the Choose Toolbox Items Dialog Box](how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md) + +- [Walkthrough: Serializing Collections of Standard Types with the DesignerSerializationVisibilityAttribute](serializing-collections-designerserializationvisibilityattribute.md) + +- [Walkthrough: Inheriting from a Windows Forms Control with Visual C#](walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md) + +- [How to: Provide a Toolbox Bitmap for a Control](how-to-provide-a-toolbox-bitmap-for-a-control.md) + +- [How to: Inherit from Existing Windows Forms Controls](how-to-inherit-from-existing-windows-forms-controls.md) + +- [Walkthrough: Debugging Custom Windows Forms Controls at Design Time](walkthrough-debugging-custom-windows-forms-controls-at-design-time.md) + +- [How to: Inherit from the Control Class](how-to-inherit-from-the-control-class.md) + +- [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md) + +- [How to: Align a Control to the Edges of Forms at Design Time](how-to-align-a-control-to-the-edges-of-forms-at-design-time.md) + +- [How to: Inherit from the UserControl Class](how-to-inherit-from-the-usercontrol-class.md) + +- [How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md) + +- [How to: Author Composite Controls](how-to-author-composite-controls.md) + +- [Walkthrough: Authoring a Composite Control with Visual C#](walkthrough-authoring-a-composite-control-with-visual-csharp.md) + +- [Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md) + +- [How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/307hck25(v=vs.120)) + +## See also + +- [How to: Apply Attributes in Windows Forms Controls](how-to-apply-attributes-in-windows-forms-controls.md) +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/developing-custom-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/developing-custom-windows-forms-controls.md new file mode 100644 index 0000000000..4493925d8a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/developing-custom-windows-forms-controls.md @@ -0,0 +1,58 @@ +--- +title: Develop Custom Controls +description: Learn about Windows Form controls. Specifically, you'll learn to combine existing controls, extend existing controls, and author your own custom controls. +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], developing using code" + - "Control class [Windows Forms], Windows Forms" +ms.assetid: 236cebc0-bd71-4f18-9fd6-5d0e592375df +--- +# Developing Custom Windows Forms Controls with the .NET Framework +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. This section provides background information and samples to help you develop Windows Forms controls. + +## In This Section + [Overview of Using Controls in Windows Forms](overview-of-using-controls-in-windows-forms.md) + Highlights the essential elements of using controls in Windows Forms applications. + + [Varieties of Custom Controls](varieties-of-custom-controls.md) + Describes the different kinds of custom controls you can author with the namespace. + + [Windows Forms Control Development Basics](windows-forms-control-development-basics.md) + Discusses the first steps in developing a Windows Forms control. + + [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) + Shows how to add to properties to Windows Forms controls. + + [Events in Windows Forms Controls](events-in-windows-forms-controls.md) + Shows how to handle and define events in Windows Forms controls. + + [Attributes in Windows Forms Controls](attributes-in-windows-forms-controls.md) + Describes the attributes you can apply to properties or other members of your custom controls and components. + + [Custom Control Painting and Rendering](custom-control-painting-and-rendering.md) + Shows how to customize the appearance of your controls. + + [Layout in Windows Forms Controls](layout-in-windows-forms-controls.md) + Shows how to create sophisticated layouts for your controls and forms. + + [Multithreading in Windows Forms Controls](multithreading-in-windows-forms-controls.md) + Shows how to implement multithreaded controls. + +## Reference + + Describes this class and has links to all of its members. + + + Describes this class and has links to all of its members. + +## Related Sections + [Design-Time Attributes for Components](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/tk67c2t8(v=vs.120)) + Lists metadata attributes to apply to components and controls so that they are displayed correctly at design time in visual designers. + + [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)) + Describes how to implement classes such as editors and designers that provide design-time support. + + [How to: License Components and Controls](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/fe8b1eh9(v=vs.120)) + Describes how to implement licensing in your control or component. + + Also see [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md). diff --git a/dotnet-desktop-guide/framework/winforms/controls/developing-windows-forms-controls-at-design-time.md b/dotnet-desktop-guide/framework/winforms/controls/developing-windows-forms-controls-at-design-time.md new file mode 100644 index 0000000000..70df82084d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/developing-windows-forms-controls-at-design-time.md @@ -0,0 +1,93 @@ +--- +title: Develop Controls at Design Time +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls [Windows Forms]" + - "Windows Forms controls, creating" + - "controls [Windows Forms]" + - "controls [Windows Forms], creating" + - "user controls [Windows Forms]" + - "custom controls [Windows Forms]" +ms.assetid: e5a8e088-7ec8-4fd9-bcb3-9078fd134829 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Develop Windows Forms controls at design time + +For control authors, the .NET Framework provides a wealth of control authoring technology. Authors are no longer limited to designing composite controls that act as a collection of preexisting controls. Through inheritance, you can create your own controls from preexisting composite controls or preexisting Windows Forms controls. You can also design your own controls that implement custom painting. These options enable a great deal of flexibility to the design and functionality of the visual interface. To take advantage of these features, you should be familiar with object-based programming concepts. + +> [!NOTE] +> It is not necessary to have a thorough understanding of inheritance, but you may find it useful to refer to [Inheritance basics (Visual Basic)](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/inheritance-basics). + +If you want to create custom controls to use on Web Forms, see [Developing Custom ASP.NET Server Controls](https://docs.microsoft.com/previous-versions/aspnet/zt27tfhy(v=vs.100)). + +## In this section + +[Walkthrough: Authoring a Composite Control](walkthrough-authoring-a-composite-control-with-visual-csharp.md)\ +Shows how to create a simple composite control in C#. + +[Walkthrough: Inheriting from a Windows Forms Control](walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md)\ +Shows how to create a simple Windows Forms control using inheritance in C#. + +[Walkthrough: Perform common tasks using designer actions](perform-common-tasks-design-actions.md)\ +Shows how to use the smart tag feature on Windows Forms controls. + +[Walkthrough: Serializing Collections of Standard Types with the DesignerSerializationVisibilityAttribute](serializing-collections-designerserializationvisibilityattribute.md)\ +Shows how to use the attribute to serialize a collection. + +[Walkthrough: Debugging Custom Windows Forms Controls at Design Time](walkthrough-debugging-custom-windows-forms-controls-at-design-time.md)\ +Shows how to debug the design-time behavior of a Windows Forms control. + +[Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md)\ +Shows how to tightly integrate a composite control into the design environment. + +[How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md)\ +Provides an overview of considerations for implementing a Windows Forms control. + +[How to: Author Composite Controls](how-to-author-composite-controls.md)\ +Shows how to create a control by inheriting from a composite control. + +[How to: Inherit from the UserControl Class](how-to-inherit-from-the-usercontrol-class.md)\ +Provides an overview of the procedure for creating a composite control. + +[How to: Inherit from Existing Windows Forms Controls](how-to-inherit-from-existing-windows-forms-controls.md)\ +Shows how to create an extended control by inheriting from the control class. + +[How to: Inherit from the Control Class](how-to-inherit-from-the-control-class.md)\ +Provides an overview of creating an extended control. + +[How to: Align a Control to the Edges of Forms at Design Time](how-to-align-a-control-to-the-edges-of-forms-at-design-time.md)\ +Shows how to use the property to align your control to the edge of the form it occupies. + +[How to: Display a Control in the Choose Toolbox Items Dialog Box](how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md)\ +Shows the procedure for installing your control so that it appears in the **Customize Toolbox** dialog box. + +[How to: Provide a Toolbox Bitmap for a Control](how-to-provide-a-toolbox-bitmap-for-a-control.md)\ +Shows how to use the to display an icon next to your custom control in the **Toolbox**. + +[How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md)\ +Shows how to use the **UserControl Test Container** to test the behavior of a composite control. + +[Design-Time Errors in the Windows Forms Designer](design-time-errors-in-the-windows-forms-designer.md)\ +Explains the meaning and use of the Design-Time Error List that appears in Microsoft Visual Studio when the Windows Forms designer fails to load. + +[Troubleshooting Control and Component Authoring](troubleshooting-control-and-component-authoring.md)\ +Shows how to diagnose and fix common issues that can occur when you author a custom component or control. + +## Reference + +- + +- + +## Related sections + +[Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md)\ +Discusses how to create your own custom controls with the .NET Framework. + +[Language Independence and Language-Independent Components](https://docs.microsoft.com/dotnet/standard/language-independence-and-language-independent-components)\ +Introduces the common language runtime, which is designed to simplify the creation and use of components. An important aspect of this simplification is enhanced interoperability between components written using different programming languages. The Common Language Specification (CLS) makes it possible to create tools and components that work with multiple programming languages. + +[Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md)\ +Describes how to enable your component or control to be displayed in the **Customize Toolbox** dialog box. diff --git a/dotnet-desktop-guide/framework/winforms/controls/dialog-box-controls-and-components-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/dialog-box-controls-and-components-windows-forms.md new file mode 100644 index 0000000000..25b5b391c5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/dialog-box-controls-and-components-windows-forms.md @@ -0,0 +1,64 @@ +--- +title: "Dialog-Box Controls and Components" +ms.date: "03/30/2017" +helpviewer_keywords: + - "CommonDialog control" + - "Windows Forms dialog boxes [Windows Forms], predefined" + - "dialog boxes [Windows Forms], Windows Forms" + - "Windows Forms, dialog boxes" +ms.assetid: 6e5f5e9e-58d6-45f3-9df0-48b7bb6bfd5c +--- +# Dialog-Box Controls and Components (Windows Forms) +The following Windows Forms controls and components present standard dialog boxes. Follow the links for more information about the functions available in each dialog box. + +## Reference + + Provides reference information about the class and its members. + + + Provides reference information about the class and its members. + + + Provides reference information about the class and its members. + + + Provides reference information about the class and its members. + + + Provides reference information about the class and its members. + + + Provides reference information about the class and its members. + + + Provides reference information about the class and its members. + +## Related Sections + [Dialog Boxes in Windows Forms](../dialog-boxes-in-windows-forms.md) + Describes how to create a dialog box for a Windows Form. + + [ColorDialog Component Overview](colordialog-component-overview-windows-forms.md) + Enables the user to select a color from a palette in a pre-configured dialog box and to add custom colors to that palette. + + [FolderBrowserDialog Component Overview (Windows Forms)](folderbrowserdialog-component-overview-windows-forms.md) + Enables users to browse and select folders. + + [FontDialog Component Overview](fontdialog-component-overview-windows-forms.md) + Exposes the fonts that are currently installed on the system. + + [OpenFileDialog Component Overview](openfiledialog-component-overview-windows-forms.md) + Allows users to open files via a pre-configured dialog box. + + [PageSetupDialog Component Overview](pagesetupdialog-component-overview-windows-forms.md) + Sets page details for printing via a pre-configured dialog box. + + [PrintDialog Component Overview](printdialog-component-overview-windows-forms.md) + Selects a printer, chooses the pages to print, and determines other print-related settings. + + [PrintPreviewDialog Control Overview](printpreviewdialog-control-overview-windows-forms.md) + Displays a document as it will appear when it is printed. + + [SaveFileDialog Component Overview](savefiledialog-component-overview-windows-forms.md) + Selects files to save and where to save them. + + Also see [Dialog Boxes in Windows Forms](../dialog-boxes-in-windows-forms.md). diff --git a/dotnet-desktop-guide/framework/winforms/controls/differences-between-the-windows-forms-datagridview-and-datagrid-controls.md b/dotnet-desktop-guide/framework/winforms/controls/differences-between-the-windows-forms-datagridview-and-datagrid-controls.md new file mode 100644 index 0000000000..a5581b0c6d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/differences-between-the-windows-forms-datagridview-and-datagrid-controls.md @@ -0,0 +1,45 @@ +--- +title: Differences Between DataGridView and DataGrid Controls +description: Learn the various differences between Windows Forms DataGridView and DataGrid controls features, as well as differences in their architecture. +ms.date: "03/30/2017" +helpviewer_keywords: + - "data grids [Windows Forms" + - "DataGrid control [Windows Forms], DataGridView control compared" + - "DataGridView control [Windows Forms], DataGrid control compared" +ms.assetid: d412c786-140e-4210-8a56-a68467530a55 +--- +# Differences Between the Windows Forms DataGridView and DataGrid Controls +The control is a new control that replaces the control. The control provides numerous basic and advanced features that are missing in the control. Additionally, the architecture of the control makes it much easier to extend and customize than the control. + + The following table describes a few of the primary features available in the control that are missing from the control. + +|DataGridView control feature|Description| +|----------------------------------|-----------------| +|Multiple column types|The control provides more built-in column types than the control. These column types meet the needs of most common scenarios, but are also easier to extend or replace than the column types in the control. For more information, see [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md).| +|Multiple ways to display data|The control is limited to displaying data from an external data source. The control, however, can display unbound data stored in the control, data from a bound data source, or bound and unbound data together. You can also implement virtual mode in the control to provide custom data management. For more information, see [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md).| +|Multiple ways to customize the display of data|The control provides many properties and events that enable you to specify how data is formatted and displayed. For example, you can change the appearance of cells, rows, and columns depending on the data they contain, or you can replace data of one data type with equivalent data of another type. For more information, see [Data Formatting in the Windows Forms DataGridView Control](data-formatting-in-the-windows-forms-datagridview-control.md).| +|Multiple options for changing cell, row, column, and header appearance and behavior|The control enables you to work with individual grid components in numerous ways. For example, you can freeze rows and columns to prevent them from scrolling; hide rows, columns, and headers; change the way row, column, and header sizes are adjusted; change the way users make selections; and provide ToolTips and shortcut menus for individual cells, rows, and columns.| + + The control is retained for backward compatibility and for special needs. For nearly all purposes, you should use the control. The only feature that is available in the control that is not available in the control is the hierarchical display of information from two related tables in a single control. You must use two controls to display information from two tables that are in a master/detail relationship. + +## Upgrading to the DataGridView Control + If you have existing applications that use the control in a simple data-bound scenario without customizations, you can simply replace the old control with the new control. Both controls use the standard Windows Forms data-binding architecture, so the control will display your bound data with no additional configuration needed. You might want to consider taking advantage of data-binding improvements, however, by binding your data to a component, which you can then bind to the control. For more information, see [BindingSource Component](bindingsource-component.md). + + Because the control has an entirely new architecture, there is no straightforward conversion path that will enable you to use customizations with the control. Many customizations are unnecessary with the control, however, because of the built-in features available in the new control. If you have created custom column types for the control that you want to use with the control, you will have to implement them again using the new architecture. For more information, see [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- +- [DataGridView Control](datagridview-control-windows-forms.md) +- [DataGrid Control](datagrid-control-windows-forms.md) +- [BindingSource Component](bindingsource-component.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) +- [Data Formatting in the Windows Forms DataGridView Control](data-formatting-in-the-windows-forms-datagridview-control.md) +- [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md) +- [Column Sort Modes in the Windows Forms DataGridView Control](column-sort-modes-in-the-windows-forms-datagridview-control.md) +- [Selection Modes in the Windows Forms DataGridView Control](selection-modes-in-the-windows-forms-datagridview-control.md) +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/disable-buttons-in-a-button-column-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/disable-buttons-in-a-button-column-in-the-datagrid.md new file mode 100644 index 0000000000..b17270c3d1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/disable-buttons-in-a-button-column-in-the-datagrid.md @@ -0,0 +1,34 @@ +--- +title: Disable Buttons in a Button Column in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], disabling buttons" + - "buttons [Windows Forms], disabling in button columns" + - "DataGridView control [Windows Forms], disabling button cells" +ms.assetid: 5c344d01-013a-4a6b-8f8d-62ec9321d81e +--- +# How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control +The control includes the class for displaying cells with a user interface (UI) like a button. However, does not provide a way to disable the appearance of the button displayed by the cell. + + The following code example demonstrates how to customize the class to display buttons that can appear disabled. The example defines a new cell type, `DataGridViewDisableButtonCell`, that derives from . This cell type provides a new `Enabled` property that can be set to `false` to draw a disabled button in the cell. The example also defines a new column type, `DataGridViewDisableButtonColumn`, that displays `DataGridViewDisableButtonCell` objects. To demonstrate this new cell and column type, the current value of each in the parent determines whether the `Enabled` property of the `DataGridViewDisableButtonCell` in the same row is `true` or `false`. + +> [!NOTE] +> When you derive from or and add new properties to the derived class, be sure to override the `Clone` method to copy the new properties during cloning operations. You should also call the base class's `Clone` method so that the properties of the base class are copied to the new cell or column. + +## Example + [!code-csharp[System.Windows.Forms.DataGridView.DisabledButtons#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/CS/form1.cs#0)] + [!code-vb[System.Windows.Forms.DataGridView.DisabledButtons#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/VB/form1.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, System.Windows.Forms and System.Windows.Forms.VisualStyles assemblies. + +## See also + +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) +- [DataGridView Control Architecture](datagridview-control-architecture-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md b/dotnet-desktop-guide/framework/winforms/controls/display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md new file mode 100644 index 0000000000..913a1dc4b9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md @@ -0,0 +1,64 @@ +--- +title: Display a Date in a Custom Format with DateTimePicker Control +description: Learn how to use the Windows Forms DateTimePicker control to format the display of dates and times in the control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "DateTimePicker control [Windows Forms], display styles" + - "examples [Windows Forms], DateTimePicker control" + - "dates [Windows Forms], displaying in DateTimePicker control" +ms.assetid: 39767691-2d2b-46b6-a663-b7901e581a6e +--- +# How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control +The Windows Forms control gives you flexibility in formatting the display of dates and times in the control. The property allows you to select from predefined formats, listed in the . If none of these is adequate for your purposes, you can create your own format style using format characters listed in . + +### To display a custom format + +1. Set the property to `DateTimePickerFormat.Custom`. + +2. Set the property to a format string. + + ```vb + DateTimePicker1.Format = DateTimePickerFormat.Custom + ' Display the date as "Mon 27 Feb 2012". + DateTimePicker1.CustomFormat = "ddd dd MMM yyyy" + ``` + + ```csharp + dateTimePicker1.Format = DateTimePickerFormat.Custom; + // Display the date as "Mon 27 Feb 2012". + dateTimePicker1.CustomFormat = "ddd dd MMM yyyy"; + ``` + + ```cpp + dateTimePicker1->Format = DateTimePickerFormat::Custom; + // Display the date as "Mon 27 Feb 2012". + dateTimePicker1->CustomFormat = "ddd dd MMM yyyy"; + ``` + +### To add text to the formatted value + +1. Use single quotation marks to enclose any character that is not a format character like "M" or a delimiter like ":". For example, the format string below displays the current date with the format "Today is: 05:30:31 Friday March 02, 2012" in the English (United States) culture. + + ```vb + DateTimePicker1.CustomFormat = "'Today is:' hh:mm:ss dddd MMMM dd, yyyy" + ``` + + ```csharp + dateTimePicker1.CustomFormat = "'Today is:' hh:mm:ss dddd MMMM dd, yyyy"; + ``` + + ```cpp + dateTimePicker1->CustomFormat = + "'Today is:' hh:mm:ss dddd MMMM dd, yyyy"; + ``` + + Depending on the culture setting, any characters not enclosed in single quotation marks may be changed. For example, the format string above displays the current date with the format "Today is: 05:30:31 Friday March 02, 2012" in the English (United States) culture. Note that the first colon is enclosed in single quotation marks, because it is not intended to be a delimiting character as it is in "hh:mm:ss". In another culture, the format might appear as "Today is: 05.30.31 Friday March 02, 2012". + +## See also + +- [DateTimePicker Control](datetimepicker-control-windows-forms.md) +- [How to: Set and Return Dates with the Windows Forms DateTimePicker Control](how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/display-a-web-page-from-a-wf-linklabel-control-visual-basic.md b/dotnet-desktop-guide/framework/winforms/controls/display-a-web-page-from-a-wf-linklabel-control-visual-basic.md new file mode 100644 index 0000000000..ec7ff49608 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/display-a-web-page-from-a-wf-linklabel-control-visual-basic.md @@ -0,0 +1,49 @@ +--- +title: Display Web Page from LinkLabel Control (Visual Basic) +ms.date: "03/30/2017" +dev_langs: + - "vb" +f1_keywords: + - "LinkLabel1_LinkClicked" +helpviewer_keywords: + - "examples [Windows Forms], LinkLabel control" + - "Web pages [Windows Forms], displaying" + - "linking [Windows Forms], to Web pages from forms" + - "Windows Forms, linking to Web pages" + - "LinkLabel control [Windows Forms], examples" +ms.assetid: 477a7398-5971-4de3-b24c-f49f32bdb28a +--- +# How to: Display a Web Page from a Windows Forms LinkLabel Control (Visual Basic) +This example displays a Web page in the default browser when a user clicks a Windows Forms control. + +## Example + +```vb +Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _ +As System.EventArgs) Handles MyBase.Load + LinkLabel1.Text = "Click here to get more info." + LinkLabel1.Links.Add(6, 4, "www.microsoft.com") +End Sub +Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal _ +e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles _ +LinkLabel1.LinkClicked + System.Diagnostics.Process.Start(e.Link.LinkData.ToString()) +End Sub +``` + +## Compiling the Code + This example requires: + +- A Windows Form named `Form1`. + +- A control named `LinkLabel1`. + +- An active Internet connection. + +## .NET Framework Security + The call to the method requires full trust. For more information, see . + +## See also + +- +- [LinkLabel Control](linklabel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/display-error-icons-for-form-validation-with-wf-errorprovider.md b/dotnet-desktop-guide/framework/winforms/controls/display-error-icons-for-form-validation-with-wf-errorprovider.md new file mode 100644 index 0000000000..70dcadacfa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/display-error-icons-for-form-validation-with-wf-errorprovider.md @@ -0,0 +1,93 @@ +--- +title: Display Error Icons for Form Validation with ErrorProvider Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "errors [Windows Forms], displaying to users" + - "error icons" + - "ErrorProvider component [Windows Forms], displaying error icons" + - "error messages [Windows Forms], displaying icons" +ms.assetid: 3b681a32-9db4-497b-a34b-34980eabee46 +--- +# How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component +You can use a Windows Forms component to display an error icon when the user enters invalid data. You must have at least two controls on the form in order to tab between them and thereby invoke the validation code. + +### To display an error icon when a control's value is invalid + +1. Add two controls — for example, text boxes — to a Windows Form. + +2. Add an component to the form. + +3. Select the first control and add code to its event handler. In order for this code to run properly, the procedure must be connected to the event. For more information, see [How to: Create Event Handlers at Run Time for Windows Forms](../how-to-create-event-handlers-at-run-time-for-windows-forms.md). + + The following code tests the validity of the data the user has entered; if the data is invalid, the method is called. The first argument of the method specifies which control to display the icon next to. The second argument is the error text to display. + + ```vb + Private Sub TextBox1_Validating(ByVal Sender As Object, _ + ByVal e As System.ComponentModel.CancelEventArgs) Handles _ + TextBox1.Validating + If Not IsNumeric(TextBox1.Text) Then + ErrorProvider1.SetError(TextBox1, "Not a numeric value.") + Else + ' Clear the error. + ErrorProvider1.SetError(TextBox1, "") + End If + End Sub + ``` + + ```csharp + protected void textBox1_Validating (object sender, + System.ComponentModel.CancelEventArgs e) + { + try + { + int x = Int32.Parse(textBox1.Text); + errorProvider1.SetError(textBox1, ""); + } + catch (Exception ex) + { + errorProvider1.SetError(textBox1, "Not an integer value."); + } + } + ``` + + ```cpp + private: + System::Void textBox1_Validating(System::Object ^ sender, + System::ComponentModel::CancelEventArgs ^ e) + { + try + { + int x = Int32::Parse(textBox1->Text); + errorProvider1->SetError(textBox1, ""); + } + catch (System::Exception ^ ex) + { + errorProvider1->SetError(textBox1, "Not an integer value."); + } + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.textBox1.Validating += new + System.ComponentModel.CancelEventHandler(this.textBox1_Validating); + ``` + + ```cpp + this->textBox1->Validating += gcnew + System::ComponentModel::CancelEventHandler + (this, &Form1::textBox1_Validating); + ``` + +4. Run the project. Type invalid (in this example, non-numeric) data into the first control, and then tab to the second. When the error icon is displayed, point at it with the mouse pointer to see the error text. + +## See also + +- +- [ErrorProvider Component Overview](errorprovider-component-overview-windows-forms.md) +- [How to: View Errors Within a DataSet with the Windows Forms ErrorProvider Component](view-errors-within-a-dataset-with-wf-errorprovider-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/display-more-than-one-month-wf-monthcalendar-control.md b/dotnet-desktop-guide/framework/winforms/controls/display-more-than-one-month-wf-monthcalendar-control.md new file mode 100644 index 0000000000..d3d75acf5c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/display-more-than-one-month-wf-monthcalendar-control.md @@ -0,0 +1,38 @@ +--- +title: Display More than One Month in MonthCalendar Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "calendars [Windows Forms], formatting display" + - "examples [Windows Forms], calendar controls" + - "calendars [Windows Forms], multiple months" + - "MonthCalendar control [Windows Forms], formatting display" +ms.assetid: d197caa2-38a5-4cb4-acc3-562130c2ace3 +--- +# How to: Display More than One Month in the Windows Forms MonthCalendar Control +The Windows Forms control can display up to 12 months at a time. By default, the control displays only one month, but you can specify how many months are displayed and how they are arranged within the control. When you change the calendar dimensions, the control is resized, so be sure there is enough room on the form for the new dimensions. + +### To display multiple months + +- Set the property to the number of months to display horizontally and vertically. + + ```vb + MonthCalendar1.CalendarDimensions = New System.Drawing.Size (3,2) + ``` + + ```csharp + monthCalendar1.CalendarDimensions = new System.Drawing.Size (3,2); + ``` + + ```cpp + monthCalendar1->CalendarDimensions = System::Drawing::Size (3,2); + ``` + +## See also + +- [MonthCalendar Control](monthcalendar-control-windows-forms.md) +- [How to: Select a Range of Dates in the Windows Forms MonthCalendar Control](how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md) +- [How to: Change the Windows Forms MonthCalendar Control's Appearance](how-to-change-monthcalendar-control-appearance.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/display-specific-days-in-bold-with-wf-monthcalendar-control.md b/dotnet-desktop-guide/framework/winforms/controls/display-specific-days-in-bold-with-wf-monthcalendar-control.md new file mode 100644 index 0000000000..9bdd9cee56 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/display-specific-days-in-bold-with-wf-monthcalendar-control.md @@ -0,0 +1,129 @@ +--- +title: Display Specific Days in Bold with MonthCalendar Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "calendars [Windows Forms], displaying dates in bold" + - "examples [Windows Forms], calendar controls" + - "GetDayBold event" + - "MonthCalendar control [Windows Forms], dates displayed in bold" +ms.assetid: 8b20db5b-8118-4825-90e8-2c45c186ac7d +--- +# How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control +The Windows Forms control can display days in bold type, either as singular dates or on a repeating basis. You might do this to draw attention to special dates, such as holidays and weekends. + + Three properties control this feature. The property contains single dates. The property contains dates that appear in bold every year. The property contains dates that appear in bold every month. Each of these properties contains an array of objects. To add or remove a date from one of these lists, you must add or remove a object. + +### To make a date appear in bold type + +1. Create the objects. + + ```vb + Dim myVacation1 As Date = New DateTime(2001, 6, 10) + Dim myVacation2 As Date = New DateTime(2001, 6, 17) + ``` + + ```csharp + DateTime myVacation1 = new DateTime(2001, 6, 10); + DateTime myVacation2 = new DateTime(2001, 6, 17); + ``` + + ```cpp + DateTime myVacation1 = DateTime(2001, 6, 10); + DateTime myVacation2 = DateTime(2001, 6, 17); + ``` + +2. Make a single date bold by calling the , , or method of the control. + + ```vb + MonthCalendar1.AddBoldedDate(myVacation1) + MonthCalendar1.AddBoldedDate(myVacation2) + ``` + + ```csharp + monthCalendar1.AddBoldedDate(myVacation1); + monthCalendar1.AddBoldedDate(myVacation2); + ``` + + ```cpp + monthCalendar1->AddBoldedDate(myVacation1); + monthCalendar1->AddBoldedDate(myVacation2); + ``` + + –or– + + Make a set of dates bold all at once by creating an array of objects and assigning it to one of the properties. + + ```vb + Dim VacationDates As DateTime() = {myVacation1, myVacation2} + MonthCalendar1.BoldedDates = VacationDates + ``` + + ```csharp + DateTime[] VacationDates = {myVacation1, myVacation2}; + monthCalendar1.BoldedDates = VacationDates; + ``` + + ```cpp + Array^ VacationDates = {myVacation1, myVacation2}; + monthCalendar1->BoldedDates = VacationDates; + ``` + +### To make a date appear in the regular font + +1. Make a single bolded date appear in the regular font by calling the , , or method. + + ```vb + MonthCalendar1.RemoveBoldedDate(myVacation1) + MonthCalendar1.RemoveBoldedDate(myVacation2) + ``` + + ```csharp + monthCalendar1.RemoveBoldedDate(myVacation1); + monthCalendar1.RemoveBoldedDate(myVacation2); + ``` + + ```cpp + monthCalendar1->RemoveBoldedDate(myVacation1); + monthCalendar1->RemoveBoldedDate(myVacation2); + ``` + + –or– + + Remove all the bolded dates from one of the three lists by calling the , , or method. + + ```vb + MonthCalendar1.RemoveAllBoldedDates() + ``` + + ```csharp + monthCalendar1.RemoveAllBoldedDates(); + ``` + + ```cpp + monthCalendar1->RemoveAllBoldedDates(); + ``` + +2. Update the appearance of the font by calling the method. + + ```vb + MonthCalendar1.UpdateBoldedDates() + ``` + + ```csharp + monthCalendar1.UpdateBoldedDates(); + ``` + + ```cpp + monthCalendar1->UpdateBoldedDates(); + ``` + +## See also + +- [MonthCalendar Control](monthcalendar-control-windows-forms.md) +- [How to: Select a Range of Dates in the Windows Forms MonthCalendar Control](how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md) +- [How to: Change the Windows Forms MonthCalendar Control's Appearance](how-to-change-monthcalendar-control-appearance.md) +- [How to: Display More than One Month in the Windows Forms MonthCalendar Control](display-more-than-one-month-wf-monthcalendar-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/displaying-data-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/displaying-data-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..1676cce8ba --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/displaying-data-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,73 @@ +--- +title: Displaying Data in DataGridView Control +description: Learn how to use the Windows Forms DataGridView control to display data from a variety of external data sources. +ms.date: "03/30/2017" +helpviewer_keywords: + - "data [Windows Forms], displaying in tabular format" + - "data grids [Windows Forms], displaying data" + - "displaying data [Windows Forms], data grids" + - "DataGridView control [Windows Forms], displaying data" +ms.assetid: b170b52a-2ebd-4948-ac2f-e52d494cebb2 +--- +# Displaying Data in the Windows Forms DataGridView Control +The `DataGridView` control is used to display data from a variety of external data sources. Alternatively, you can add rows and columns to the control and manually populate it with data. + + When you bind the control to a data source, you can generate columns automatically based on the schema of the data source. If these columns do not appear just as you want them to, you can hide, remove, or rearrange them. You can also add unbound columns to display supplemental data that does not come from the data source. + + Additionally, you can display your data using standard formats (such as currency format), or you can customize the display formatting to present your data however you need to (such as changing the background color for negative numbers, or replacing string values with corresponding images). + +## In This Section + [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) + Describes the options for populating the control with data. + + [Data Formatting in the Windows Forms DataGridView Control](data-formatting-in-the-windows-forms-datagridview-control.md) + Describes the options for formatting cell display values. + + [Walkthrough: Creating an Unbound Windows Forms DataGridView Control](walkthrough-creating-an-unbound-windows-forms-datagridview-control.md) + Describes how to manually populate the control with data. + + [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md) + Describes how to populate the control with data by binding it to a `BindingSource` that contains information pulled from a database. + + [How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control](autogenerate-columns-in-a-data-bound-wf-datagridview-control.md) + Describes how to automatically generate columns based on a bound data source. + + [How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control](remove-autogenerated-columns-from-a-wf-datagridview-control.md) + Describes how to hide or delete columns generated automatically from a bound data source. + + [How to: Change the Order of Columns in the Windows Forms DataGridView Control](how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md) + Describes how to rearrange columns generated automatically from a bound data source. + + [How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control](unbound-column-to-a-data-bound-datagridview.md) + Describes how to supplement data from a bound data source by displaying additional, unbound columns. + + [How to: Bind Objects to Windows Forms DataGridView Controls](how-to-bind-objects-to-windows-forms-datagridview-controls.md) + Describes how to bind the control to a collection of arbitrary objects so that each object is displayed in its own row. + + [How to: Access Objects Bound to Windows Forms DataGridView Rows](how-to-access-objects-bound-to-windows-forms-datagridview-rows.md) + Describes how to retrieve an object bound to a particular row of the control. + + [Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls](creating-a-master-detail-form-using-two-datagridviews.md) + Describes how to display data from two related database tables so that the values shown in one `DataGridView` control depend on the currently selected row in another control. + + [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md) + Describes how to handle the event to change the appearance of cells depending on their values. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the property. + + + Provides reference documentation for the component. + +## Related Sections + [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) + Provides topics that describe how to change the way users add and modify data in the control. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/domainupdown-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/domainupdown-control-overview-windows-forms.md new file mode 100644 index 0000000000..2e3572c73f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/domainupdown-control-overview-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "DomainUpDown Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "DomainUpDown" +helpviewer_keywords: + - "spin button control [Windows Forms], about spin button" + - "DomainUpDown control [Windows Forms], about DomainUpDown control" +ms.assetid: 3f40f9c1-20ad-4331-b9b5-b0127eb36eb3 +--- +# DomainUpDown Control Overview (Windows Forms) +The Windows Forms control is essentially a combination of a text box and a pair of buttons for moving up or down through a list. The control displays and sets a text string from a list of choices. The user can select the string by clicking up and down buttons to move through a list, by pressing the UP and DOWN ARROW keys, or by typing a string that matches an item in the list. One possible use for this control is for selecting items from an alphabetically sorted list of names. + +> [!NOTE] +> To sort the list, set the property to `true`. + + The function of this control is very similar to the list box or combo box, but it takes up very little space. + +## Key Properties + The key properties of the control are , , and . The property contains the list of objects whose text values are displayed in the control. If is set to `false`, the control automatically completes text that the user types and matches it to a value in the list. If is set to `true`, scrolling past the last item will take you to the first item in the list and vice versa. The key methods of the control are and . + + This control displays only text strings. If you want a control that displays numeric values, use the control. For more information, see [NumericUpDown Control Overview](numericupdown-control-overview-windows-forms.md). + +## See also + +- +- [DomainUpDown Control](domainupdown-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/domainupdown-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/domainupdown-control-windows-forms.md new file mode 100644 index 0000000000..3fba1d59b1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/domainupdown-control-windows-forms.md @@ -0,0 +1,38 @@ +--- +title: "DomainUpDown Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "DomainUpDown control [Windows Forms]" + - "spin button control [Windows Forms], up-down controls" + - "up-down controls" + - "spin button control" + - "up-down controls [Windows Forms], spin button controls" +ms.assetid: fb7cf017-e931-4a95-9d21-8caee4ee122a +--- +# DomainUpDown Control (Windows Forms) +The Windows Forms control looks like a combination of a text box and a pair of buttons for moving up or down through a list. The control displays and sets a text string from a list of choices. The user can select the string by clicking up and down buttons to move through a list, by pressing the UP and DOWN ARROW keys, or by typing a string that matches an item in the list. One possible use for this control is for selecting items from an alphabetically sorted list of names. (To sort the list, set the property to `true`.) The function of this control is very similar to the list box or combo box, but it takes up very little space. + + The key properties of the control are , , and . The property contains the list of objects whose text values are displayed in the control. If is set to `false`, the control automatically completes text that the user types and matches it to a value in the list. If is set to `true`, scrolling past the last item will take you to the first item in the list and vice versa. The key methods of the control are and . + + This control displays only text strings. If you want a control that displays numeric values, use the control. For more information, see [NumericUpDown Control](numericupdown-control-windows-forms.md) . + +## In This Section + [DomainUpDown Control Overview](domainupdown-control-overview-windows-forms.md) + Introduces the general concepts of the control, which allows users to browse through and select from a list of text strings. + + [How to: Add Items to Windows Forms DomainUpDown Controls Programmatically](how-to-add-items-to-windows-forms-domainupdown-controls-programmatically.md) + Describes how to specify the text strings the control should display. + + [How to: Remove Items from Windows Forms DomainUpDown Controls](how-to-remove-items-from-windows-forms-domainupdown-controls.md) + Describes how to delete items from the control in code. + +## Reference + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members.. + +## Related Sections + [Controls You Can Use On Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/enable-column-reordering-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/enable-column-reordering-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..cbbefdea06 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/enable-column-reordering-in-the-datagrid-using-the-designer.md @@ -0,0 +1,26 @@ +--- +title: Enable Column Reordering in DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], column order" + - "Windows Forms, columns" + - "columns [Windows Forms], reordering" + - "data [Windows Forms], displaying" +ms.assetid: d82bd69c-6799-4439-a32c-91139c5901d1 +--- +# How to: Enable Column Reordering in the Windows Forms DataGridView Control Using the Designer +When viewing data displayed in a Windows Forms control, users sometimes want to compare the values in specific columns. This can be inconvenient if the columns are widely separated in the control, especially if users must scroll back and forth horizontally in order to see all the columns they are interested in. You can make the task of comparing column values easier by enabling your users to reorder the columns. When you enable column reordering, users can move a column to a new position by dragging the column header with the mouse. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To enable column reordering + +- Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Enable Column Reordering**. + +## See also + +- +- +- [How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer](freeze-columns-in-the-datagrid-using-the-designer.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/enable-drag-and-drop-operations-with-wf-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/enable-drag-and-drop-operations-with-wf-richtextbox-control.md new file mode 100644 index 0000000000..33c88866a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/enable-drag-and-drop-operations-with-wf-richtextbox-control.md @@ -0,0 +1,166 @@ +--- +title: Enable Drag-and-Drop Operations with RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], text boxes" + - "drag and drop [Windows Forms], richTextBox control" + - "text boxes [Windows Forms], drag-and-drop operations" + - "RichTextBox control [Windows Forms], drag-and-drop operations" +ms.assetid: ca167d1c-2014-4cf0-96a0-20598470be3b +--- +# How to: Enable Drag-and-Drop Operations with the Windows Forms RichTextBox Control +Drag-and-drop operations with the Windows Forms control are done by handling the and events. Thus, drag-and-drop operations are extremely simple with the control. + +### To enable drag operations in a RichTextBox control + +1. Set the property of the control to `true`. + +2. Write code in the event handler of the event. Use an `if` statement to ensure that the data being dragged is of an acceptable type (in this case, text). The property can be set to any value of the enumeration. + + ```vb + Private Sub RichTextBox1_DragEnter(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DragEventArgs) _ + Handles RichTextBox1.DragEnter + If (e.Data.GetDataPresent(DataFormats.Text)) Then + e.Effect = DragDropEffects.Copy + Else + e.Effect = DragDropEffects.None + End If + End Sub + ``` + + ```csharp + private void richTextBox1_DragEnter(object sender, + System.Windows.Forms.DragEventArgs e) + { + if (e.Data.GetDataPresent(DataFormats.Text)) + e.Effect = DragDropEffects.Copy; + else + e.Effect = DragDropEffects.None; + } + ``` + + ```cpp + private: + void richTextBox1_DragEnter(System::Object ^ sender, + System::Windows::Forms::DragEventArgs ^ e) + { + if (e->Data->GetDataPresent(DataFormats::Text)) + e->Effect = DragDropEffects::Copy; + else + e->Effect = DragDropEffects::None; + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.richTextBox1.DragEnter += new + System.Windows.Forms.DragEventHandler + (this.richTextBox1_DragEnter); + ``` + + ```cpp + this->richTextBox1->DragEnter += gcnew + System::Windows::Forms::DragEventHandler + (this, &Form1::richTextBox1_DragEnter); + ``` + +3. Write code to handle the event. Use the method to retrieve the data being dragged. + + In the example below, the code sets the property of the control equal to the data being dragged. If there is already text in the control, the dragged text is inserted at the insertion point. + + ```vb + Private Sub RichTextBox1_DragDrop(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DragEventArgs) _ + Handles RichTextBox1.DragDrop + Dim i As Int16 + Dim s As String + + ' Get start position to drop the text. + i = RichTextBox1.SelectionStart + s = RichTextBox1.Text.Substring(i) + RichTextBox1.Text = RichTextBox1.Text.Substring(0, i) + + ' Drop the text on to the RichTextBox. + RichTextBox1.Text = RichTextBox1.Text + _ + e.Data.GetData(DataFormats.Text).ToString() + RichTextBox1.Text = RichTextBox1.Text + s + End Sub + ``` + + ```csharp + private void richTextBox1_DragDrop(object sender, + System.Windows.Forms.DragEventArgs e) + { + int i; + String s; + + // Get start position to drop the text. + i = richTextBox1.SelectionStart; + s = richTextBox1.Text.Substring(i); + richTextBox1.Text = richTextBox1.Text.Substring(0,i); + + // Drop the text on to the RichTextBox. + richTextBox1.Text = richTextBox1.Text + + e.Data.GetData(DataFormats.Text).ToString(); + richTextBox1.Text = richTextBox1.Text + s; + } + ``` + + ```cpp + private: + System::Void richTextBox1_DragDrop(System::Object ^ sender, + System::Windows::Forms::DragEventArgs ^ e) + { + int i; + String ^s; + + // Get start position to drop the text. + i = richTextBox1->SelectionStart; + s = richTextBox1->Text->Substring(i); + richTextBox1->Text = richTextBox1->Text->Substring(0,i); + + // Drop the text on to the RichTextBox. + String ^str = String::Concat(richTextBox1->Text, e->Data + ->GetData(DataFormats->Text)->ToString()); + richTextBox1->Text = String::Concat(str, s); + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.richTextBox1.DragDrop += new + System.Windows.Forms.DragEventHandler + (this.richTextBox1_DragDrop); + ``` + + ```cpp + this->richTextBox1->DragDrop += gcnew + System::Windows::Forms::DragEventHandler + (this, &Form1::richTextBox1_DragDrop); + ``` + +### To test the drag-and-drop functionality in your application + +1. Save and build your application. While it is running, run WordPad. + + WordPad is a text editor installed by Windows that allows drag-and-drop operations. It is accessible by clicking the **Start** button, selecting **Run**, typing `WordPad` in the text box of the **Run** dialog box, and then clicking **OK**. + +2. Once WordPad is open, type a string of text in it. Using the mouse, select the text, and then drag the selected text over to the control in your Windows application. + + Notice that when you point the mouse at the control (and, consequently, raise the event), the mouse pointer changes and you can drop the selected text into the control. + + When you release the mouse button, the selected text is dropped (that is, the event is raised) and is inserted within the control. + +## See also + +- +- [How to: Perform Drag-and-Drop Operations Between Applications](../advanced/how-to-perform-drag-and-drop-operations-between-applications.md) +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/enable-tile-view-in-a-wf-listview-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/enable-tile-view-in-a-wf-listview-control-using-the-designer.md new file mode 100644 index 0000000000..b7721ae5a3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/enable-tile-view-in-a-wf-listview-control-using-the-designer.md @@ -0,0 +1,30 @@ +--- +title: Enable Tile View in ListView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "tile view feature" + - "ListView control [Windows Forms], tile view" + - "tiling [Windows Forms], Windows Forms, controls" +ms.assetid: 12f0816a-52b8-41ee-a6d9-ded3a8a5817a +--- +# How to: Enable Tile View in a Windows Forms ListView Control Using the Designer +The tile view feature of the control enables you to provide a visual balance between graphical and textual information. The textual information displayed for an item in tile view is the same as the column information defined for details view. Tile view functions in combination with either the grouping or insertion mark features in the control. + + The tile view uses a 32 x 32 icon and several lines of text, as shown in the following image. + + ![Tile View in a ListView Control](./media/enable-tile-view-in-a-wf-listview-control-using-the-designer/tile-view-in-listview-control.gif "Tile view icons and text") + + Tile view properties and methods enable you to specify which column fields to display for each item, and to collectively control the size and appearance of all items within a tile view window. For clarity, the first line of text in a tile is always the item's name; it cannot be changed. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To set tile view in the designer + +1. In Visual Studio, select the control on your form. + +2. In the **Properties** window, select the property and choose **Tile**. + +## See also + +- +- [ListView Control Overview](listview-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/enable-users-to-copy-multiple-cells-to-the-clipboard-datagridview.md b/dotnet-desktop-guide/framework/winforms/controls/enable-users-to-copy-multiple-cells-to-the-clipboard-datagridview.md new file mode 100644 index 0000000000..69c804110b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/enable-users-to-copy-multiple-cells-to-the-clipboard-datagridview.md @@ -0,0 +1,44 @@ +--- +title: Enable Users to Copy Multiple Cells to the Clipboard from DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "cells [Windows Forms], copying to Clipboard" + - "DataGridView control [Windows Forms], copying multiple cells" + - "data grids [Windows Forms], copying multiple cells" + - "Clipboard [Windows Forms], copying multiple cells" +ms.assetid: fd0403b2-d0e3-4ae0-839c-0f737e1eb4a9 +--- +# How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control +When you enable cell copying, you make the data in your control easily accessible to other applications through the . The values of the selected cells are converted to strings and added to the Clipboard as tab-delimited text values for pasting into applications like Notepad and Excel, and as an HTML-formatted table for pasting into applications like Word. + + You can configure cell copying to copy cell values only, to include row and column header text in the Clipboard data, or to include header text only when users select entire rows or columns. + + Depending on the selection mode, users can select multiple disconnected groups of cells. When a user copies cells to the Clipboard, rows and columns with no selected cells are not copied. All other rows or columns become rows and columns in the table of data copied to the Clipboard. Unselected cells in these rows or columns are copied as blank placeholders to the Clipboard. + +### To enable cell copying + +- Set the property. + + [!code-csharp[System.Windows.Forms.DataGridViewClipboardDemo#15](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/CS/datagridviewclipboarddemo.cs#15)] + [!code-vb[System.Windows.Forms.DataGridViewClipboardDemo#15](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/VB/datagridviewclipboarddemo.vb#15)] + +## Example + The following complete code example demonstrates how cells are copied to the Clipboard. This example includes a button that copies the selected cells to the Clipboard using the method and displays the Clipboard contents in a text box. + + [!code-csharp[System.Windows.Forms.DataGridViewClipboardDemo#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/CS/datagridviewclipboarddemo.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewClipboardDemo#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/VB/datagridviewclipboarddemo.vb#00)] + +## Compiling the Code + This code requires: + +- References to the N:System and N:System.Windows.Forms assemblies. + +## See also + +- +- +- +- [Selection and Clipboard Use with the Windows Forms DataGridView Control](selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/errorprovider-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/errorprovider-component-overview-windows-forms.md new file mode 100644 index 0000000000..b74d7ab0c4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/errorprovider-component-overview-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "ErrorProvider Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ErrorProvider" +helpviewer_keywords: + - "errors [Windows Forms], displaying to users" + - "error messages [Windows Forms], displaying" + - "ErrorProvider component [Windows Forms], about ErrorProvider component" +ms.assetid: ced189f2-b5c8-46a7-a6f1-37f5af95dc99 +--- +# ErrorProvider Component Overview (Windows Forms) +The Windows Forms [ErrorProvider](errorprovider-component-windows-forms.md) component is used to validate user input on a form or control. It is typically used in conjunction with validating user input on a form, or displaying errors within a dataset. An error provider is a better alternative than displaying an error message in a message box, because once a message box is dismissed, the error message is no longer visible. The component displays an error icon (![A white exclamation point inside a red circle.](./media/errorprovider-component-overview-windows-forms/vb-error-provider-icon.gif)) next to the relevant control, such as a text box; when the user positions the mouse pointer over the error icon, a ToolTip appears, showing the error message string. + +## Key Properties + The component's key properties are , , and . When using component with data-bound controls, the property must be set to the appropriate container (usually the Windows Form) in order for the component to display an error icon on the form. When the component is added in the designer, the property is set to the containing form; if you add the control in code, you must set it yourself. + + The property can be set to a custom error icon instead of the default. When the property is set, the component can display error messages for a dataset. The key method of the component is the method, which specifies the error message string and where the error icon should appear. + +> [!NOTE] +> The component does not provide built-in support for accessibility clients. To make your application accessible when using this component, you must provide an additional, accessible feedback mechanism. + +## See also + +- +- [How to: View Errors Within a DataSet with the Windows Forms ErrorProvider Component](view-errors-within-a-dataset-with-wf-errorprovider-component.md) +- [How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component](display-error-icons-for-form-validation-with-wf-errorprovider.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/errorprovider-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/errorprovider-component-windows-forms.md new file mode 100644 index 0000000000..a8f68c8450 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/errorprovider-component-windows-forms.md @@ -0,0 +1,29 @@ +--- +title: "ErrorProvider Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "error messages [Windows Forms], displaying" + - "errors [Windows Forms]" + - "ErrorProvider component [Windows Forms]" +ms.assetid: c0f2e231-c5c9-413d-a507-75af2db499b6 +--- +# ErrorProvider Component (Windows Forms) +The Windows Forms `ErrorProvider` component is used to show the user in a non-intrusive way that something is wrong. It is typically used in conjunction with validating user input on a form, or displaying errors within a dataset. + +## In This Section + [ErrorProvider Component Overview](errorprovider-component-overview-windows-forms.md) + Explains what this component is and its key features and properties. + + [How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component](display-error-icons-for-form-validation-with-wf-errorprovider.md) + Gives directions for validating user input with an error provider component. + + [How to: View Errors Within a DataSet with the Windows Forms ErrorProvider Component](view-errors-within-a-dataset-with-wf-errorprovider-component.md) + Gives directions for using an error provider component to display data errors. + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/events-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/events-in-windows-forms-controls.md new file mode 100644 index 0000000000..6e3a650a95 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/events-in-windows-forms-controls.md @@ -0,0 +1,19 @@ +--- +title: Events in Controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "events [Windows Forms], custom controls (using code)" + - "custom controls [Windows Forms], events overview (using code)" +ms.assetid: 7e3d1379-87aa-437c-afce-c99454eff30e +--- +# Events in Windows Forms Controls +A Windows Forms control inherits more than sixty events from . These include the event, which causes a control to be drawn, events related to displaying a window, such as the and events, and low-level mouse and keyboard events. Some low-level events are synthesized by into semantic events such as and . For details about inherited events, see . + + If your custom control needs to override inherited event functionality, override the inherited `On`*EventName* method instead of attaching a delegate. If you are not familiar with the event model in the .NET Framework, see [Raising Events from a Component](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/sh2e3k5z(v=vs.120)). + +## See also + +- [Overriding the OnPaint Method](overriding-the-onpaint-method.md) +- [Handling User Input](handling-user-input.md) +- [Defining an Event](defining-an-event-in-windows-forms-controls.md) +- [Events](https://docs.microsoft.com/dotnet/standard/events/index) diff --git a/dotnet-desktop-guide/framework/winforms/controls/filedialog-class.md b/dotnet-desktop-guide/framework/winforms/controls/filedialog-class.md new file mode 100644 index 0000000000..63ae1aa5e5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/filedialog-class.md @@ -0,0 +1,29 @@ +--- +title: "FileDialog Class" +ms.date: "03/30/2017" +helpviewer_keywords: + - "FileDialog class [Windows Forms]" +ms.assetid: 85a8fb62-c7d9-4a30-9b74-1cd10efe6ccb +--- +# FileDialog Class +The Windows Forms class is the common base class for the and components. You can make changes to the class that affect the appearance and behavior of these dialog boxes, depending on the version of Windows the application is running on. + +## In This Section + [How To: Opt Out of File Dialog Box Automatic Upgrade](how-to-opt-out-of-file-dialog-box-automatic-upgrade.md) + Describes how to opt out of a style automatic upgrade to a file dialog box. + + [How To: Add a Custom Place to a File Dialog Box](how-to-add-a-custom-place-to-a-file-dialog-box.md) + Describes how to add a custom file location to a file dialog box. + + [Known Folder GUIDs for File Dialog Custom Places](known-folder-guids-for-file-dialog-custom-places.md) + List the folder names and their associated GUIDs. + +## Reference + + + + +## Related Sections + [OpenFileDialog Component](openfiledialog-component-windows-forms.md) + + [SaveFileDialog Component](savefiledialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/flowlayoutpanel-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/flowlayoutpanel-control-overview.md new file mode 100644 index 0000000000..2692c98896 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/flowlayoutpanel-control-overview.md @@ -0,0 +1,28 @@ +--- +title: "FlowLayoutPanel Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "FlowLayoutPanel" +helpviewer_keywords: + - "forms [Windows Forms], dynamic layout" + - "layout [Windows Forms], dynamic" + - "Windows Forms, dynamic layout" + - "FlowLayoutPanel control [Windows Forms], about FlowLayoutPanel control" +ms.assetid: 3883e024-f5a0-456d-9c27-b4dfa1cc9045 +--- +# FlowLayoutPanel Control Overview +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. + + Any Windows Forms control can be a child of the control, including other instances of . With this capability, you can construct sophisticated layouts that adapt to your form's dimensions at run time. + + Also see [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md). + +## See also + +- +- +- [FlowLayoutPanel Control](flowlayoutpanel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/flowlayoutpanel-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/flowlayoutpanel-control-windows-forms.md new file mode 100644 index 0000000000..36bad4102e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/flowlayoutpanel-control-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "FlowLayoutPanel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "FlowLayoutPanel control [Windows Forms]" + - "layout [Windows Forms]" + - "Windows Forms, arranging contents" +ms.assetid: 630c9305-9ecf-4f99-94f9-ddf06de82713 +--- +# FlowLayoutPanel Control (Windows Forms) +The `FlowLayoutPanel` control arranges its contents in a horizontal or vertical flow direction. Its contents can be wrapped from one row to the next, or from one column to the next. Alternately, its contents can be clipped instead of wrapped. + + The topics in this section describe the concepts and techniques that allow you to build `FlowLayoutPanel` features into your applications. + +## In This Section + [FlowLayoutPanel Control Overview](flowlayoutpanel-control-overview.md) + Introduces the general concepts of the `FlowLayoutPanel` control, which allows you to create a layout which flows horizontally or vertically. + + [How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md) + Explains how to use the and properties to anchor and dock child controls in a control. + + Also see [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md). + +## Reference + + Provides reference documentation for the control. diff --git a/dotnet-desktop-guide/framework/winforms/controls/folderbrowserdialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/folderbrowserdialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..b71ee194dd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/folderbrowserdialog-component-overview-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "FolderBrowserDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "FolderBrowserDialog" +helpviewer_keywords: + - "FolderBrowserDialog component [Windows Forms], about FolderBrowserDialog" + - "directories [Windows Forms], enabling browsing in applications" + - "folders [Windows Forms], enabling browsing in applications" +ms.assetid: 796b622c-3ba9-4356-93bb-e217fc52f2c7 +--- +# FolderBrowserDialog Component Overview (Windows Forms) + +The Windows Forms component is a modal dialog box that is used for browsing and selecting folders. New folders can also be created from within the component. + +> [!NOTE] +> To select files, instead of folders, use the [OpenFileDialog](openfiledialog-component-windows-forms.md) component. + +The component is displayed at run time using the method. Set the property to determine the top-most folder and any subfolders that will appear within the tree view of the dialog box. Once the dialog box has been shown, you can use the property to get the path of the folder that was selected. + +When it is added to a form, the component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio. + +## See also + +- +- [How to: Choose Folders with the Windows Forms FolderBrowserDialog Component](how-to-choose-folders-with-the-windows-forms-folderbrowserdialog-component.md) +- [FolderBrowserDialog Component](folderbrowserdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/folderbrowserdialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/folderbrowserdialog-component-windows-forms.md new file mode 100644 index 0000000000..db18772fe4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/folderbrowserdialog-component-windows-forms.md @@ -0,0 +1,30 @@ +--- +title: "FolderBrowserDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "folders [Windows Forms], browsing" + - "FolderBrowserDialog component [Windows Forms]" + - "browsing folders" + - "directories [Windows Forms], browsing" +ms.assetid: d71a0c5e-898a-4eea-be74-93bdf50d1852 +--- +# FolderBrowserDialog Component (Windows Forms) +The Windows Forms `FolderBrowserDialog` component displays an interface with which users can browse and select a folder or create a new one. It is a complement to the [OpenFileDialog Component](openfiledialog-component-windows-forms.md) component, which is used for browsing and selecting files. + +## In This Section + [FolderBrowserDialog Component Overview (Windows Forms)](folderbrowserdialog-component-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Choose Folders with the Windows Forms FolderBrowserDialog Component](how-to-choose-folders-with-the-windows-forms-folderbrowserdialog-component.md) + Explains how to programmatically extract the selected folder from the dialog box, as well as work with some of the other, optional properties of the component. + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Dialog Boxes in Windows Forms](../dialog-boxes-in-windows-forms.md) + Provides a list of tasks for dialog boxes, which often display tabs. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/fontdialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/fontdialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..76ad7cd1fa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/fontdialog-component-overview-windows-forms.md @@ -0,0 +1,23 @@ +--- +title: "FontDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "FontDialog" +helpviewer_keywords: + - "Font dialog box [Windows Forms], Windows Forms" + - "Font dialog box" + - "FontDialog component [Windows Forms], about FontDialog component" +ms.assetid: daf46e57-1b4b-4b7a-bad0-b50ca7ba75dc +--- +# FontDialog Component Overview (Windows Forms) +The Windows Forms component is a pre-configured dialog box, which is the standard Windows **Font** dialog box used to expose the fonts that are currently installed on the system. Use it within your Windows-based application as a simple solution for font selection in lieu of configuring your own dialog box. + + By default, the dialog box shows list boxes for Font, Font style, and Size; check boxes for effects like Strikeout and Underline; a drop-down list for Script; and a sample of how the font will appear. (Script refers to different character scripts that are available for a given font, for example, Hebrew or Japanese.) To display the font dialog box, call the method. + +## Key Properties + The component has a number of properties that configure its appearance. The properties that set the dialog-box selections are and . The property sets the font, style, size, script, and effects; for example, `Arial, 10pt, style=Italic, Strikeout`. + +## See also + +- +- [FontDialog Component](fontdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/fontdialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/fontdialog-component-windows-forms.md new file mode 100644 index 0000000000..36c88d4c65 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/fontdialog-component-windows-forms.md @@ -0,0 +1,29 @@ +--- +title: "FontDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "fonts [Windows Forms], dialog box" + - "FontDialog component [Windows Forms]" + - "Font dialog box [Windows Forms], Windows Forms" +ms.assetid: 54015df3-aab2-4338-84e5-ba78cedbfdfc +--- +# FontDialog Component (Windows Forms) +The Windows Forms component is a pre-configured dialog box. It is the same **Font** dialog box exposed by the Windows operating system. The component inherits from the class. + +## In This Section + [FontDialog Component Overview](fontdialog-component-overview-windows-forms.md) + Introduces the general concepts of the component, which you use to display a pre-configured dialog box. Users can use the dialog box to manipulate fonts and their settings. + + [How to: Show a Font List with the FontDialog Component](how-to-show-a-font-list-with-the-fontdialog-component.md) + Explains how to choose a font at run time through an instance of the component. + +## Reference + + Provides reference information about the class and its members. + +## Related Sections + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Describes a set of controls and components that enable users to perform standard interactions with the application or system. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information about their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/freeze-columns-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/freeze-columns-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..03daaf3826 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/freeze-columns-in-the-datagrid-using-the-designer.md @@ -0,0 +1,37 @@ +--- +title: Freeze Columns in DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, columns" + - "columns [Windows Forms], freezing" + - "DataGridView control [Windows Forms], column freezing" + - "data [Windows Forms], displaying" +ms.assetid: 87412dd2-478f-4751-af87-dafc591fc215 +--- +# How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer +When users view data displayed in a Windows Forms control, they sometimes need to refer to a single column or set of columns frequently. For example, when you display a table of customer information that contains many columns, it is useful for you to display the customer name at all times while enabling other columns to scroll outside the visible region. + + To achieve this behavior, you can freeze columns in the control. When you freeze a column, all the columns to its left (or to its right in right-to-left language scripts) are frozen as well. Frozen columns remain in place while all other columns can scroll. If column reordering is enabled, the frozen columns are treated as a group distinct from the unfrozen columns. Users can reposition columns in either group, but they cannot move a column from one group to the other. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To freeze a column using the designer + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Edit Columns**. + +2. Select a column from the **Selected Columns** list. + +3. In the **Column Properties** grid, set the property to `true`. + + > [!NOTE] + > You can also freeze a column when adding it by selecting the **Frozen** box in the **Add Column** dialog box. + +## See also + +- +- +- [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md) +- [How to: Enable Column Reordering in the Windows Forms DataGridView Control Using the Designer](enable-column-reordering-in-the-datagrid-using-the-designer.md) +- [How to: Display Right-to-Left Text in Windows Forms for Globalization](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/7d3337xw(v=vs.100)) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/get-and-set-the-current-cell-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/get-and-set-the-current-cell-wf-datagridview-control.md new file mode 100644 index 0000000000..fb24b04f15 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/get-and-set-the-current-cell-wf-datagridview-control.md @@ -0,0 +1,50 @@ +--- +title: Get and Set the Current Cell in DataGridView Control +description: Learn how to programmatically discover which cell is currently active by getting and setting the current cell in the Windows Forms DataGridView control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], getting current cell" + - "DataGridView control [Windows Forms], setting current cell" + - "cells [Windows Forms], getting and setting current" +ms.assetid: b0e41e57-493a-4bd0-9376-a6f76723540c +--- +# How to: Get and Set the Current Cell in the Windows Forms DataGridView Control +Interaction with the often requires that you programmatically discover which cell is currently active. You may also need to change the current cell. You can perform these tasks with the property. + +> [!NOTE] +> You cannot set the current cell in a row or column that has its property set to `false`. + + Depending on the control's selection mode, changing the current cell can change the selection. For more information, see [Selection Modes in the Windows Forms DataGridView Control](selection-modes-in-the-windows-forms-datagridview-control.md). + +### To get the current cell programmatically + +- Use the control's property. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#080](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#080)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#080](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#080)] + +### To set the current cell programmatically + +- Set the property of the control. In the following code example, the current cell is set to row 0, column 1. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#085](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#085)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#085](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#085)] + +## Compiling the Code + This example requires: + +- controls named `getCurrentCellButton` and `setCurrentCellButton`. In Visual C#, you must attach the events for each button to the associated event handler in the example code. + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) +- [Selection Modes in the Windows Forms DataGridView Control](selection-modes-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/group-controls-with-wf-panel-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/group-controls-with-wf-panel-control-using-the-designer.md new file mode 100644 index 0000000000..50c43f51d5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/group-controls-with-wf-panel-control-using-the-designer.md @@ -0,0 +1,27 @@ +--- +title: Group Controls with Panel Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "Panel control [Windows Forms], grouping controls" + - "controls [Windows Forms], grouping" + - "Windows Forms controls, grouping" +ms.assetid: 7e1cd708-fdb1-49d8-9ca2-5640b276bf2e +--- +# How to: Group Controls with the Windows Forms Panel Control Using the Designer +Windows Forms controls are used to group other controls. There are three reasons to group controls. One is visual grouping of related form elements for a clear user interface; another is programmatic grouping, of radio buttons for example; the last is for moving the controls as a unit at design time. + +## To create a group of controls + +1. Drag a control from the **Windows Forms** tab of the Toolbox onto a form. + +2. Add other controls to the panel, drawing each inside the panel. + + If you have existing controls that you want to enclose in a panel, you can select all the controls, cut them to the Clipboard, select the control, and then paste them into the panel. You can also drag them into the panel. + +3. (Optional) If you want to add a border to a panel, set its property. There are three choices: , , and . + +## See also + +- [Panel Control](panel-control-windows-forms.md) +- [Panel Control Overview](panel-control-overview-windows-forms.md) +- [How to: Set the Background of a Panel](how-to-set-the-background-of-a-windows-forms-panel.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/groupbox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/groupbox-control-overview-windows-forms.md new file mode 100644 index 0000000000..1fe02a7bb4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/groupbox-control-overview-windows-forms.md @@ -0,0 +1,21 @@ +--- +title: "GroupBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "GroupBox" +helpviewer_keywords: + - "GroupBox control [Windows Forms], about GroupBox control" + - "grouping controls [Windows Forms], Windows Forms" +ms.assetid: 03bd8ff9-c905-4f01-9bc6-8438b11d0881 +--- +# GroupBox Control Overview (Windows Forms) +Windows Forms controls are used to provide an identifiable grouping for other controls. Typically, you use group boxes to subdivide a form by function. For example, you may have an order form that specifies mailing options such as which overnight carrier to use. Grouping all options in a group box gives the user a logical visual cue, and at design time all the controls can be moved easily — when you move the single control, all its contained controls move, too. + + The group box's caption is defined by the property. For more information, see [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md). + +## GroupBox and Panel + The control is similar to the control; however, only the control displays a caption, and only the control can have scroll bars. + +## See also + +- [GroupBox Control](groupbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/groupbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/groupbox-control-windows-forms.md new file mode 100644 index 0000000000..6926daa656 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/groupbox-control-windows-forms.md @@ -0,0 +1,29 @@ +--- +title: "GroupBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], grouping" + - "GroupBox control [Windows Forms]" + - "grouping controls [Windows Forms]" +ms.assetid: ee7fb3ed-2fae-4df3-bdeb-15d42e5d7d75 +--- +# GroupBox Control (Windows Forms) +Windows Forms controls are used to provide an identifiable grouping for other controls. Typically, you use group boxes to subdivide a form by function. For example, you may have an order form that specifies mailing options such as which overnight carrier to use. Grouping all options in a group box gives the user a logical visual cue. The control is similar to the control; however, only the control displays a caption, and only the control can have scroll bars. + +## In This Section + [GroupBox Control Overview](groupbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Group Controls with the Windows Forms GroupBox Control](how-to-group-controls-with-the-windows-forms-groupbox-control.md) + Describes how to use this control to group controls. + +## Reference + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/handle-errors-that-occur-during-data-entry-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/handle-errors-that-occur-during-data-entry-in-the-datagrid.md new file mode 100644 index 0000000000..e85f2e2167 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/handle-errors-that-occur-during-data-entry-in-the-datagrid.md @@ -0,0 +1,39 @@ +--- +title: Handle Errors That Occur During Data Entry in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "error handling [Windows Forms], dataGridView control" + - "data grids [Windows Forms], error handling" + - "DataGridView control [Windows Forms], error handling" + - "data entry [Windows Forms], error handling" + - "error handling [Windows Forms], data entry" +ms.assetid: 9004e72f-fdec-4264-a37d-2c99764efc13 +--- +# How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control +The following code example demonstrates how to use the control to report data entry errors to the user. + + For a complete explanation of this code example, see [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridView.DataError#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs#00)] + [!code-vb[System.Windows.Forms.DataGridView.DataError#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Windows.Forms, and System.XML assemblies. + +## .NET Framework Security + Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + +## See also + +- +- +- [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md) +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) +- [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/handling-errors-that-occur-during-data-entry-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/handling-errors-that-occur-during-data-entry-in-the-datagrid.md new file mode 100644 index 0000000000..f2c8cb57df --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/handling-errors-that-occur-during-data-entry-in-the-datagrid.md @@ -0,0 +1,96 @@ +--- +title: "Walkthrough: Handling errors that occur during data entry in DataGridView control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "error handling [Windows Forms], dataGridView control" + - "data grids [Windows Forms], error handling" + - "DataGridView control [Windows Forms], error handling" + - "data entry [Windows Forms], error handling" + - "error handling [Windows Forms], data entry" + - "walkthroughs [Windows Forms], DataGridView control" +ms.assetid: 30a68b85-d3af-4946-83c1-1e2d010d0511 +--- +# Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control + +Handling errors from the underlying data store is a required feature for a data-entry application. The Windows Forms control makes this easy by exposing the event, which is raised when the data store detects a constraint violation or a broken business rule. + +In this walkthrough, you will retrieve rows from the `Customers` table in the Northwind sample database and display them in a control. When a duplicate `CustomerID` value is detected in a new row or an edited existing row, the event will occur, which will be handled by displaying a that describes the exception. + +To copy the code in this topic as a single listing, see [How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control](handle-errors-that-occur-during-data-entry-in-the-datagrid.md). + +## Prerequisites + +In order to complete this walkthrough, you will need: + +- Access to a server that has the Northwind SQL Server sample database. + +## Creating the Form + +#### To handle data-entry errors in the DataGridView control + +1. Create a class that derives from and contains a control and a component. + + The following code example provides basic initialization and includes a `Main` method. + + [!code-csharp[System.Windows.Forms.DataGridView.DataError#01](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs#01)] + [!code-vb[System.Windows.Forms.DataGridView.DataError#01](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb#01)] + [!code-csharp[System.Windows.Forms.DataGridView.DataError#02](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs#02)] + [!code-vb[System.Windows.Forms.DataGridView.DataError#02](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb#02)] + +2. Implement a method in your form's class definition for handling the details of connecting to the database. + + This code example uses a `GetData` method that returns a populated object. Be sure that you set the `connectionString` variable to a value that is appropriate for your database. + + > [!IMPORTANT] + > Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + + [!code-csharp[System.Windows.Forms.DataGridView.DataError#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs#30)] + [!code-vb[System.Windows.Forms.DataGridView.DataError#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb#30)] + +3. Implement a handler for your form's event that initializes the and and sets up the data binding. + + [!code-csharp[System.Windows.Forms.DataGridView.DataError#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs#10)] + [!code-vb[System.Windows.Forms.DataGridView.DataError#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb#10)] + +4. Handle the event on the . + + If the context for the error is a commit operation, display the error in a . + + [!code-csharp[System.Windows.Forms.DataGridView.DataError#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs#20)] + [!code-vb[System.Windows.Forms.DataGridView.DataError#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb#20)] + +## Testing the Application + +You can now test the form to make sure it behaves as expected. + +#### To test the form + +- Press F5 to run the application. + + You will see a control filled with data from the Customers table. If you enter a duplicate value for `CustomerID` and commit the edit, the cell value will revert automatically and you will see a that displays the data entry error. + +## Next Steps + +This application gives you a basic understanding of the control's capabilities. You can customize the appearance and behavior of the control in several ways: + +- Change border and header styles. For more information, see [How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control](change-the-border-and-gridline-styles-in-the-datagrid.md). + +- Enable or restrict user input to the control. For more information, see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md), and [How to: Make Columns Read-Only in the Windows Forms DataGridView Control](how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md). + +- Validate user input to the control. For more information, see [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md). + +- Handle very large data sets using virtual mode. For more information, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +- Customize the appearance of cells. For more information, see [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) and [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) +- [How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control](handle-errors-that-occur-during-data-entry-in-the-datagrid.md) +- [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/handling-user-input.md b/dotnet-desktop-guide/framework/winforms/controls/handling-user-input.md new file mode 100644 index 0000000000..2868874a03 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/handling-user-input.md @@ -0,0 +1,65 @@ +--- +title: "Handling User Input" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], user input using code" + - "custom controls [Windows Forms], keyboard events using code" + - "custom controls [Windows Forms], mouse events using code" +ms.assetid: d9b12787-86f6-4022-8e0f-e12d312c4af2 +--- +# Handling User Input +This topic describes the main keyboard and mouse events provided by . When handling an event, control authors should override the protected `On`*EventName* method rather than attaching a delegate to the event. For a review of events, see [Raising Events from a Component](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/sh2e3k5z(v=vs.120)). + +> [!NOTE] +> If there is no data associated with an event, an instance of the base class is passed as an argument to the `On`*EventName* method. + +## Keyboard Events + The common keyboard events that your control can handle are , , and . + +|Event Name|Method to Override|Description of Event| +|----------------|------------------------|--------------------------| +|`KeyDown`|`void OnKeyDown(KeyEventArgs)`|Raised only when a key is initially pressed.| +|`KeyPress`|`void OnKeyPress`

`(KeyPressEventArgs)`|Raised every time a key is pressed. If a key is held down, a event is raised at the repeat rate defined by the operating system.| +|`KeyUp`|`void OnKeyUp(KeyEventArgs)`|Raised when a key is released.| + +> [!NOTE] +> Handling keyboard input is considerably more complex than overriding the events in the preceding table and is beyond the scope of this topic. For more information, see [User Input in Windows Forms](../user-input-in-windows-forms.md). + +## Mouse Events + The mouse events that your control can handle are , , , , , and . + +|Event Name|Method to Override|Description of Event| +|----------------|------------------------|--------------------------| +|`MouseDown`|`void OnMouseDown(MouseEventArgs)`|Raised when the mouse button is pressed while the pointer is over the control.| +|`MouseEnter`|`void OnMouseEnter(EventArgs)`|Raised when the pointer first enters the region of the control.| +|`MouseHover`|`void OnMouseHover(EventArgs)`|Raised when the pointer hovers over the control.| +|`MouseLeave`|`void OnMouseLeave(EventArgs)`|Raised when the pointer leaves the region of the control.| +|`MouseMove`|`void OnMouseMove(MouseEventArgs)`|Raised when the pointer moves in the region of the control.| +|`MouseUp`|`void OnMouseUp(MouseEventArgs)`|Raised when the mouse button is released while the pointer is over the control or the pointer leaves the region of the control.| + + The following code fragment shows an example of overriding the event. + + [!code-csharp[System.Windows.Forms.FlashTrackBar#7](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#7)] + [!code-vb[System.Windows.Forms.FlashTrackBar#7](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#7)] + + The following code fragment shows an example of overriding the event. + + [!code-csharp[System.Windows.Forms.FlashTrackBar#8](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#8)] + [!code-vb[System.Windows.Forms.FlashTrackBar#8](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#8)] + + The following code fragment shows an example of overriding the event. + + [!code-csharp[System.Windows.Forms.FlashTrackBar#9](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#9)] + [!code-vb[System.Windows.Forms.FlashTrackBar#9](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#9)] + + For the complete source code for the `FlashTrackBar` sample, see [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + +## See also + +- [Events in Windows Forms Controls](events-in-windows-forms-controls.md) +- [Defining an Event](defining-an-event-in-windows-forms-controls.md) +- [Events](https://docs.microsoft.com/dotnet/standard/events/index) +- [User Input in Windows Forms](../user-input-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/helpprovider-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/helpprovider-component-overview-windows-forms.md new file mode 100644 index 0000000000..05a9f5a06c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/helpprovider-component-overview-windows-forms.md @@ -0,0 +1,35 @@ +--- +title: "HelpProvider Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "HelpProvider" +helpviewer_keywords: + - "HelpProvider component [Windows Forms], about HelpProvider component" + - "Help [Windows Forms], adding to Windows applications" + - "F1 Help [Windows Forms], adding to Windows Forms" + - "dialog boxes [Windows Forms], context-sensitive Help" + - "Windows Forms, context-sensitive Help" +ms.assetid: 6b10c2cc-c577-4cb5-9669-e37b33416af9 +--- +# HelpProvider Component Overview (Windows Forms) +The Windows Forms [HelpProvider](helpprovider-component-windows-forms.md) component is used to associate an HTML Help 1.x Help file (either a .chm file, produced with the HTML Help Workshop, or an .htm file) with your Windows application. You can provide help in a variety of ways: + +- Provide context-sensitive Help for controls on Windows Forms. + +- Provide context-sensitive Help on a particular dialog box or specific controls on a dialog box. + +- Open a Help file to specific areas, such as the main page of a Table of Contents, the Index, or a search function. + +## Using the Help Provider + Adding a component to your Windows Form allows the other controls on the form to expose the Help properties of the component. This enables you to provide help for the controls on your Windows Form. You can associate a Help file with the component using the property. You specify the type of Help provided by calling and providing a value from the enumeration for the specified control. You provide the keyword or topic for Help by calling the method. + + Optionally, to associate a specific Help string with another control, use the method. The string that you associate with a control using this method is displayed in a pop-up window when the user presses the F1 key while the control has focus. + + If has not been set, you must use to provide the Help text. If you have set both and the Help string, Help based on will take precedence. + +> [!NOTE] +> You may encounter problems using the relative path when specifying the path to the Help file in the method or property of the control. As such, be sure to use the absolute file path to specify the Help file. + +## See also + +- [Help Systems in Windows Forms Applications](../advanced/help-systems-in-windows-forms-applications.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/helpprovider-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/helpprovider-component-windows-forms.md new file mode 100644 index 0000000000..8ec5907f39 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/helpprovider-component-windows-forms.md @@ -0,0 +1,30 @@ +--- +title: "HelpProvider Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "forms [Windows Forms], Help" + - "Help [Windows Forms], displaying on Windows Forms" + - "HelpProvider component [Windows Forms]" +ms.assetid: a09a6e0b-79d8-457f-bb36-86fad2beeada +--- +# HelpProvider Component (Windows Forms) +The Windows Forms `HelpProvider` component is used to associate an HTML Help 1.x Help file (either a .chm file, produced with the HTML Help Workshop, or an .htm file) with your Windows-based application. + +## In This Section + [HelpProvider Component Overview](helpprovider-component-overview-windows-forms.md) + Introduces the general concepts of the `HelpProvider` component, which lets you associate an HTML Help file with a Windows-based application. + + See [Help Systems in Windows Forms Applications](../advanced/help-systems-in-windows-forms-applications.md). + +## Reference + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + Also see [Help Systems in Windows Forms Applications](../advanced/help-systems-in-windows-forms-applications.md). diff --git a/dotnet-desktop-guide/framework/winforms/controls/hide-columns-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/hide-columns-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..00140a2b7f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/hide-columns-in-the-datagrid-using-the-designer.md @@ -0,0 +1,33 @@ +--- +title: Hide Columns in DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, columns" + - "columns [Windows Forms], hiding" + - "DataGridView control [Windows Forms], column hiding" + - "data [Windows Forms], displaying" +ms.assetid: a81c38e6-2527-426a-bcb1-be691403be04 +--- +# How to: Hide Columns in the Windows Forms DataGridView Control Using the Designer +Sometimes you will want to display only some of the columns that are available in a Windows Forms control. For example, you may want to show an employee salary column to users with management credentials while hiding it from other users. Alternately, you may want to bind the control to a data source that contains many columns, only some of which you want to display. In this case, you will typically remove the columns you are not interested in displaying rather than hiding them. For more information, see [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md). + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To hide a column using the designer + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Edit Columns**. + +2. Select a column from the **Selected Columns** list. + +3. In the **Column Properties** grid, set the property to `false`. + + > [!NOTE] + > You can also hide a column when adding it by clearing the **Visible** check box in the **Add Column** dialog box. + +## See also + +- +- +- [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-access-objects-bound-to-windows-forms-datagridview-rows.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-access-objects-bound-to-windows-forms-datagridview-rows.md new file mode 100644 index 0000000000..2bc5890545 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-access-objects-bound-to-windows-forms-datagridview-rows.md @@ -0,0 +1,42 @@ +--- +title: Access Objects Bound to DataGridView Rows +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "object binding [Windows Forms], accessing bound objects" + - "data grids [Windows Forms], accessing bound objects" + - "DataGridView control [Windows Forms], accessing objects bound to rows" +ms.assetid: 0e05748f-4403-4eb8-8b2f-b098108181b5 +--- +# How to: Access Objects Bound to Windows Forms DataGridView Rows +Sometimes it is useful to display a table of information stored in a collection of business objects. When you bind a control to such a collection, each public property is displayed in its own column unless the property has been marked non-browsable with a . For example, a collection of `Customer` objects would have columns such as **Name** and **Address**. + + If these objects contain additional information and code that you want to access, you can reach it through row objects. In the following code example, users can select multiple rows and click a button to send an invoice to each of the corresponding customers. + +### To access row-bound objects + +- Use the property. + + [!code-csharp[System.Windows.Forms.DataGridViewObjectBinding#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/CS/datagridviewobjectbinding.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewObjectBinding#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/VB/datagridviewobjectbinding.vb#10)] + +## Example + The complete code example includes a simple `Customer` implementation and binds the to an containing a few `Customer` objects. The event handler of the must access the `Customer` objects through the rows, because the customer collection is not accessible outside the event handler. + + [!code-csharp[System.Windows.Forms.DataGridViewObjectBinding#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/CS/datagridviewobjectbinding.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewObjectBinding#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/VB/datagridviewobjectbinding.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Bind Objects to Windows Forms DataGridView Controls](how-to-bind-objects-to-windows-forms-datagridview-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-access-the-html-source-in-the-managed-html-document-object-model.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-access-the-html-source-in-the-managed-html-document-object-model.md new file mode 100644 index 0000000000..c7ff67ad55 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-access-the-html-source-in-the-managed-html-document-object-model.md @@ -0,0 +1,45 @@ +--- +title: "How to: Access the HTML Source in the Managed HTML Document Object Model" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "managed HTML DOM" + - "HTML [Windows Forms], accessing in Windows Forms" +ms.assetid: 53db79fa-8a5e-448e-88c2-f54ace3860b6 +--- +# How to: Access the HTML Source in the Managed HTML Document Object Model +The and properties on the control return the HTML of the current document as it existed when it was first displayed. However, if you modify the page using method and property calls such as and , these changes will not appear when you call and . To obtain the most up-to-date HTML source for the DOM, you must call the property on the HTML element. + + The following procedure shows how to retrieve the dynamic source and display it in a separate shortcut menu. + +### Retrieving the dynamic source with the OuterHtml property + +1. Create a new Windows Forms application. Start with a single , and call it `Form1`. + +2. Host the control in your Windows Forms application, and name it `WebBrowser1`. For more information, see [How to: Add Web Browser Capabilities to a Windows Forms Application](how-to-add-web-browser-capabilities-to-a-windows-forms-application.md). + +3. Create a second in your application called `CodeForm`. + +4. Add a control to `CodeForm` and set its property to `Fill`. + +5. Create a public property on `CodeForm` called `Code`. + + [!code-csharp[DisplayWebBrowserCode#1](~/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.cs#1)] + [!code-vb[DisplayWebBrowserCode#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.vb#1)] + +6. Add a control named `Button1` to your , and monitor for the event. For details on monitoring events, see [Events](https://docs.microsoft.com/dotnet/standard/events/index). + +7. Add the following code to the event handler. + + [!code-csharp[DisplayWebBrowserCode#2](~/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.cs#2)] + [!code-vb[DisplayWebBrowserCode#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.vb#2)] + +## Robust Programming + Always test the value of before attempting to retrieve it. If the current page is not finished loading, or one or more of its child objects may not be initialized. + +## See also + +- [Using the Managed HTML Document Object Model](using-the-managed-html-document-object-model.md) +- [WebBrowser Control Overview](webbrowser-control-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-access-the-managed-html-document-object-model.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-access-the-managed-html-document-object-model.md new file mode 100644 index 0000000000..5ffa45c0b4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-access-the-managed-html-document-object-model.md @@ -0,0 +1,44 @@ +--- +title: "How to: Access the Managed HTML Document Object Model" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "HTML DOM [Windows Forms], accessing" + - "managed HTML DOM [Windows Forms], accessing" +ms.assetid: 40fa5cd5-1ed8-42f6-a93f-9ac01608bbeb +--- +# How to: Access the Managed HTML Document Object Model +You can access the managed HTML Document Object Model (DOM) from two types of applications: + +- A Windows Forms application (.exe) that hosted the managed control. These two technologies complement one another, with the control displaying the page to the user and the HTML DOM representing the document's logical structure. + +- A Windows Forms hosted within Internet Explorer. You can access the HTML DOM representing the page on which your is hosted in order to change the document's structure or open modal dialog boxes, among many other possibilities. + +### To access DOM from a Windows Forms application + +1. Host a control within your Windows Forms application and monitor for the event. For details on hosting controls and monitoring for events, see [Events](https://docs.microsoft.com/dotnet/standard/events/index). + +2. Retrieve the for the current page by accessing the property of the control. + +### To access DOM from a UserControl hosted in Internet Explorer + +1. Create your own custom derived class of the class. For more information, see [How to: Author Composite Controls](how-to-author-composite-controls.md). + +2. Place the following code inside of your Load event handler for your : + + [!code-csharp[AccessHTMLDOMControl#1](~/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.cs#1)] + [!code-vb[AccessHTMLDOMControl#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.vb#1)] + +## Robust Programming + +1. When using the DOM through the control, you should always wait until the event occurs before attempting to access the property of the control. The event is raised after the entire document has loaded; if you use the DOM before then, you risk causing a run-time exception in your application. + +## .NET Framework Security + +1. Your application or will require full trust in order to access the managed HTML DOM. If you are deploying a Windows Forms application using ClickOnce, you can request full trust using either Permission Elevation or Trusted Application Deployment; see [Securing ClickOnce Applications](/visualstudio/deployment/securing-clickonce-applications) for details. + +## See also + +- [Using the Managed HTML Document Object Model](using-the-managed-html-document-object-model.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-tab-page-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-tab-page-using-the-designer.md new file mode 100644 index 0000000000..ed8f6d39e7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-tab-page-using-the-designer.md @@ -0,0 +1,27 @@ +--- +title: "How to: Add a Control to a Tab Page Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "TabPage control" + - "tab controls [Windows Forms], tab order" + - "tab pages [Windows Forms], adding controls" +ms.assetid: 7ee734e1-e31e-4ed0-bbc0-a7e8a1f20fef +--- +# How to: Add a Control to a Tab Page Using the Designer +The use of the Windows Forms is to display other controls in an organized fashion. You can use these instructions to display a picture on the main part of a tab page. For information about adding an icon to the label part of a tab page, see [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md). + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To add a control using the designer + +1. Click the appropriate tab page so that it appears on top. + +2. Draw the control on the tab page. + +## See also + +- [TabControl Control](tabcontrol-control-windows-forms.md) +- [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) +- [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) +- [How to: Disable Tab Pages](how-to-disable-tab-pages.md) +- [How to: Add and Remove Tabs with the Windows Forms TabControl](how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-tab-page.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-tab-page.md new file mode 100644 index 0000000000..0bbd8a1f87 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-tab-page.md @@ -0,0 +1,31 @@ +--- +title: "How to: Add a Control to a Tab Page" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "TabPage control" + - "tab controls [Windows Forms], tab order" + - "tab pages [Windows Forms], adding controls" +ms.assetid: b092532e-7346-469f-b9a1-897f9bea4fb7 +--- +# How to: Add a Control to a Tab Page +You can use the Windows Forms to display other controls in an organized fashion. The following procedure shows how to add a button to the first tab. For information about adding an icon to the label part of a tab page, see [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md). + +### To add a control programmatically + +1. Use the method of the collection returned by the property of : + + [!code-cpp[TabPageControlCollectionHowToAdd#1](~/samples/snippets/cpp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cpp/add.cpp#1)] + [!code-csharp[TabPageControlCollectionHowToAdd#1](~/samples/snippets/csharp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cs/add.cs#1)] + [!code-vb[TabPageControlCollectionHowToAdd#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/vb/add.vb#1)] + +## See also + +- [TabControl Control](tabcontrol-control-windows-forms.md) +- [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) +- [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) +- [How to: Disable Tab Pages](how-to-disable-tab-pages.md) +- [How to: Add and Remove Tabs with the Windows Forms TabControl](how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-toolstripcontentpanel.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-toolstripcontentpanel.md new file mode 100644 index 0000000000..5d014fa347 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-control-to-a-toolstripcontentpanel.md @@ -0,0 +1,30 @@ +--- +title: "How to: Add a Control to a ToolStripContentPanel" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStripContentPanel [Windows Forms], adding controls" +ms.assetid: fa410960-bf1a-42fc-80e8-f2e27fb3dbb8 +--- +# How to: Add a Control to a ToolStripContentPanel +You can programmatically add one or more controls to a . + +## Example + The following code example demonstrates how to add a to a . + + [!code-csharp[System.Windows.Forms.ToolStripContainer#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.ToolStripContainer#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/VB/Form1.vb#1)] + +## Compiling the Code + This code example requires: + +- References to the System, System.Data and System.Windows.Forms assemblies. + +## See also + +- +- +- [ToolStripContainer Control](toolstripcontainer-control.md) +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-custom-place-to-a-file-dialog-box.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-custom-place-to-a-file-dialog-box.md new file mode 100644 index 0000000000..eca73b84d7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-custom-place-to-a-file-dialog-box.md @@ -0,0 +1,37 @@ +--- +title: "How To: Add a Custom Place to a File Dialog Box" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Custom Place to dialog box" + - "adding Custom Place to dialog box" + - "CustomPlaces collection" +ms.assetid: 63f6469b-59cd-40f6-9e61-8b5831856780 +--- +# How To: Add a Custom Place to a File Dialog Box +The default open and save dialog boxes on Windows Vista have an area on the left side of the dialog box titled **Favorite Links**. This area is called custom places. The and classes allow you to add folders to the collection. + +> [!NOTE] +> In order for a custom place to appear in the or , the property must be set to `true` (the default). + +### To add a custom place to a file dialog box + +- Add a path, a Known Folder GUID, or a object to the collection of the dialog box. + + The following code example shows how to add a path: + + ```vb + OpenFileDialog1.CustomPlaces.Add("C:\MyCustomPlace") + ``` + + ```csharp + openFileDialog1.CustomPlaces.Add("C:\\MyCustomPlace"); + ``` + +## See also + +- +- +- [Known Folder GUIDs for File Dialog Custom Places](known-folder-guids-for-file-dialog-custom-places.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-toolstripcontainer-to-a-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-toolstripcontainer-to-a-form.md new file mode 100644 index 0000000000..517e884045 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-a-toolstripcontainer-to-a-form.md @@ -0,0 +1,31 @@ +--- +title: "How to: Add a ToolStripContainer to a Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms], built-in rafting" + - "ToolStrip control [Windows Forms], built-in rafting" + - "ToolStripContainer control [Windows Forms], adding to Windows Forms" +ms.assetid: d0f55095-a833-453e-be5a-644906d75d54 +--- +# How to: Add a ToolStripContainer to a Form +You can programmatically add a to a Windows Form and populate it with controls. + +## Example + The following code example demonstrates how to add a and a to a Windows Forms, how to add items to the , and how to add the to the of the . + + [!code-csharp[System.Windows.Forms.ToolStripContainer2#1](~/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/cs/form1.cs#1)] + [!code-vb[System.Windows.Forms.ToolStripContainer2#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/vb/form1.vb#1)] + +## Compiling the Code + This code example requires: + +- References to the System.Drawing, System.Text, and System.Windows.Forms assemblies. + +## See also + +- +- [ToolStripContainer Control](toolstripcontainer-control.md) +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-activex-controls-to-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-activex-controls-to-windows-forms.md new file mode 100644 index 0000000000..a8b6d26b13 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-activex-controls-to-windows-forms.md @@ -0,0 +1,35 @@ +--- +title: Add ActiveX Controls to forms +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, ActiveX controls" + - "forms [Windows Forms], adding ActiveX controls" + - "ActiveX controls [Windows Forms], adding" +ms.assetid: 54a61e5b-555e-4887-b41e-6244fed271eb +--- +# How to: Add ActiveX Controls to Windows Forms + +While the Windows Forms Designer in Visual Studio is optimized to host Windows Forms controls, you can also put ActiveX controls on Windows Forms. + +> [!CAUTION] +> There are performance limitations for Windows Forms when ActiveX controls are added to them. + +Before you add ActiveX controls to your form, you must add them to the Toolbox. For more information, see [COM Components, Customize Toolbox Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/cby6tzh5(v=vs.100)). + +## Add an ActiveX control to your Windows Form + +To add an ActiveX control to your Windows Form, double-click the control on the Toolbox. + +Visual Studio adds all references to the control in your project. For more information about things to keep in mind when using ActiveX controls on Windows Forms, see [Considerations When Hosting an ActiveX Control on a Windows Form](considerations-when-hosting-an-activex-control-on-a-windows-form.md). + +> [!NOTE] +> The Windows Forms ActiveX Control Importer (AxImp.exe) creates event arguments of a different type than expected upon importation of ActiveX dynamic link libraries. The arguments created by AxImp.exe are similar to the following: `Invoke(object sender, DWebBrowserEvents2_ProgressChangeEvent e)`, when `Invoke(object sender, DWebBrowserEvents2_ProgressChangeEventArgs e)` is expected. Be aware that this irregularity does not prevent code from functioning normally. For details, see [Windows Forms ActiveX Control Importer (Aximp.exe)](https://docs.microsoft.com/dotnet/framework/tools/aximp-exe-windows-forms-activex-control-importer). + +## See also + +- [Windows Forms Controls](index.md) +- [Controls and Programmable Objects Compared in Various Languages and Libraries](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/0061wezk(v=vs.100)) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-items-with-the-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-items-with-the-windows-forms-listview-control.md new file mode 100644 index 0000000000..bb161d360a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-items-with-the-windows-forms-listview-control.md @@ -0,0 +1,35 @@ +--- +title: Add and Remove Items with ListView Control +description: Learn how to add and remove an item with the Windows Forms ListView control by specifying the item and assigning properties to it. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ListView control [Windows Forms], populating" + - "list views [Windows Forms], adding list items" + - "ListView control [Windows Forms], adding list items" +ms.assetid: 1b35a80a-edd8-495f-a807-a28c4aae52c6 +--- +# How to: Add and Remove Items with the Windows Forms ListView Control +The process of adding an item to a Windows Forms control consists primarily of specifying the item and assigning properties to it. Adding or removing list items can be done at any time. + +### To add items programmatically + +1. Use the method of the property. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#11)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#11)] + +### To remove items programmatically + +1. Use the or method of the property. The method removes a single item; the method removes all items from the list. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#12)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#12)] + +## See also + +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md new file mode 100644 index 0000000000..5ab76d912c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md @@ -0,0 +1,74 @@ +--- +title: Add and Remove Nodes with TreeView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], TreeView control" + - "TreeView control [Windows Forms], removing nodes" + - "tree nodes in TreeView control" + - "TreeView control [Windows Forms], adding nodes" +ms.assetid: de1b82db-4905-449a-9f59-af271a6b6673 +--- +# How to: Add and Remove Nodes with the Windows Forms TreeView Control +The Windows Forms control stores the top-level nodes in its collection. Each also has its own collection to store its child nodes. Both collection properties are of type , which provides standard collection members that enable you to add, remove, and rearrange the nodes at a single level of the node hierarchy. + +### To add nodes programmatically + +1. Use the method of the tree view's property. + + ```vb + ' Adds new node as a child node of the currently selected node. + Dim newNode As TreeNode = New TreeNode("Text for new node") + TreeView1.SelectedNode.Nodes.Add(newNode) + ``` + + ```csharp + // Adds new node as a child node of the currently selected node. + TreeNode newNode = new TreeNode("Text for new node"); + treeView1.SelectedNode.Nodes.Add(newNode); + ``` + + ```cpp + // Adds new node as a child node of the currently selected node. + TreeNode ^ newNode = new TreeNode("Text for new node"); + treeView1->SelectedNode->Nodes->Add(newNode); + ``` + +### To remove nodes programmatically + +1. Use the method of the tree view's property to remove a single node, or the method to clear all nodes. + + ```vb + ' Removes currently selected node, or root if nothing is selected. + TreeView1.Nodes.Remove(TreeView1.SelectedNode) + ' Clears all nodes. + TreeView1.Nodes.Clear() + ``` + + ```csharp + // Removes currently selected node, or root if nothing + // is selected. + treeView1.Nodes.Remove(treeView1.SelectedNode); + // Clears all nodes. + TreeView1.Nodes.Clear(); + ``` + + ```cpp + // Removes currently selected node, or root if nothing + // is selected. + treeView1->Nodes->Remove(treeView1->SelectedNode); + // Clears all nodes. + treeView1->Nodes->Clear(); + ``` + +## See also + +- [TreeView Control](treeview-control-windows-forms.md) +- [TreeView Control Overview](treeview-control-overview-windows-forms.md) +- [How to: Set Icons for the Windows Forms TreeView Control](how-to-set-icons-for-the-windows-forms-treeview-control.md) +- [How to: Iterate Through All Nodes of a Windows Forms TreeView Control](how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md) +- [How to: Determine Which TreeView Node Was Clicked](how-to-determine-which-treeview-node-was-clicked-windows-forms.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md new file mode 100644 index 0000000000..edf6580213 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md @@ -0,0 +1,77 @@ +--- +title: Add and Remove Tabs with TabControl +description: Learn how to add and remove tabs with the Windows Forms TabControl control, which contains two TabPage controls. Access these tabs through the TabPages property. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "tabs [Windows Forms], removing from pages" + - "TabPage control" + - "TabControl control [Windows Forms], adding and removing tabs" + - "tabs [Windows Forms], adding to pages" + - "tab pages" +ms.assetid: 66d4dfca-41e8-44e3-9c80-fb7ac4cb1619 +--- +# How to: Add and Remove Tabs with the Windows Forms TabControl +By default, a control contains two controls. You can access these tabs through the property. + +### To add a tab programmatically + +- Use the method of the property. + + ```vb + Dim myTabPage As New TabPage() + myTabPage.Text = "TabPage" & (TabControl1.TabPages.Count + 1) + TabControl1.TabPages.Add(myTabPage) + ``` + + ```csharp + string title = "TabPage " + (tabControl1.TabCount + 1).ToString(); + TabPage myTabPage = new TabPage(title); + tabControl1.TabPages.Add(myTabPage); + ``` + + ```cpp + String^ title = String::Concat("TabPage ", + (tabControl1->TabCount + 1).ToString()); + TabPage^ myTabPage = gcnew TabPage(title); + tabControl1->TabPages->Add(myTabPage); + ``` + +### To remove a tab programmatically + +- To remove selected tabs, use the method of the property. + + -or- + +- To remove all tabs, use the method of the property. + + ```vb + ' Removes the selected tab: + TabControl1.TabPages.Remove(TabControl1.SelectedTab) + ' Removes all the tabs: + TabControl1.TabPages.Clear() + ``` + + ```csharp + // Removes the selected tab: + tabControl1.TabPages.Remove(tabControl1.SelectedTab); + // Removes all the tabs: + tabControl1.TabPages.Clear(); + ``` + + ```cpp + // Removes the selected tab: + tabControl1->TabPages->Remove(tabControl1->SelectedTab); + // Removes all the tabs: + tabControl1->TabPages->Clear(); + ``` + +## See also + +- [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) +- [How to: Add a Control to a Tab Page](how-to-add-a-control-to-a-tab-page.md) +- [How to: Disable Tab Pages](how-to-disable-tab-pages.md) +- [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-buttons-to-a-toolbar-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-buttons-to-a-toolbar-control-using-the-designer.md new file mode 100644 index 0000000000..a9d3a2d412 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-buttons-to-a-toolbar-control-using-the-designer.md @@ -0,0 +1,48 @@ +--- +title: "How to: Add Buttons to a ToolBar Control Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "toolbars [Windows Forms], adding buttons" + - "ToolBar control [Windows Forms], adding buttons" + - "ToolBar control [Windows Forms], adding separators" + - "examples [Windows Forms], toolbars" + - "ToolBar control [Windows Forms], adding drop-down menus" +ms.assetid: d9ce3040-3e21-4e2d-80ae-b430982b2db8 +--- +# How to: Add Buttons to a ToolBar Control Using the Designer + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + +An integral part of the control is the buttons you add to it. These can be used to provide easy access to menu commands or, alternately, they can be placed in another area of the user interface of your application to expose commands to your users that are not available in the menu structure. + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To add buttons at design time + +1. Select the control. + +2. In the **Properties** window, click the property to select it and click the **Ellipsis** (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button to open the **ToolBarButton Collection Editor**. + +3. Use the **Add** and **Remove** buttons to add and remove buttons from the control. + +4. Configure the properties of the individual buttons in the **Properties** window that appears in the pane on the right side of the editor. The following table shows some important properties to consider. + + |Property|Description| + |--------------|-----------------| + ||Sets the menu to be displayed in the drop-down toolbar button. The toolbar button's property must be set to . This property takes an instance of the class as a reference.| + ||Sets whether a toggle-style toolbar button is partially pushed. The toolbar button's property must be set to .| + ||Sets whether a toggle-style toolbar button is currently in the pushed state. The toolbar button's property must be set to or .| + ||Sets the style of the toolbar button. Must be one of the values in the enumeration.| + ||The text string displayed by the button.| + ||The text that appears as a ToolTip for the button.| + +5. Click **OK** to close the dialog box and create the panels you specified. + +## See also + +- +- [How to: Define an Icon for a ToolBar Button](how-to-define-an-icon-for-a-toolbar-button.md) +- [How to: Trigger Menu Events for Toolbar Buttons](how-to-trigger-menu-events-for-toolbar-buttons.md) +- [ToolBar Control Overview](toolbar-control-overview-windows-forms.md) +- [ToolBar Control](toolbar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-buttons-to-a-toolbar-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-buttons-to-a-toolbar-control.md new file mode 100644 index 0000000000..afcb1fdde4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-buttons-to-a-toolbar-control.md @@ -0,0 +1,151 @@ +--- +title: "How to: Add Buttons to a ToolBar Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "toolbars [Windows Forms], adding buttons" + - "ToolBar control [Windows Forms], adding buttons" + - "ToolBar control [Windows Forms], adding separators" + - "examples [Windows Forms], toolbars" + - "ToolBar control [Windows Forms], adding drop-down menus" +ms.assetid: 78a58a8d-1041-4e38-9219-4096fa6a5c5c +--- +# How to: Add Buttons to a ToolBar Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + An integral part of the control is the buttons you add to it. These can be used to provide easy access to menu commands or, alternately, they can be placed in another area of the user interface of your application to expose commands to your users that are not available in the menu structure. + + The examples below assume that a control has been added to a Windows Form (`Form1`). + +### To add buttons programmatically + +1. In a procedure, create toolbar buttons by adding them to the collection. + +2. Specify property settings for an individual button by passing the button's index via the property. + + The example below assumes a form with a control already added. + + > [!NOTE] + > The collection is a zero-based collection, so code should proceed accordingly. + + ```vb + Public Sub CreateToolBarButtons() + ' Create buttons and set text property. + ToolBar1.Buttons.Add("One") + ToolBar1.Buttons.Add("Two") + ToolBar1.Buttons.Add("Three") + ToolBar1.Buttons.Add("Four") + ' Set properties of StatusBar panels. + ' Set Style property. + ToolBar1.Buttons(0).Style = ToolBarButtonStyle.PushButton + ToolBar1.Buttons(1).Style = ToolBarButtonStyle.Separator + ToolBar1.Buttons(2).Style = ToolBarButtonStyle.ToggleButton + ToolBar1.Buttons(3).Style = ToolBarButtonStyle.DropDownButton + ' Set the ToggleButton's PartialPush property. + ToolBar1.Buttons(2).PartialPush = True + ' Instantiate a ContextMenu component and menu items. + ' Set the DropDownButton's DropDownMenu property to the context menu. + Dim cm As New ContextMenu() + Dim miOne As New MenuItem("One") + Dim miTwo As New MenuItem("Two") + Dim miThree As New MenuItem("Three") + cm.MenuItems.Add(miOne) + cm.MenuItems.Add(miTwo) + cm.MenuItems.Add(miThree) + ToolBar1.Buttons(3).DropDownMenu = cm + ' Set the PushButton's Pushed property. + ToolBar1.Buttons(0).Pushed = True + ' Set the ToolTipText property of one of the buttons. + ToolBar1.Buttons(1).ToolTipText = "Button 2" + End Sub + ``` + + ```csharp + public void CreateToolBarButtons() + { + // Create buttons and set text property. + toolBar1.Buttons.Add("One"); + toolBar1.Buttons.Add("Two"); + toolBar1.Buttons.Add("Three"); + toolBar1.Buttons.Add("Four"); + + // Set properties of StatusBar panels. + // Set Style property. + toolBar1.Buttons[0].Style = ToolBarButtonStyle.PushButton; + toolBar1.Buttons[1].Style = ToolBarButtonStyle.Separator; + toolBar1.Buttons[2].Style = ToolBarButtonStyle.ToggleButton; + toolBar1.Buttons[3].Style = ToolBarButtonStyle.DropDownButton; + + // Set the ToggleButton's PartialPush property. + toolBar1.Buttons[2].PartialPush = true; + + // Instantiate a ContextMenu component and menu items. + // Set the DropDownButton's DropDownMenu property to + // the context menu. + ContextMenu cm = new ContextMenu(); + MenuItem miOne = new MenuItem("One"); + MenuItem miTwo = new MenuItem("Two"); + MenuItem miThree = new MenuItem("Three"); + cm.MenuItems.Add(miOne); + cm.MenuItems.Add(miTwo); + cm.MenuItems.Add(miThree); + + toolBar1.Buttons[3].DropDownMenu = cm; + // Set the PushButton's Pushed property. + toolBar1.Buttons[0].Pushed = true; + // Set the ToolTipText property of 1 of the buttons. + toolBar1.Buttons[1].ToolTipText = "Button 2"; + } + ``` + + ```cpp + public: + void CreateToolBarButtons() + { + // Create buttons and set text property. + toolBar1->Buttons->Add( "One" ); + toolBar1->Buttons->Add( "Two" ); + toolBar1->Buttons->Add( "Three" ); + toolBar1->Buttons->Add( "Four" ); + + // Set properties of StatusBar panels. + // Set Style property. + toolBar1->Buttons[0]->Style = ToolBarButtonStyle::PushButton; + toolBar1->Buttons[1]->Style = ToolBarButtonStyle::Separator; + toolBar1->Buttons[2]->Style = ToolBarButtonStyle::ToggleButton; + toolBar1->Buttons[3]->Style = ToolBarButtonStyle::DropDownButton; + + // Set the ToggleButton's PartialPush property. + toolBar1->Buttons[2]->PartialPush = true; + + // Instantiate a ContextMenu component and menu items. + // Set the DropDownButton's DropDownMenu property to + // the context menu. + System::Windows::Forms::ContextMenu^ cm = gcnew System::Windows::Forms::ContextMenu; + MenuItem^ miOne = gcnew MenuItem( "One" ); + MenuItem^ miTwo = gcnew MenuItem( "Two" ); + MenuItem^ miThree = gcnew MenuItem( "Three" ); + cm->MenuItems->Add( miOne ); + cm->MenuItems->Add( miTwo ); + cm->MenuItems->Add( miThree ); + toolBar1->Buttons[3]->DropDownMenu = cm; + + // Set the PushButton's Pushed property. + toolBar1->Buttons[0]->Pushed = true; + + // Set the ToolTipText property of 1 of the buttons. + toolBar1->Buttons[1]->ToolTipText = "Button 2"; + } + ``` + +## See also + +- +- [How to: Define an Icon for a ToolBar Button](how-to-define-an-icon-for-a-toolbar-button.md) +- [How to: Trigger Menu Events for Toolbar Buttons](how-to-trigger-menu-events-for-toolbar-buttons.md) +- [ToolBar Control Overview](toolbar-control-overview-windows-forms.md) +- [ToolBar Control](toolbar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-columns-to-the-windows-forms-listview-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-columns-to-the-windows-forms-listview-control-using-the-designer.md new file mode 100644 index 0000000000..79b61e4bc2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-columns-to-the-windows-forms-listview-control-using-the-designer.md @@ -0,0 +1,31 @@ +--- +title: Add Columns to ListView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "ListView control [Windows Forms], adding column headers" + - "columns [Windows Forms], adding to ListView controls" +ms.assetid: 5b1a8b4d-587e-479a-95c1-f9b90884f13a +--- +# How to: Add Columns to the Windows Forms ListView Control Using the Designer + +The Windows Forms control can display multiple columns for each list item when in the **Details** view. You can use the columns to display several types of information about each list item. For example, a list of files could display the file name, file type, size, and date the file was last modified. For information on populating the columns once they are created, see [How to: Display Subitems in Columns with the Windows Forms ListView Control](how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md). + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To add columns in the designer + +1. In the **Properties** window, set the control's property to . + +2. In the **Properties** window, click the **Ellipsis** button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property. + + The **ColumnHeader Collection Editor** appears. + +3. Use the **Add** button to add new columns. You can then select the column header and set its text (the caption of the column), text alignment, and width. + +## See also + +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) +- [How to: Display Subitems in Columns with the Windows Forms ListView Control](how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md) +- [How to: Display Icons for the Windows Forms ListView Control](how-to-display-icons-for-the-windows-forms-listview-control.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-columns-to-the-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-columns-to-the-windows-forms-listview-control.md new file mode 100644 index 0000000000..abfc508002 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-columns-to-the-windows-forms-listview-control.md @@ -0,0 +1,30 @@ +--- +title: Add Columns to ListView Control +description: Learn how to add columns to the Windows Forms ListView control to display several types of information about each list item. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ListView control [Windows Forms], adding column headers" + - "columns [Windows Forms], adding to ListView controls" + - "list views [Windows Forms], adding columns" +ms.assetid: 79174274-12ee-4a5d-80db-6ec02976d010 +--- +# How to: Add Columns to the Windows Forms ListView Control +In the Details view, the control can display multiple columns for each list item. You can use the columns to display to the user several types of information about each list item. For example, a list of files could display the file name, file type, size, and date the file was last modified. For information about populating the columns after they are created, see [How to: Display Subitems in Columns with the Windows Forms ListView Control](how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md). + +### To add columns programmatically + +1. Set the control's property to . + +2. Use the method of the list view's property. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#31](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#31)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#31](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#31)] + +## See also + +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-controls-to-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-controls-to-windows-forms.md new file mode 100644 index 0000000000..6fe24856e6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-controls-to-windows-forms.md @@ -0,0 +1,90 @@ +--- +title: Add Controls +description: Learn how to draw a control on a Windows Form. A control is a component on a form you can use to display information or accept user input. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms controls, adding to form" + - "controls [Windows Forms], adding" +ms.assetid: 2af86001-9d62-4154-87fb-66db2c3cd9fd +--- +# How to: Add Controls to Windows Forms + +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. For more information about controls, see [Windows Forms Controls](index.md). + +## To draw a control on a form + +1. Open the form. For more information, see [How to: Display Windows Forms in the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/w5yd62ts(v=vs.100)). + +2. In the **Toolbox**, click the control you want to add to your form. + +3. On the form, click where you want the upper-left corner of the control to be located, and drag to where you want the lower-right corner of the control to be located. + + The control is added to the form with the specified location and size. + + > [!NOTE] + > Each control has a default size defined. You can add a control to your form in the control's default size by dragging it from the **Toolbox** to the form. + +## To drag a control to a form + +1. Open the form. For more information, see [How to: Display Windows Forms in the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/w5yd62ts(v=vs.100)). + +2. In the **Toolbox**, click the control you want and drag it to your form. + + The control is added to the form at the specified location in its default size. + + > [!NOTE] + > You can double-click a control in the **Toolbox** to add it to the upper-left corner of the form in its default size. + + You can also add controls dynamically to a form at run time. In the following code example, a control will be added to the form when a control is clicked. + + > [!NOTE] + > The following procedure requires the existence of a form with a **Button** control, `Button1`, already placed on it. + +## To add a control to a form programmatically + +1. In the method that handles the button's `Click` event within your form's class, insert code similar to the following to add a reference to your control variable, set the control's `Location`, and add the control. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + Dim MyText As New TextBox() + MyText.Location = New Point(25, 25) + Me.Controls.Add(MyText) + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + TextBox myText = new TextBox(); + myText.Location = new Point(25,25); + this.Controls.Add (myText); + } + ``` + + ```cpp + private: + System::Void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + TextBox ^ myText = gcnew TextBox(); + myText->Location = Point(25,25); + this->Controls->Add(myText); + } + ``` + + > [!NOTE] + > You can also add code to initialize other properties of the control. + + > [!IMPORTANT] + > You might expose your local computer to a security risk through the network by referencing a malicious `UserControl`. This would only be a concern in the case of a malicious person creating a damaging custom control, followed by you mistakenly adding it to your project. + +## See also + +- [Windows Forms Controls](index.md) +- [How to: Resize Controls on Windows Forms](how-to-resize-controls-on-windows-forms.md) +- [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-controls-without-a-user-interface-to-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-controls-without-a-user-interface-to-windows-forms.md new file mode 100644 index 0000000000..ea8839b0fe --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-controls-without-a-user-interface-to-windows-forms.md @@ -0,0 +1,82 @@ +--- +title: Add Controls Without a User Interface +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "NonVisualSelection" +helpviewer_keywords: + - "invisible controls [Windows Forms]" + - "Windows Forms controls, adding to form" + - "controls [Windows Forms], nonvisual" + - "Windows Forms controls, nonvisual" + - "nonvisual controls [Windows Forms]" +ms.assetid: 52134d9c-cff6-4eed-8e2b-3d5eb3bd494e +--- +# How to: Add Controls Without a User Interface to Windows Forms + +A nonvisual control (or component) provides functionality to your application. Unlike other controls, components do not provide a user interface to the user and thus do not need to be displayed on the Windows Forms Designer surface. When a component is added to a form, the Windows Forms Designer displays a resizable tray at the bottom of the form where all components are displayed. Once a control has been added to the component tray, you can select the component and set its properties as you would any other control on the form. + +## Add a component to a Windows Form + +1. Open the form in Visual Studio. For details, see [How to: Display Windows Forms in the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/w5yd62ts(v=vs.100)). + +2. In the **Toolbox**, click a component and drag it to your form. + + Your component appears in the component tray. + +Furthermore, components can be added to a form at run time. This is a common scenario, especially because components do not have a visual expression, unlike controls that have a user interface. In the example below, a component is added at run time. (Note that Visual Studio contains a number of different timers; in this case, use a Windows Forms component. For more information about the different timers in Visual Studio, see [Introduction to Server-Based Timers](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/tb9yt5e6(v=vs.90)).) + +> [!CAUTION] +> Components often have control-specific properties that must be set for the component to function effectively. In the case of the component below, you set the `Interval` property. Be sure, when adding components to your project, that you set the properties necessary for that component. + +## Add a component to a Windows Form programmatically + +1. Create an instance of the class in code. + +2. Set the `Interval` property to determine the time between ticks of the timer. + +3. Configure any other necessary properties for your component. + + The following code shows the creation of a with its `Interval` property set. + + ```vb + Public Sub CreateTimer() + Dim timerKeepTrack As New System.Windows.Forms.Timer + timerKeepTrack.Interval = 1000 + End Sub + ``` + + ```csharp + public void createTimer() + { + System.Windows.Forms.Timer timerKeepTrack = new + System.Windows.Forms.Timer(); + timerKeepTrack.Interval = 1000; + } + ``` + + ```cpp + public: + void createTimer() + { + System::Windows::Forms::Timer^ timerKeepTrack = gcnew + System::Windows::Forms::Timer(); + timerKeepTrack->Interval = 1000; + } + ``` + + > [!IMPORTANT] + > You might expose your local computer to a security risk through the network by referencing a malicious UserControl. This would only be a concern in the case of a malicious person creating a damaging custom control, followed by you mistakenly adding it to your project. + +## See also + +- [Windows Forms Controls](index.md) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) +- [How to: Add ActiveX Controls to Windows Forms](how-to-add-activex-controls-to-windows-forms.md) +- [Putting Controls on Windows Forms](putting-controls-on-windows-forms.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-enhancements-to-toolstripmenuitems.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-enhancements-to-toolstripmenuitems.md new file mode 100644 index 0000000000..1f9ab40aee --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-enhancements-to-toolstripmenuitems.md @@ -0,0 +1,114 @@ +--- +title: "How to: Add Enhancements to ToolStripMenuItems" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "commands [Windows Forms], grouping on menus" + - "check marks [Windows Forms], adding to menus" + - "ToolStripMenuItems [Windows Forms], displaying access keys" + - "menus [Windows Forms], grouping commands" + - "menu items [Windows Forms], displaying shortcut keys" + - "ToolStripMenuItems" + - "separators [Windows Forms], displaying on menus" + - "menu items [Windows Forms], showing separators" + - "menu items [Windows Forms], adding check marks" + - "ToolStripMenuItems [Windows Forms], adding check marks" + - "menu items [Windows Forms], adding images" + - "ToolStripSeparators [Windows Forms], displaying on MenuStrips" + - "menu items [Windows Forms], displaying access keys" + - "ToolStripMenuItems [Windows Forms], displaying shortcut keys" + - "ToolStripMenuItems [Windows Forms], adding images" + - "keyboard shortcuts [Windows Forms], displaying on menus" + - "images [Windows Forms], adding to menus" + - "ToolStripMenuItems [Windows Forms], showing separator bars" +ms.assetid: aa5f19bb-b545-4378-bfa6-36ba592f0d7c +--- +# How to: Add Enhancements to ToolStripMenuItems +You can enhance the usability of and controls in the following ways: + +- Add check marks to designate whether a feature is turned on or off, such as whether a ruler is displayed along the margin of a word-processing application, or to indicate which file in a list of files is being displayed, such as on a **Window** menu. + +- Add images that visually represent menu commands. + +- Display shortcut keys to provide a keyboard alternative to the mouse for performing commands. For example, pressing CTRL+C performs the **Copy** command. + +- Display access keys to provide a keyboard alternative to the mouse for menu navigation. For example, pressing ALT+F chooses the **File** menu. + +- Show separator bars to group related commands and make menus more readable. + +### To display a check mark on a menu command + +- Set its property to `true`. + + This also sets the property to `true`. Use this procedure only if you want the menu command to appear as checked by default, regardless of whether it is selected. + +### To display a check mark that changes state with each click + +- Set the menu command's property to `true`. + +### To add an image to a menu command + +- Set the menu command's property to the name of the image. If the property of this menu command is set to or , the image cannot be displayed. + +> [!NOTE] +> The image margin can also show a check mark if you so choose. Also, you can set the property of the image to `true`, and the image will appear with a hatched border around it at run time. + +### To display a shortcut key for a menu command + +- Set the menu command's property to the desired keyboard combination, such as CTRL+O for the **Open** menu command, and set the property to `true`. + +### To display custom shortcut keys for a menu command + +- Set the menu command's property to the desired keyboard combination, such as CTRL+SHIFT+O rather than SHIFT+CTRL+O, and set the property to `true`. + +### To display an access key for a menu command + +- When you set the property for the menu command, enter an ampersand (&) before the letter you want to be underlined as the access key. For example, typing `&Open` as the property of a menu item will result in a menu command that appears as Open. + + To navigate to this menu command, press ALT to give focus to the , and press the access key of the menu name. When the menu opens and shows items with access keys, you only need to press the access key to select the menu command. + +> [!NOTE] +> Avoid defining duplicate access keys, such as defining ALT+F twice in the same menu system. The selection order of duplicate access keys cannot be guaranteed. + +### To display a separator bar between menu commands + +- After you define your and the items it will contain, use the or method to add the menu commands and controls to the in the order you want. + + ```vb + ' This code adds a top-level File menu to the MenuStrip. + Me.menuStrip1.Items.Add(New ToolStripMenuItem() _ + {Me.fileToolStripMenuItem}) + + ' This code adds the New and Open menu commands, a separator bar, + ' and the Save and Exit menu commands to the top-level File menu, + ' in that order. + Me.fileToolStripMenuItem.DropDownItems.AddRange(New _ + ToolStripMenuItem() {Me.newToolStripMenuItem, _ + Me.openToolStripMenuItem, Me.toolStripSeparator1, _ + Me.saveToolStripMenuItem, Me.exitToolStripMenuItem}) + ``` + + ```csharp + // This code adds a top-level File menu to the MenuStrip. + this.menuStrip1.Items.Add(new ToolStripItem[]_ + {this.fileToolStripMenuItem}); + + // This code adds the New and Open menu commands, a separator bar, + // and the Save and Exit menu commands to the top-level File menu, + // in that order. + this.fileToolStripMenuItem.DropDownItems.AddRange(new _ + ToolStripItem[] { + this.newToolStripMenuItem, + this.openToolStripMenuItem, + this.toolStripSeparator1, + this.saveToolStripMenuItem, + this.exitToolStripMenuItem}); + ``` + +## See also + +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-items-to-windows-forms-domainupdown-controls-programmatically.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-items-to-windows-forms-domainupdown-controls-programmatically.md new file mode 100644 index 0000000000..de7bd8092c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-items-to-windows-forms-domainupdown-controls-programmatically.md @@ -0,0 +1,57 @@ +--- +title: Add Items to DomainUpDown Controls Programmatically +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "spin button control [Windows Forms], adding items" + - "DomainUpDown control [Windows Forms], adding items to" +ms.assetid: fd31d314-33eb-4181-90f8-d32ed0c4e072 +--- +# How to: Add Items to Windows Forms DomainUpDown Controls Programmatically +You can add items to the Windows Forms control in code. Call the or method of the class to add items to the control's property. The method adds an item to the end of a collection, while the method adds an item at a specified position. + +### To add a new item + +1. Use the method to add an item to the end of the list of items. + + ```vb + DomainUpDown1.Items.Add("noodles") + ``` + + ```csharp + domainUpDown1.Items.Add("noodles"); + ``` + + ```cpp + domainUpDown1->Items->Add("noodles"); + ``` + + -or- + +2. Use the method to insert an item into the list at a specified position. + + ```vb + ' Inserts an item at the third position in the list + DomainUpDown1.Items.Insert(2, "rice") + ``` + + ```csharp + // Inserts an item at the third position in the list + domainUpDown1.Items.Insert(2, "rice"); + ``` + + ```cpp + // Inserts an item at the third position in the list + domainUpDown1->Items->Insert(2, "rice"); + ``` + +## See also + +- +- +- +- [DomainUpDown Control](domainupdown-control-windows-forms.md) +- [DomainUpDown Control Overview](domainupdown-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-menu-items-to-a-contextmenustrip.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-menu-items-to-a-contextmenustrip.md new file mode 100644 index 0000000000..8e70101206 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-menu-items-to-a-contextmenustrip.md @@ -0,0 +1,46 @@ +--- +title: "How to: Add Menu Items to a ContextMenuStrip" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ContextMenuStrips [Windows Forms], adding menu items" + - "shortcut menus [Windows Forms], adding items" + - "context menus [Windows Forms], adding menu items" +ms.assetid: 1ec14776-3ea2-4752-bd22-4fae0fd19e1a +--- +# How to: Add Menu Items to a ContextMenuStrip +You can add just one menu item or several items at a time to a . + +### To add a single menu item to a ContextMenuStrip + +- Use the method to add one menu item to a . + + ```vb + Me.contextMenuStrip1.Items.Add(Me.toolStripMenuItem1) + ``` + + ```csharp + this.contextMenuStrip1.Items.Add(toolStripMenuItem1); + ``` + +### To add several menu items to a ContextMenuStrip + +- Use the method to add several menu items to a . + + ```vb + Me.contextMenuStrip1.Items.AddRange(New _ + System.Windows.Forms.ToolStripItem() {Me.toolStripMenuItem1, _ + Me.toolStripMenuItem2}) + ``` + + ```csharp + this.contextMenuStrip1.Items.AddRange(new + System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem1, this.toolStripMenuItem2}); + ``` + +## See also + +- [ContextMenuStrip Control](contextmenustrip-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-or-remove-imagelist-images-with-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-or-remove-imagelist-images-with-the-designer.md new file mode 100644 index 0000000000..06a6f43ca5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-or-remove-imagelist-images-with-the-designer.md @@ -0,0 +1,36 @@ +--- +title: "How to: Add or Remove ImageList Images with the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ImageList component [Windows Forms], adding images" + - "ImageList component [Windows Forms], removing images" + - "images [Windows Forms], adding to ImageList component" +ms.assetid: 5699b244-e37c-4d20-bc35-7441e55c1e3a +--- +# How to: Add or Remove ImageList Images with the Designer + +You can add images to an component several different ways. You can add images very quickly by using the smart tag associated with the , or if you are setting several other properties on the , you may find it more convenient to add images with the Properties window. You can also add images by using code. For more information about how to add images with code, see [How to: Add or Remove Images with the Windows Forms ImageList Component](how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md). Typically you populate the component with images before it is associated with a control, but this is not required. + +### To add or remove images by using the Properties window + +1. Select the component, or add one to the form. + +2. In the Properties window, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property. + +3. In the **Image Collection Editor**, click **Add** or **Remove** to add or remove images from the list. + +### To add or remove images using the smart tag + +1. Select the component, or add one to the form. + +2. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) + +3. In the **ImageList Tasks** dialog box, select **Choose Images**. + +4. In the **Images Collection Editor** click **Add** or **Remove** to add or remove images from the list. + +## See also + +- [Images, Bitmaps, and Metafiles](../advanced/images-bitmaps-and-metafiles.md) +- [Walkthrough: Perform common tasks using designer actions](perform-common-tasks-design-actions.md) +- [ImageList Component](imagelist-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md new file mode 100644 index 0000000000..d464d8a601 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md @@ -0,0 +1,142 @@ +--- +title: Add or Remove Images with ImageList Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "images [Windows Forms], removing from ImageList component" + - "images [Windows Forms], storing for controls" + - "ImageList component [Windows Forms], adding images" + - "ImageList component [Windows Forms], removing images" + - "images [Windows Forms], adding to ImageList component" + - "images [Windows Forms], displaying with controls" +ms.assetid: c5eacc56-f769-4e2e-bfb7-f756620913db +--- +# How to: Add or Remove Images with the Windows Forms ImageList Component +The Windows Forms component is typically populated with images before it is associated with a control. However, you can add and remove images after associating the image list with a control. + +> [!NOTE] +> When you remove images, verify that the property of any associated controls is still valid. + +### To add images programmatically + +- Use the method of the image list's property. + + In the following code example, the path set for the location of the image is the **My Documents** folder. This location is used because you can assume that most computers that are running the Windows operating system will include this folder. Choosing this location also lets users who have minimal system access levels more safely run the application. The following code example requires that you have a form with an control already added. + + ```vb + Public Sub LoadImage() + Dim myImage As System.Drawing.Image = _ + Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Image.gif") + ImageList1.Images.Add(myImage) + End Sub + ``` + + ```csharp + public void addImage() + { + // Be sure that you use an appropriate escape sequence (such as the + // @) when specifying the location of the file. + System.Drawing.Image myImage = + Image.FromFile + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Image.gif"); + imageList1.Images.Add(myImage); + } + ``` + + ```cpp + public: + void addImage() + { + // Replace the bold image in the following sample + // with your own icon. + // Be sure that you use an appropriate escape sequence (such as + // \\) when specifying the location of the file. + System::Drawing::Image ^ myImage = + Image::FromFile(String::Concat( + System::Environment::GetFolderPath( + System::Environment::SpecialFolder::Personal), + "\\Image.gif")); + imageList1->Images->Add(myImage); + } + ``` + +### To add images with a key value. + +- Use one of the methods of the image list's property that takes a key value. + + In the following code example, the path set for the location of the image is the **My Documents** folder. This location is used because you can assume that most computers that are running the Windows operating system will include this folder. Choosing this location also lets users who have minimal system access levels more safely run the application. The following code example requires that you have a form with an control already added. + + ```vb + Public Sub LoadImage() + Dim myImage As System.Drawing.Image = _ + Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Image.gif") + ImageList1.Images.Add("myPhoto", myImage) + End Sub + ``` + +```csharp +public void addImage() +{ +// Be sure that you use an appropriate escape sequence (such as the +// @) when specifying the location of the file. + System.Drawing.Image myImage = + Image.FromFile + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Image.gif"); + imageList1.Images.Add("myPhoto", myImage); +} +``` + +### To remove all images programmatically + +- Use the method to remove a single image + + ,-or- + + Use the method to clear all images in the image list. + + ```vb + ' Removes the first image in the image list + ImageList1.Images.Remove(myImage) + ' Clears all images in the image list + ImageList1.Images.Clear() + ``` + +```csharp +// Removes the first image in the image list. +imageList1.Images.Remove(myImage); +// Clears all images in the image list. +imageList1.Images.Clear(); +``` + +### To remove images by key + +- Use the method to remove a single image by its key. + + ```vb + ' Removes the image named "myPhoto" from the list. + ImageList1.Images.RemoveByKey("myPhoto") + ``` + +```csharp +// Removes the image named "myPhoto" from the list. +imageList1.Images.RemoveByKey("myPhoto"); +``` + +## See also + +- [ImageList Component](imagelist-component-windows-forms.md) +- [ImageList Component Overview](imagelist-component-overview-windows-forms.md) +- [Images, Bitmaps, and Metafiles](../advanced/images-bitmaps-and-metafiles.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-panels-to-a-statusbar-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-panels-to-a-statusbar-control.md new file mode 100644 index 0000000000..10a1584fc3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-panels-to-a-statusbar-control.md @@ -0,0 +1,125 @@ +--- +title: "How to: Add Panels to a StatusBar Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "panels [Windows Forms], status bars" + - "status bars [Windows Forms], adding panels" + - "StatusBar control [Windows Forms], adding panels" +ms.assetid: 835e3902-288c-4c38-9d69-0696d8695009 +--- +# How to: Add Panels to a StatusBar Control +> [!IMPORTANT] +> The and controls replace and add functionality to the and controls; however, the and controls are retained for both backward compatibility and future use, if you choose. + + The programmable area within a [StatusBar Control](statusbar-control-windows-forms.md) control consists of instances of the class. These are added through additions to the class. + +### To add panels to a status bar + +1. In a procedure, create status-bar panels by adding them to the . Specify property settings for individual panels by using its index passed through the property. + + In the following code example, the path set for the location of the icon is the **My Documents** folder. This location is used because you can assume that most computers running the Windows operating system will include this folder. Choosing this location also allows users with minimal system access levels to safely run the application. The following example requires a form with a control already added. + + > [!NOTE] + > The is a zero-based collection, so code should proceed accordingly. + + ```vb + Public Sub CreateStatusBarPanels() + ' Create panels and set text property. + StatusBar1.Panels.Add("One") + StatusBar1.Panels.Add("Two") + StatusBar1.Panels.Add("Three") + ' Set properties of StatusBar panels. + ' Set AutoSize property of panels. + StatusBar1.Panels(0).AutoSize = StatusBarPanelAutoSize.Spring + StatusBar1.Panels(1).AutoSize = StatusBarPanelAutoSize.Contents + StatusBar1.Panels(2).AutoSize = StatusBarPanelAutoSize.Contents + ' Set BorderStyle property of panels. + StatusBar1.Panels(0).BorderStyle = StatusBarPanelBorderStyle.Raised + StatusBar1.Panels(1).BorderStyle = StatusBarPanelBorderStyle.Sunken + StatusBar1.Panels(2).BorderStyle = StatusBarPanelBorderStyle.Raised + ' Set Icon property of third panel. You should replace the bolded + ' icon in the sample below with an icon of your own choosing. + StatusBar1.Panels(2).Icon = New _ + System.Drawing.Icon(System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Icon.ico") + StatusBar1.ShowPanels = True + End Sub + ``` + + ```csharp + public void CreateStatusBarPanels() + { + // Create panels and set text property. + statusBar1.Panels.Add("One"); + statusBar1.Panels.Add("Two"); + statusBar1.Panels.Add("Three"); + // Set properties of StatusBar panels. + // Set AutoSize property of panels. + statusBar1.Panels[0].AutoSize = StatusBarPanelAutoSize.Spring; + statusBar1.Panels[1].AutoSize = StatusBarPanelAutoSize.Contents; + statusBar1.Panels[2].AutoSize = StatusBarPanelAutoSize.Contents; + // Set BorderStyle property of panels. + statusBar1.Panels[0].BorderStyle = + StatusBarPanelBorderStyle.Raised; + statusBar1.Panels[1].BorderStyle = StatusBarPanelBorderStyle.Sunken; + statusBar1.Panels[2].BorderStyle = StatusBarPanelBorderStyle.Raised; + // Set Icon property of third panel. You should replace the bolded + // icon in the sample below with an icon of your own choosing. + // Note the escape character used (@) when specifying the path. + statusBar1.Panels[2].Icon = + new System.Drawing.Icon (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + + @"\Icon.ico"); + statusBar1.ShowPanels = true; + } + ``` + + ```cpp + public: + void CreateStatusBarPanels() + { + // Create panels and set text property. + statusBar1->Panels->Add("One"); + statusBar1->Panels->Add("Two"); + statusBar1->Panels->Add("Three"); + // Set properties of StatusBar panels. + // Set AutoSize property of panels. + statusBar1->Panels[0]->AutoSize = + StatusBarPanelAutoSize::Spring; + statusBar1->Panels[1]->AutoSize = + StatusBarPanelAutoSize::Contents; + statusBar1->Panels[2]->AutoSize = + StatusBarPanelAutoSize::Contents; + // Set BorderStyle property of panels. + statusBar1->Panels[0]->BorderStyle = + StatusBarPanelBorderStyle::Raised; + statusBar1->Panels[1]->BorderStyle = + StatusBarPanelBorderStyle::Sunken; + statusBar1->Panels[2]->BorderStyle = + StatusBarPanelBorderStyle::Raised; + // Set Icon property of third panel. + // You should replace the bolded image + // in the sample below with an icon of your own choosing. + statusBar1->Panels[2]->Icon = + gcnew System::Drawing::Icon(String::Concat( + System::Environment::GetFolderPath( + System::Environment::SpecialFolder::Personal), + "\\Icon.ico")); + statusBar1->ShowPanels = true; + } + ``` + +## See also + +- +- +- [Collection Editor Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/xc4yyekt(v=vs.100)) +- [How to: Set the Size of Status-Bar Panels](how-to-set-the-size-of-status-bar-panels.md) +- [Walkthrough: Updating Status Bar Information at Run Time](walkthrough-updating-status-bar-information-at-run-time.md) +- [How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked](determine-which-panel-wf-statusbar-control-was-clicked.md) +- [StatusBar Control Overview](statusbar-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-search-capabilities-to-a-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-search-capabilities-to-a-listview-control.md new file mode 100644 index 0000000000..648213d08d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-search-capabilities-to-a-listview-control.md @@ -0,0 +1,51 @@ +--- +title: "How to: Add Search Capabilities to a ListView Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "lists [Windows Forms], enabling searching" + - "list views [Windows Forms], enabling searching" + - "ListView control [Windows Forms], adding search capabilities" + - "searching [Windows Forms], adding search capabilities to ListView control" +ms.assetid: 557782d9-b705-4bab-b496-9938afddac82 +--- +# How to: Add Search Capabilities to a ListView Control +Oftentimes when working with a large list of items in a control, you want to offer search capabilities to the user. The control offers this capability in two different ways: text matching and location searching. + + The method allows you to perform a text search on a in list or details view, given a search string and an optional starting and ending index. In contrast, the method allows you to find an item in a in icon or tile view, given a set of x- and y-coordinates and a direction to search. + +### To find an item using text + +1. Create a with the property set to or , and then populate the with items. + +2. Call the method, passing the text of the item you would like to find. + +3. The following code example demonstrates how to create a basic , populate it with items, and use text input from the user to find an item in the list. + + [!code-cpp[System.Windows.Forms.ListViewFindItems#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/form1.cpp#1)] + [!code-csharp[System.Windows.Forms.ListViewFindItems#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.ListViewFindItems#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/VB/form1.vb#1)] + +### To find an item using x- and y-coordinates + +1. Create a with the property set to or , and then populate the with items. + +2. Call the method, passing the desired x- and y-coordinates and the direction you would like to search. + +3. The following code example demonstrates how to create a basic icon , populate it with items, and capture the event to find the nearest item in the up direction. + + [!code-cpp[System.Windows.Forms.ListViewFindItems#2](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/form1.cpp#2)] + [!code-csharp[System.Windows.Forms.ListViewFindItems#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/CS/form1.cs#2)] + [!code-vb[System.Windows.Forms.ListViewFindItems#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/VB/form1.vb#2)] + +## See also + +- +- +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..85fc822b6f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md @@ -0,0 +1,96 @@ +--- +title: Add Tables and Columns to DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "columns [Windows Forms], adding to DataGrid control" + - "tables [Windows Forms], adding to DataGrid control" + - "DataGrid control [Windows Forms], adding tables and columns" +ms.assetid: 2fe661b9-aa06-49b9-a314-a0d3cbfdcb4d +--- +# How to: Add Tables and Columns to the Windows Forms DataGrid Control + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + +You can display data in the Windows Forms control in tables and columns by creating **DataGridTableStyle** objects and adding them to the **GridTableStylesCollection** object, which is accessed through the control's **TableStyles** property. Each table style displays the contents of whatever data table is specified in the **DataGridTableStyle** object's **MappingName** property. By default, a table style with no column styles specified will display all the columns within that data table. You can restrict which columns from the table appear by adding **DataGridColumnStyle** objects to the **GridColumnStylesCollection** object, which is accessed through the **GridColumnStyles** property of each **DataGridTableStyle** object. + +### To add a table and column to a DataGrid programmatically + +1. In order to display data in the table, you must first bind the control to a dataset. For more information, see [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md). + + > [!CAUTION] + > When programmatically specifying column styles, always create **DataGridColumnStyle** objects and add them to the **GridColumnStylesCollection** object before adding **DataGridTableStyle** objects to the **GridTableStylesCollection** object. When you add an empty **DataGridTableStyle** object to the collection, **DataGridColumnStyle** objects are automatically generated for you. Consequently, an exception will be thrown if you try to add new **DataGridColumnStyle** objects with duplicate **MappingName** values to the **GridColumnStylesCollection** object. + +2. Declare a new table style and set its mapping name. + + ```vb + Dim ts1 As New DataGridTableStyle() + ts1.MappingName = "Customers" + ``` + + ```csharp + DataGridTableStyle ts1 = new DataGridTableStyle(); + ts1.MappingName = "Customers"; + ``` + + ```cpp + DataGridTableStyle* ts1 = new DataGridTableStyle(); + ts1->MappingName = S"Customers"; + ``` + +3. Declare a new column style and set its mapping name and other properties. + + ```vb + Dim myDataCol As New DataGridBoolColumn() + myDataCol.HeaderText = "My New Column" + myDataCol.MappingName = "Current" + ``` + + ```csharp + DataGridBoolColumn myDataCol = new DataGridBoolColumn(); + myDataCol.HeaderText = "My New Column"; + myDataCol.MappingName = "Current"; + ``` + + ```cpp + DataGridBoolColumn^ myDataCol = gcnew DataGridBoolColumn(); + myDataCol->HeaderText = "My New Column"; + myDataCol->MappingName = "Current"; + ``` + +4. Call the **Add** method of the **GridColumnStylesCollection** object to add the column to the table style + + ```vb + ts1.GridColumnStyles.Add(myDataCol) + ``` + + ```csharp + ts1.GridColumnStyles.Add(myDataCol); + ``` + + ```cpp + ts1->GridColumnStyles->Add(myDataCol); + ``` + +5. Call the **Add** method of the **GridTableStylesCollection** object to add the table style to the data grid. + + ```vb + DataGrid1.TableStyles.Add(ts1) + ``` + + ```csharp + dataGrid1.TableStyles.Add(ts1); + ``` + + ```cpp + dataGrid1->TableStyles->Add(ts1); + ``` + +## See also + +- [DataGrid Control](datagrid-control-windows-forms.md) +- [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time.md new file mode 100644 index 0000000000..58b0c2bdc6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time.md @@ -0,0 +1,101 @@ +--- +title: "How to: Add to or Remove from a Collection of Controls at Run Time" +description: Learn how to add controls to and remove controls from any container control on your forms, such as the Panel or GroupBox control, or even the form itself. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "run time [Windows Forms], removing controls" + - "controls [Windows Forms], adding using collections" + - "controls collections" + - "collections [Windows Forms], adding items" + - "run time [Windows Forms], adding controls" + - "controls [Windows Forms], removing using collections" +ms.assetid: 771bf895-3d5f-469b-a324-3528f343657e +--- +# How to: Add to or Remove from a Collection of Controls at Run Time +Common tasks in application development are adding controls to and removing controls from any container control on your forms (such as the or control, or even the form itself). At design time, controls can be dragged directly onto a panel or group box. At run time, these controls maintain a `Controls` collection, which keeps track of what controls are placed on them. + +> [!NOTE] +> The following code example applies to any control that maintains a collection of controls within it. + +### To add a control to a collection programmatically + +1. Create an instance of the control to be added. + +2. Set properties of the new control. + +3. Add the control to the `Controls` collection of the parent control. + + The following code example shows how to create an instance of the control. It requires a form with a control and that the event-handling method for the button being created, `NewPanelButton_Click`, already exists. + + ```vb + Public NewPanelButton As New Button() + + Public Sub AddNewControl() + ' The Add method will accept as a parameter any object that derives + ' from the Control class. In this case, it is a Button control. + Panel1.Controls.Add(NewPanelButton) + ' The event handler indicated for the Click event in the code + ' below is used as an example. Substite the appropriate event + ' handler for your application. + AddHandler NewPanelButton.Click, AddressOf NewPanelButton_Click + End Sub + ``` + + ```csharp + public Button newPanelButton = new Button(); + + public void addNewControl() + { + // The Add method will accept as a parameter any object that derives + // from the Control class. In this case, it is a Button control. + panel1.Controls.Add(newPanelButton); + // The event handler indicated for the Click event in the code + // below is used as an example. Substitute the appropriate event + // handler for your application. + this.newPanelButton.Click += new System.EventHandler(this. NewPanelButton_Click); + } + ``` + +### To remove controls from a collection programmatically + +1. Remove the event handler from the event. In Visual Basic, use the [RemoveHandler Statement](https://docs.microsoft.com/dotnet/visual-basic/language-reference/statements/removehandler-statement) keyword; in C#, use the [-= operator](https://docs.microsoft.com/dotnet/csharp/language-reference/operators/subtraction-operator). + +2. Use the `Remove` method to delete the desired control from the panel's `Controls` collection. + +3. Call the method to release all the resources used by the control. + + ```vb + Public Sub RemoveControl() + ' NOTE: The code below uses the instance of + ' the button (NewPanelButton) from the previous example. + If Panel1.Controls.Contains(NewPanelButton) Then + RemoveHandler NewPanelButton.Click, AddressOf _ + NewPanelButton_Click + Panel1.Controls.Remove(NewPanelButton) + NewPanelButton.Dispose() + End If + End Sub + ``` + + ```csharp + private void removeControl(object sender, System.EventArgs e) + { + // NOTE: The code below uses the instance of + // the button (newPanelButton) from the previous example. + if(panel1.Controls.Contains(newPanelButton)) + { + this.newPanelButton.Click -= new System.EventHandler(this. + NewPanelButton_Click); + panel1.Controls.Remove(newPanelButton); + newPanelButton.Dispose(); + } + } + ``` + +## See also + +- +- [Panel Control](panel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-toolstrip-items-dynamically.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-toolstrip-items-dynamically.md new file mode 100644 index 0000000000..9fd825f888 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-toolstrip-items-dynamically.md @@ -0,0 +1,39 @@ +--- +title: "How to: Add ToolStrip Items Dynamically" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ContextMenuStrip control [Windows Forms]" + - "toolbars [Windows Forms], adding items dynamically" + - "ToolStrip control [Windows Forms]" +ms.assetid: 0e8dea56-5f46-408b-914d-7e360341a234 +--- +# How to: Add ToolStrip Items Dynamically +You can dynamically populate the menu item collection of a control when the menu opens. + +## Example + The following code example demonstrates how to dynamically add items to a control. The example also shows how to reuse the same for three different controls on the form. + + In the example, an event handler populates the menu item collection. The event handler examines the and properties and adds a describing the source control. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#40](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#40)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#40](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#40)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-add-web-browser-capabilities-to-a-windows-forms-application.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-web-browser-capabilities-to-a-windows-forms-application.md new file mode 100644 index 0000000000..f0df137efb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-add-web-browser-capabilities-to-a-windows-forms-application.md @@ -0,0 +1,38 @@ +--- +title: Add web browser capabilities to app +description: Learn how to add web browser capabilities to a Windows Forms application with the WebBrowser control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "WebBrowser control [Windows Forms], adding Web browser capabilities to your application" + - "WebBrowser control [Windows Forms], examples" + - "Web browsers [.NET Framework], adding to Windows Forms" + - "examples [Windows Forms], WebBrowser control" + - "Windows Forms, adding Web browser functionality" +ms.assetid: 3871f072-b57a-435b-9976-e5da28df04a7 +--- +# How to add web browser capabilities to a Windows Forms application + +With the control, you can add Web browser functionality to your application. The control works like a Web browser by default. After you load an initial URL by setting the property, you can navigate by clicking hyperlinks or by using keyboard shortcuts to move backward and forward through navigation history. By default, you can access additional browser functionality through the right-click shortcut menu. You can also open new documents by dropping them onto the control. The control also has several properties, methods, and events that you can use to implement user interface features similar to those found in Internet Explorer. + +The following code example implements an address bar, typical browser buttons, a **File** menu, a status bar, and a title bar that displays the current page title. + +## Example + +[!code-cpp[System.Windows.Forms.WebBrowser#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CPP/form1.cpp#0)] +[!code-csharp[System.Windows.Forms.WebBrowser#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CS/form1.cs#0)] +[!code-vb[System.Windows.Forms.WebBrowser#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/VB/form1.vb#0)] + +## Compile the code + +This example requires: + +- References to the `System`, `System.Drawing`, and `System.Windows.Forms` assemblies. + +## See also + +- +- [WebBrowser Control](webbrowser-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-align-a-control-to-the-edges-of-forms-at-design-time.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-a-control-to-the-edges-of-forms-at-design-time.md new file mode 100644 index 0000000000..238c62a0c0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-a-control-to-the-edges-of-forms-at-design-time.md @@ -0,0 +1,47 @@ +--- +title: "How to: Align a Control to the Edges of Forms at Design Time" +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], docking using designer" + - "Dock property [Windows Forms], aligning controls (using designer)" +ms.assetid: 51f08998-5e3b-4330-be58-a4edd0eb60f4 +--- +# How to: Align a Control to the Edges of Forms at Design Time + +You can make your control align to the edge of your forms by setting the value of the property. This property designates where your control resides in the form. The property can be set to the following values: + +|Setting|Effect on your control| +|-------------|----------------------------| +||Docks to the bottom of the form.| +||Fills all remaining space in the form.| +||Docks to the left side of the form.| +||Does not dock anywhere, and it appears at the location specified by its .| +||Docks to the right side of the form.| +||Docks to the top of the form.| + +These values can also be set in code. For more information, see [How to: Align a Control to the Edges of Forms](how-to-align-a-control-to-the-edges-of-forms.md). + +## Set the Dock property for your control at design time + +1. In the Windows Forms Designer in Visual Studio, select your control. + +2. In the **Properties** window, click the drop-down box next to the property. + + A graphical interface representing the six possible settings is displayed. + +3. Choose the appropriate setting. + +4. Your control will now dock in the manner specified by the setting. + +## See also + +- +- +- [How to: Align a Control to the Edges of Forms](how-to-align-a-control-to-the-edges-of-forms.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) +- [How to: Anchor Controls on Windows Forms](how-to-anchor-controls-on-windows-forms.md) +- [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) +- [How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-align-a-control-to-the-edges-of-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-a-control-to-the-edges-of-forms.md new file mode 100644 index 0000000000..9372995676 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-a-control-to-the-edges-of-forms.md @@ -0,0 +1,54 @@ +--- +title: "How to: Align a Control to the Edges of Forms" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Dock property [Windows Forms], aligning controls (using code)" + - "forms [Windows Forms], aligning controls" + - "controls [Windows Forms], aligning on forms" + - "custom controls [Windows Forms], docking using code" +ms.assetid: 5994cb59-242b-4e75-bd0e-62879c34d702 +--- +# How to: Align a Control to the Edges of Forms + +You can make your control align to the edge of your forms by setting the property. This property designates where your control resides in the form. The property can be set to the following values: + +|Setting|Effect on your control| +|-------------|----------------------------| +||Docks to the bottom of the form.| +||Fills all remaining space in the form.| +||Docks to the left side of the form.| +||Does not dock anywhere, and it appears at the location specified by its property.| +||Docks to the right side of the form.| +||Docks to the top of the form.| + +There is design-time support for this feature in Visual Studio. + +## Set the Dock property for your control at run time + +Set the property to the appropriate value in code. + +```vb +' To set the Dock property internally. +Me.Dock = DockStyle.Top +' To set the Dock property from another object. +UserControl1.Dock = DockStyle.Top +``` + +```csharp +// To set the Dock property internally. +this.Dock = DockStyle.Top; +// To set the Dock property from another object. +UserControl1.Dock = DockStyle.Top; +``` + +## See also + +- +- +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md) +- [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) +- [AutoSize Property Overview](autosize-property-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md new file mode 100644 index 0000000000..52cbe07d66 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md @@ -0,0 +1,36 @@ +--- +title: "How to: Align and Stretch a Control in a TableLayoutPanel Control" +ms.date: "03/30/2017" +f1_keywords: + - "net.ComponentModel.StyleCollectionEditor.TLP.AlignStretchCtrl" +helpviewer_keywords: + - "TableLayoutPanel control [Windows Forms], stretching controls" + - "controls [Windows Forms], stretching" + - "controls [Windows Forms], aligning" +ms.assetid: 7dc1a157-6fee-4995-8ebc-b65bdc0909a8 +--- +# How to: Align and Stretch a Control in a TableLayoutPanel Control + +You can align and stretch controls in a with the and properties. + +## Align and stretch a control + +1. In Visual Studio, drag a control from the **Toolbox** onto your form. + +2. Drag a control from the **Toolbox** into the upper-left cell of the control. The control is centered in the cell. + +3. Set the value of the control's property to `Left,Right`. The control stretches to match the width of the cell. + +4. Set the value of the control's property to `Top,Bottom`. The control stretches to match the height of the cell. + +5. Set the value of the control's property to . The control expands to fill the cell. + +6. Set the value of the control's property to . The control returns to its original size and moves to the upper-left corner of the cell. The **Windows Forms Designer** has set the property to `Top, Left`. + +7. Set the value of the control's property to `Bottom,Right`. The control moves to the lower-right corner of the cell. + +8. Set the value of the control's property to . The control moves to the center of the cell. + +## See also + +- [TableLayoutPanel Control](tablelayoutpanel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-align-multiple-controls-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-multiple-controls-on-windows-forms.md new file mode 100644 index 0000000000..bce3044612 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-align-multiple-controls-on-windows-forms.md @@ -0,0 +1,37 @@ +--- +title: Align Multiple Controls +ms.date: 03/30/2017 +f1_keywords: + - Designer_Microsoft.VisualStudio.Windows.Forms.Design.DocumentDesigner +helpviewer_keywords: + - "forms [Windows Forms], aligning controls" + - "Windows Forms, aligning controls" + - "controls [Windows Forms], positioning" + - "controls [Windows Forms], aligning" +ms.assetid: b7175656-f532-49e9-b0b1-177d1b40af3e +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Align Multiple Controls on Windows Forms + +To standardize the layout of the user interface (UI) of your Windows-based application, you can position groups of controls with a single command. + +## To align multiple controls on a form + +1. In Visual Studio, open the form that contains the controls you want to position in the **Windows Forms Designer**. + +2. Select the controls you want to align. The first control you select is the primary control to which the others will be aligned. + +3. On the **Format** menu, select **Align**, and then select one of the seven choices available. + +## See also + +- [Windows Forms Controls](index.md) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [How to: Reassign Existing Controls to a Different Parent](how-to-reassign-existing-controls-to-a-different-parent.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md new file mode 100644 index 0000000000..b3e4e3bc6d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md @@ -0,0 +1,62 @@ +--- +title: "How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control" +description: Learn how to programmatically anchor and dock child controls in a Windows Forms FlowLayoutPanel control. +ms.date: "03/30/2017" +helpviewer_keywords: + - "layout [Windows Forms], child controls" + - "FlowLayoutPanel control [Windows Forms], child controls" + - "controls [Windows Forms], child" + - "child controls [Windows Forms], anchoring and docking" +ms.assetid: a2bcdfca-9b63-45e6-9c0e-3411015cba98 +--- +# How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control + +The control supports the and properties in its child controls. + +### To anchor and dock child controls in a FlowLayoutPanel control + +1. Create a control on your form. + +2. Set the of the control to **300**, and set its to . + +3. Create two controls, and place them in the control. + +4. Set the of the first button to **200**. + +5. Set the property of the second button to . + + > [!NOTE] + > The second button assumes the same width as the first button. It does not stretch across the width of the control. + +6. Set the property of the second button to `None`. This causes the button to assume its original width. + +7. Set the property of the second button to `Left, Right`. + + > [!IMPORTANT] + > The second button assumes the same width as the first button. It does not stretch across the width of the control. This is the general rule for anchoring and docking in the control: for vertical flow directions, the control calculates the width of an implied column from the widest child control in the column. All other controls in this column with or properties are aligned or stretched to fit this implied column. The behavior works in a similar way for horizontal flow directions. The control calculates the height of an implied row from the tallest child control in the row, and all docked or anchored child controls in this row are aligned or sized to fit the implied row. + +## Example + +The following illustration shows four buttons that are anchored and docked relative to the blue button in a . The is . + +![FlowLayoutPanel anchoring](./media/net-flpanchorexp.gif "NET_FLPanchorExp") + +The following illustration shows four buttons that are anchored and docked relative to the blue button in a . The is . + +![FlowLayoutPanel anchoring](./media/vs-flpanchor2.gif "VS_FLPanchor2") + +The following code example demonstrates various property values for a control in a control. + +[!code-csharp[System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/CS/FlpAnchorExampleForm.cs#1)] +[!code-vb[System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/VB/FlpAnchorExampleForm.vb#1)] + +## Compiling the Code + +This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- [FlowLayoutPanel Control Overview](flowlayoutpanel-control-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md new file mode 100644 index 0000000000..6f8db93e06 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md @@ -0,0 +1,82 @@ +--- +title: "How to: Anchor and Dock Child Controls in a TableLayoutPanel Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "net.ComponentModel.StyleCollectionEditor.TLP.AnchorDock" +helpviewer_keywords: + - "layout [Windows Forms], child controls" + - "controls [Windows Forms], child" + - "child controls [Windows Forms], anchoring and docking" + - "TableLayoutPanel control [Windows Forms], child controls" +ms.assetid: 0d267c35-25f1-49b8-8976-c64e8f0ddc0b +--- +# How to: Anchor and Dock Child Controls in a TableLayoutPanel Control +The control supports the and properties in its child controls. + +### To align a child control in a TableLayoutPanel cell + +1. Create a control on your form. + +2. Set the value of the control's and properties to **1**. + +3. Create a control in the control. The occupies the upper-left corner of the cell. + +4. Change the value of the control's property to `Left`. The control moves to align with the left border of the cell. + + > [!NOTE] + > This behavior differs from the behavior of other container controls. In other container controls, the child control does not move when the property is set, and the distance between the anchored control and the parent container's boundary is fixed at the time the property is set. + +5. Change the value of the control's property to `Top, Left`. The control moves to occupy the top-left corner of the cell. + +6. Repeat step 5 with a value of `Top, Right` to move the control to the top-right corner of the cell. Repeat with values of `Bottom, Left` and `Bottom, Right`. + +### To stretch a child control in a TableLayoutPanel cell + +1. Change the value of the control's property to `Left, Right`. The control is resized to stretch across the cell. + + > [!NOTE] + > This behavior differs from the behavior of other container controls. In other container controls, the child control is not resized when the property is set to `Left, Right` or `Top, Bottom`. + +2. Change the value of the control's property to `Top, Bottom`. The control is resized to stretch from the top to the bottom of the cell. + +3. Change the value of the control's property to `Top, Bottom, Left, Right`. The control is resized to fill the cell. + +4. Change the value of the control's property to `None`. The control is resized and centered in the cell. + +5. Change the value of the control's property to . The control moves to align with the left border of the cell. The control retains its width, but its height is resized to fill the cell vertically. + + > [!NOTE] + > This is the same behavior that occurs in other container controls. + +6. Change the value of the control's property to . The control is resized to fill the cell. + +## Example + The following illustration shows five buttons anchored in five separate cells. + + ![TableLayoutPanel Anchoring](./media/vs-tlpanchor.gif "VS_TLPanchor") + + The following illustration shows four buttons anchored in the corners of four separate cells. + + ![TableLayoutPanel Anchoring](./media/vs-tlpanchor2.gif "VS_TLPanchor2") + + The following illustration shows three buttons stretched by anchoring in three separate cells. + + ![TableLayoutPanel Anchoring](./media/vs-tlpanchor3.gif "VS_TLPAnchor3") + + The following code example demonstrates all the combinations of property values for a control in a control. + + [!code-csharp[System.Windows.Forms.TableLayoutPanel.AnchorExampleForm#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/CS/TlpAnchorExampleForm.cs#1)] + [!code-vb[System.Windows.Forms.TableLayoutPanel.AnchorExampleForm#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/VB/TlpAnchorExampleForm.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- [TableLayoutPanel Control](tablelayoutpanel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-controls-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-controls-on-windows-forms.md new file mode 100644 index 0000000000..74ff9a5494 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-anchor-controls-on-windows-forms.md @@ -0,0 +1,58 @@ +--- +title: Anchor Controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "Anchor property [Windows Forms], enabling resizable forms" + - "Windows Forms controls, screen resolutions" + - "resizing forms [Windows Forms]" + - "Windows Forms controls, size" + - "screen resolution and control display" + - "controls [Windows Forms], anchoring" + - "forms [Windows Forms], resizing" + - "Windows Forms, resizing" + - "controls [Windows Forms], positioning" +ms.assetid: 59ea914f-fbd3-427a-80fe-decd02f7ae6d +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Anchor controls on Windows Forms + +If you're designing a form that the user can resize at run time, the controls on your form should resize and reposition properly. To resize controls dynamically with the form, you can use the property of Windows Forms controls. The property defines an anchor position for the control. When a control is anchored to a form and the form is resized, the control maintains the distance between the control and the anchor positions. For example, if you have a control that is anchored to the left, right, and bottom edges of the form, as the form is resized, the control resizes horizontally so that it maintains the same distance from the right and left sides of the form. In addition, the control positions itself vertically so that its location is always the same distance from the bottom edge of the form. If a control is not anchored and the form is resized, the position of the control relative to the edges of the form is changed. + +The property interacts with the property. For more information, see [AutoSize Property Overview](autosize-property-overview.md). + +## Anchor a control on a form + +1. In Visual Studio, select the control you want to anchor. + + > [!NOTE] + > You can anchor multiple controls simultaneously by pressing the CTRL key, clicking each control to select it, and then following the rest of this procedure. + +2. In the **Properties** window, click the arrow to the right of the property. + + An editor is displayed that shows a cross. + +3. To set an anchor, click the top, left, right, or bottom section of the cross. + + Controls are anchored to the top and left by default. + +4. To clear a side of the control that has been anchored, click that arm of the cross. + +5. To close the property editor, click the property name again. + +When your form is displayed at run time, the control resizes to remain positioned at the same distance from the edge of the form. The distance from the anchored edge always remains the same as the distance defined when the control is positioned in the Windows Forms Designer. + +> [!NOTE] +> Certain controls, such as the control, have a limit to their height. Anchoring the control to the bottom of its form or container cannot force the control to exceed its height limit. + +Inherited controls must be `Protected` to be able to be anchored. To change the access level of a control, set its `Modifiers` property in the **Properties** window. + +## See also + +- [Windows Forms Controls](index.md) +- [AutoSize Property Overview](autosize-property-overview.md) +- [How to: Dock Controls on Windows Forms](how-to-dock-controls-on-windows-forms.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-append-a-menustrip-to-an-mdi-parent-window-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-append-a-menustrip-to-an-mdi-parent-window-windows-forms.md new file mode 100644 index 0000000000..d6e82bab9a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-append-a-menustrip-to-an-mdi-parent-window-windows-forms.md @@ -0,0 +1,83 @@ +--- +title: "How to: Append a MenuStrip to an MDI Parent Window" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "MenuStrip control [Windows Forms], merging" + - "MenuStrip control [Windows Forms], appending" + - "MDI [Windows Forms], merging menu items" +ms.assetid: ab70c936-b452-4653-b417-17be57bb795b +--- +# How to: Append a MenuStrip to an MDI Parent Window (Windows Forms) +In some applications, the kind of a multiple-document interface (MDI) child window can be different from the MDI parent window. For example, the MDI parent might be a spreadsheet, and the MDI child might be a chart. In that case, you want to update the contents of the MDI parent's menu with the contents of the MDI child's menu as MDI child windows of different kinds are activated. + + The following procedure uses the , , , and properties to append the MDI child menu to the MDI parent menu. Closing the MDI child window removes the appended menu from the MDI parent. + + Also see [Multiple-Document Interface (MDI) Applications](../advanced/multiple-document-interface-mdi-applications.md). + +### To append a menu item to an MDI parent + +1. Create a form and set its property to `true`. + +2. Add a to `Form1` and set the property of the to `true`. + +3. Set the property of the `Form1` to `false`. + +4. Add a top-level menu item to the `Form1` and set its property to `&File`. + +5. Add a submenu item to the `&File` menu item and set its property to `&Open`. + +6. Add a form to the project, add a to the form, and set the property of the `Form2` to `true`. + +7. Add a top-level menu item to the `Form2` and set its property to `&Special`. + +8. Add two submenu items to the `&Special` menu item and set their properties to `Command&1` and `Command&2`, respectively. + +9. Set the property of the `&Special`, `Command&1`, and `Command&2` menu items to . + +10. Create an event handler for the event of the `&Open` . + +11. Within the event handler, insert code similar to the following code example to create and display new instances of `Form2` as MDI children of `Form1`. + + ```vb + Private Sub openToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles openToolStripMenuItem.Click + Dim NewMDIChild As New Form2() + 'Set the parent form of the child window. + NewMDIChild.MdiParent = Me + 'Display the new form. + NewMDIChild.Show() + End Sub + ``` + + ```csharp + private void openToolStripMenuItem_Click(object sender, EventArgs e) + { + Form2 newMDIChild = new Form2(); + // Set the parent form of the child window. + newMDIChild.MdiParent = this; + // Display the new form. + newMDIChild.Show(); + } + ``` + +12. Place code similar to the following code example in the `&Open` to register the event handler. + + ```vb + Private Sub openToolStripMenuItem_Click(sender As Object, e As _ + EventArgs) Handles openToolStripMenuItem.Click + ``` + + ```csharp + this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); + ``` + +## Compiling the Code + This example requires: + +- Two controls named `Form1` and `Form2`. + +- A control on `Form1` named `menuStrip1`, and a control on `Form2` named `menuStrip2`. + +- References to the and assemblies. diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-apply-attributes-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-apply-attributes-in-windows-forms-controls.md new file mode 100644 index 0000000000..8ce32035a1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-apply-attributes-in-windows-forms-controls.md @@ -0,0 +1,80 @@ +--- +title: Apply Attributes in Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], applying attributes" + - "attributes [Windows Forms], applying" + - "Windows Forms controls, applying attributes" +ms.assetid: af0a3f7f-155b-4ba1-83c4-9cf721331a06 +--- +# How to: Apply Attributes in Windows Forms Controls +To develop components and controls that interact correctly with the design environment and execute correctly at run time, you need to apply attributes correctly to classes and members. + +## Example + The following code example demonstrates how to use several attributes on a custom control. The control demonstrates a simple logging capability. When the control is bound to a data source, it displays the values sent by the data source in a control. If a value exceeds the value specified by the `Threshold` property, a `ThresholdExceeded` event is raised. + + The `AttributesDemoControl` logs values with a `LogEntry` class. The `LogEntry` class is a template class, which means it is parameterized on the type that it logs. For example, if the `AttributesDemoControl` is logging values of type `float`, each `LogEntry` instance is declared and used as follows. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#110](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/form1.cs#110)] + [!code-vb[System.ComponentModel.AttributesDemoControl#110](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/form1.vb#110)] + +> [!NOTE] +> Because `LogEntry` is parameterized by an arbitrary type, it must use reflection to operate on the parameter type. For the threshold feature to work, the parameter type `T` must implement the interface. + + The form that hosts the `AttributesDemoControl` queries a performance counter periodically. Each value is packaged in a `LogEntry` of the appropriate type and added to the form's . The `AttributesDemoControl` receives the value through its data binding and displays the value in a control. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#1)] + [!code-vb[System.ComponentModel.AttributesDemoControl#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#1)] + + [!code-csharp[System.ComponentModel.AttributesDemoControl#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/form1.cs#100)] + [!code-vb[System.ComponentModel.AttributesDemoControl#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/form1.vb#100)] + + The first code example is the `AttributesDemoControl` implementation. The second code example demonstrates a form that uses the `AttributesDemoControl`. + +## Class-level Attributes + Some attributes are applied at the class level. The following code example shows the attributes that are commonly applied to a Windows Forms control. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#20)] + [!code-vb[System.ComponentModel.AttributesDemoControl#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#20)] + +### TypeConverter Attribute + is another commonly used class-level attribute. The following code example shows its use for the `LogEntry` class. This example also shows an implementation of a for the `LogEntry` type, called `LogEntryTypeConverter`. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#5)] + [!code-vb[System.ComponentModel.AttributesDemoControl#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#5)] + +## Member-level Attributes + Some attributes are applied at the member level. The following code examples show some attributes that are commonly applied to properties of Windows Forms controls. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#21)] + [!code-vb[System.ComponentModel.AttributesDemoControl#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#21)] + +### AmbientValue Attribute + The following example demonstrates the and shows code that supports its interaction with the design environment. This interaction is called *ambience*. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#23)] + [!code-vb[System.ComponentModel.AttributesDemoControl#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#23)] + +### Databinding Attributes + The following examples demonstrate an implementation of complex data binding. The class-level , shown previously, specifies the `DataSource` and `DataMember` properties to use for data binding. The specifies the type to which the `DataSource` property will bind. + + [!code-csharp[System.ComponentModel.AttributesDemoControl#25](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#25)] + [!code-vb[System.ComponentModel.AttributesDemoControl#25](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#25)] + + [!code-csharp[System.ComponentModel.AttributesDemoControl#26](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs#26)] + [!code-vb[System.ComponentModel.AttributesDemoControl#26](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb#26)] + +## Compiling the Code + +- The form that hosts the `AttributesDemoControl` requires a reference to the `AttributesDemoControl` assembly in order to build. + +## See also + +- +- +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [Attributes in Windows Forms Controls](attributes-in-windows-forms-controls.md) +- [How to: Serialize Collections of Standard Types with the DesignerSerializationVisibilityAttribute](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/ms171833(v=vs.120)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-associate-a-contextmenustrip-with-a-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-associate-a-contextmenustrip-with-a-control.md new file mode 100644 index 0000000000..72b17fa2f1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-associate-a-contextmenustrip-with-a-control.md @@ -0,0 +1,42 @@ +--- +title: "How to: Associate a ContextMenuStrip with a Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "context menus [Windows Forms], relating" + - "ContextMenuStrips [Windows Forms], associating with controls" + - "context menus [Windows Forms], associating with controls" + - "ContextMenuStrips [Windows Forms], relating" +ms.assetid: 6fc40a42-5d69-427f-aa30-0a146193226b +--- +# How to: Associate a ContextMenuStrip with a Control +After creating your controls and shortcut menus, use the following procedures to display a given shortcut menu when the user right-clicks the control. These procedures associate a with a Windows Form and with a control. + +### To associate a ContextMenuStrip with a Windows Form + +1. Set the property to the name of the associated . + +### To associate a ContextMenuStrip with a ToolStrip control + +1. Set the control's property to the name of the associated . + +## Example + The following code example creates a Windows Form and a , and associates a different control with each of them. + + [!code-csharp[System.Windows.Forms.ContextMenuStrip#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.ContextMenuStrip#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [How to: Add Menu Items to a ContextMenuStrip](how-to-add-menu-items-to-a-contextmenustrip.md) +- [ContextMenuStrip Control](contextmenustrip-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-associate-a-shortcut-menu-with-a-windows-forms-notifyicon-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-associate-a-shortcut-menu-with-a-windows-forms-notifyicon-component.md new file mode 100644 index 0000000000..702809684f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-associate-a-shortcut-menu-with-a-windows-forms-notifyicon-component.md @@ -0,0 +1,129 @@ +--- +title: Associate a Shortcut Menu with NotifyIcon Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "context menus [Windows Forms], for background processes" + - "NotifyIcon component [Windows Forms], associating shortcut menus" + - "shortcut menus [Windows Forms], for background processes" +ms.assetid: d68f3926-08d3-4f7d-949f-1981b29cf188 +--- +# How to: Associate a Shortcut Menu with a Windows Forms NotifyIcon Component +> [!NOTE] +> Although and replace and add functionality to the and controls of previous versions, and are retained for both backward compatibility and future use if you choose. + + The component displays an icon in the status notification area of the taskbar. Commonly, applications enable you to right-click this icon to send commands to the application it represents. By associating a component with the component, you can add this functionality to your applications. + +> [!NOTE] +> If you want your application to be minimized at startup while displaying an instance of the component in the taskbar, set the main form's property to and be sure the component's property is set to `true`. + +### To associate a shortcut menu with the NotifyIcon component at design time + +1. Add a component to your form, and set the important properties, such as the and properties. + + For more information, see [How to: Add Application Icons to the TaskBar with the Windows Forms NotifyIcon Component](app-icons-to-the-taskbar-with-wf-notifyicon.md). + +2. Add a component to your Windows Form. + + Add menu items to the shortcut menu representing the commands you want to make available at run time. This is also a good time to add menu enhancements to these menu items, such as access keys. + +3. Set the property of the component to the shortcut menu that you added. + + With this property set, the shortcut menu will be displayed when the icon on the taskbar is clicked. + +### To associate a shortcut menu with the NotifyIcon component programmatically + +1. Create an instance of the class and a class, with whatever property settings are necessary for the application ( and properties for the component, menu items for the component). + +2. Set the property of the component to the shortcut menu that you added. + + With this property set, the shortcut menu will be displayed when the icon on the taskbar is clicked. + + > [!NOTE] + > The following code example creates a basic menu structure. You will need to customize the menu choices to those that fit the application you are developing. Additionally, you will want to write code to handle the events for these menu items. + + ```vb + Public ContextMenu1 As New ContextMenu + Public NotifyIcon1 As New NotifyIcon + + Public Sub CreateIconMenuStructure() + ' Add menu items to shortcut menu. + ContextMenu1.MenuItems.Add("&Open Application") + ContextMenu1.MenuItems.Add("S&uspend Application") + ContextMenu1.MenuItems.Add("E&xit") + + ' Set properties of NotifyIcon component. + NotifyIcon1.Icon = New System.Drawing.Icon _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Icon.ico") + NotifyIcon1.Text = "Right-click me!" + NotifyIcon1.Visible = True + NotifyIcon1.ContextMenu = ContextMenu1 + End Sub + ``` + +```csharp +public NotifyIcon notifyIcon1 = new NotifyIcon(); +public ContextMenu contextMenu1 = new ContextMenu(); + +public void createIconMenuStructure() +{ + // Add menu items to shortcut menu. + contextMenu1.MenuItems.Add("&Open Application"); + contextMenu1.MenuItems.Add("S&uspend Application"); + contextMenu1.MenuItems.Add("E&xit"); + + // Set properties of NotifyIcon component. + notifyIcon1.Icon = new System.Drawing.Icon + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Icon.ico"); + notifyIcon1.Visible = true; + notifyIcon1.Text = "Right-click me!"; + notifyIcon1.Visible = true; + notifyIcon1.ContextMenu = contextMenu1; +} +``` + +```cpp +public: + System::Windows::Forms::NotifyIcon ^ notifyIcon1; + System::Windows::Forms::ContextMenu ^ contextMenu1; + + void createIconMenuStructure() + { + // Add menu items to shortcut menu. + contextMenu1->MenuItems->Add("&Open Application"); + contextMenu1->MenuItems->Add("S&uspend Application"); + contextMenu1->MenuItems->Add("E&xit"); + + // Set properties of NotifyIcon component. + notifyIcon1->Icon = gcnew System::Drawing::Icon + (String::Concat(System::Environment::GetFolderPath + (System::Environment::SpecialFolder::Personal), + "\\Icon.ico")); + notifyIcon1->Text = "Right-click me!"; + notifyIcon1->Visible = true; + notifyIcon1->ContextMenu = contextMenu1; + } +``` + +> [!NOTE] +> You must initialize `notifyIcon1` and `contextMenu1,` which you can do by including the following statements in the constructor of your form: + +```cpp +notifyIcon1 = gcnew System::Windows::Forms::NotifyIcon(); +contextMenu1 = gcnew System::Windows::Forms::ContextMenu(); +``` + +## See also + +- +- +- [How to: Add Application Icons to the TaskBar with the Windows Forms NotifyIcon Component](app-icons-to-the-taskbar-with-wf-notifyicon.md) +- [NotifyIcon Component](notifyicon-component-windows-forms.md) +- [NotifyIcon Component Overview](notifyicon-component-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-attach-a-shortcut-menu-to-a-treenode-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-attach-a-shortcut-menu-to-a-treenode-using-the-designer.md new file mode 100644 index 0000000000..b3daef8b7e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-attach-a-shortcut-menu-to-a-treenode-using-the-designer.md @@ -0,0 +1,28 @@ +--- +title: "How to: Attach a Shortcut Menu to a TreeNode Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "shortcut menus [Windows Forms], attaching to TreeNodes" + - "TreeNode [Windows Forms], attaching a shortcut menu using Designer" +ms.assetid: 8e45e184-1313-4f8f-90ff-2cd5789b2268 +--- +# How to: Attach a Shortcut Menu to a TreeNode Using the Designer +The Windows Forms control displays a hierarchy of nodes, similar to the files and folders displayed in the left pane of the Windows Explorer feature in Windows operating systems. By setting the property, you can provide context-sensitive operations to the user when they right-click the control. By associating a component with individual items, you can add a customized level of shortcut menu functionality to your controls. + +## To associate a shortcut menu with a TreeNode at design time + +1. Add a control to your form, and then add nodes to the as needed. For more information, see [How to: Add and Remove Nodes with the Windows Forms TreeView Control](how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md). + +2. Add a component to your form, and then add menu items to the shortcut menu that represent node-level operations you wish to make available at run time. For more information, see [How to: Add Menu Items to a ContextMenuStrip](how-to-add-menu-items-to-a-contextmenustrip.md). + +3. Reopen the **TreeNodeEditor** dialog box for the control, select the node to edit, and set its property to the shortcut menu that you added. + +4. When this property is set, the shortcut menu will be displayed when you right-click the node. + + Additionally, you will want to write code to handle the events for these menu items. + +## See also + +- [TreeView Control](treeview-control-windows-forms.md) +- [TreeView Control Overview](treeview-control-overview-windows-forms.md) +- [ContextMenuStrip Control](contextmenustrip-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-attach-a-shortcut-menu-to-a-treeview-node.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-attach-a-shortcut-menu-to-a-treeview-node.md new file mode 100644 index 0000000000..25f115d99e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-attach-a-shortcut-menu-to-a-treeview-node.md @@ -0,0 +1,36 @@ +--- +title: "How to: Attach a ShortCut Menu to a TreeView Node" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "shortcut menus [Windows Forms], adding to TreeView controls" + - "TreeView control [Windows Forms], adding shortcut menus" + - "tree nodes in TreeView control [Windows Forms], shortcut menus" +ms.assetid: a23c6752-fd8f-44ad-b781-bab37962fc7c +--- +# How to: Attach a ShortCut Menu to a TreeView Node +The Windows Forms control displays a hierarchy of nodes, similar to the files and folders displayed in the left pane of Windows Explorer. By setting the property, you can provide context-sensitive operations to the user when they right-click the control. By associating a component with individual items, you can add a customized level of shortcut menu functionality to your controls. + +### To associate a shortcut menu with a TreeNode programmatically + +1. Instantiate a control with the appropriate property settings, create a root , and then add subnodes. + +2. Instantiate a component, and then add a for each operation you want to make available at run time. + +3. Set the property of the appropriate to the shortcut menu you create. + +4. When this property is set, the shortcut menu will be displayed when you right-click the node. + + The following code example creates a basic and associated with the root of the . You will need to customize the menu choices to those that fit the you are developing. Additionally, you will want to write code to handle the events for these menu items. + + [!code-cpp[System.Windows.Forms.TreeNodeContextMenuStrip#1](~/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/Form1.cpp#1)] + [!code-csharp[System.Windows.Forms.TreeNodeContextMenuStrip#1](~/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.TreeNodeContextMenuStrip#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/VB/Form1.vb#1)] + +## See also + +- +- [TreeView Control](treeview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-author-composite-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-author-composite-controls.md new file mode 100644 index 0000000000..1e26100fa6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-author-composite-controls.md @@ -0,0 +1,80 @@ +--- +title: "How to: Author Composite Controls" +ms.date: "03/30/2017" +helpviewer_keywords: + - "UserControl class [Windows Forms], creating composite controls" + - "user controls [Windows Forms], creating" + - "user controls [Windows Forms], inheriting from" + - "composite controls [Windows Forms], creating" +ms.assetid: 79c9cf05-5ab6-4a18-886d-88a64748b098 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Author composite controls + +Composite controls can be employed in many ways. You can author them as part of a Windows desktop application project, and use them only on forms in the project. Or you can author them in a Windows Control Library project, compile the project into an assembly, and use the controls in other projects. You can even inherit from them and use visual inheritance to customize them quickly for special purposes. + +## To author a composite control + +1. In Visual Studio, create a new **Windows Application** project, and name it **DemoControlHost**. + +2. On the **Project** menu, click **Add User Control**. + +3. In the **Add New Item** dialog box, give the class file (.vb or .cs file) the name you want the composite control to have. + +4. Select the **Add** button to create the class file for the composite control. + +5. Add controls from the **Toolbox** to the composite control surface. + +6. Place code in event procedures, to handle events raised by the composite control or by its constituent controls. + +7. Close the designer for the composite control, and save the file when you are prompted. + +8. On the **Build** menu, click **Build Solution**. + + The project must be built in order for custom controls to appear in the **Toolbox**. + +9. Use the **DemoControlHost** tab of the **Toolbox** to add instances of your control to `Form1`. + +## To author a control class library + +1. Open a new **Windows Control Library** project. + + By default, the project contains a composite control. + +2. Add controls and code as described in the procedure above. + +3. Choose a control you do not want inheriting classes to change, and set the **Modifiers** property of this control to **Private**. + +4. Build the DLL. + +## To inherit from a composite control in a control class library + +1. On the **File** menu, point to **Add** and select **New Project** to add a new **Windows Application** project to the solution. + +2. In **Solution Explorer**, right-click the **References** folder for the new project and choose **Add Reference** to open the **Add Reference** dialog box. + +3. Select the **Projects** tab and double-click your control library project. + +4. On the **Build** menu, click **Build Solution**. + +5. In **Solution Explorer**, right-click your control library project and select **Add New Item** from the shortcut menu. + +6. Select the **Inherited User Control** template from the **Add New Item** dialog box. + +7. In the **Inheritance Picker** dialog box, double-click the control you want to inherit from. + + A new control is added to your project. + +8. Open the visual designer for the new control and add additional constituent controls. + + You can see the constituent controls that were inherited from the composite control in your DLL, and you can alter the properties of controls whose **Modifiers** property is **Public**. You cannot change the properties of the control whose **Modifiers** property is **Private**. + +## See also + +- [Walkthrough: Authoring a Composite Control](walkthrough-authoring-a-composite-control-with-visual-csharp.md) +- [Walkthrough: Inheriting from a Windows Forms Control](walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md) +- [Control Type Recommendations](control-type-recommendations.md) +- [How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-author-controls-for-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-author-controls-for-windows-forms.md new file mode 100644 index 0000000000..796c81fb38 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-author-controls-for-windows-forms.md @@ -0,0 +1,53 @@ +--- +title: "How to: Author Controls" +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], creating" + - "UserControl class [Windows Forms], Windows Forms" + - "custom controls [Windows Forms], creating" +ms.assetid: 7570e982-545b-4c3a-a7c7-55581d313400 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Author controls for Windows Forms + +A control represents a graphical link between the user and the program. A control can provide or process data, accept user input, respond to events, or perform any number of other functions that connect the user and the application. Because a control is essentially a component with a graphical interface, it can serve any function that a component does, as well as provide user interaction. Controls are created to serve specific purposes, and authoring controls is just another programming task. With that in mind, the following steps represent an overview of the control authoring process. Links provide additional information on the individual steps. + +## To author a control + +1. Determine what you want your control to accomplish, or what part it will play in your application. Factors to consider are: + + - What kind of graphical interface do you need? + + - What specific user interactions will this control handle? + + - Is the functionality you need provided by any existing controls? + + - Can you get the functionality you need by combining several Windows Forms controls? + +2. If you need an object model for your control, determine how functionality will be distributed throughout the object model, and divide up functionality between the control and any subobjects. An object model may be useful if you are planning a complex control, or want to incorporate several functionalities. + +3. Determine the type of control (for example, user control, custom control, inherited Windows Forms control) you need. For details, see [Control Type Recommendations](control-type-recommendations.md) and [Varieties of Custom Controls](varieties-of-custom-controls.md). + +4. Express functionality as properties, methods, and events of the control and its subobjects or subsidiary structures, and assign appropriate access levels (for example, public, protected, and so on). + +5. If you need custom painting for your control, add code for it. For details, see [Custom Control Painting and Rendering](custom-control-painting-and-rendering.md). + +6. If your control inherits from , you can test its runtime behavior by building the control project and running it in the **UserControl Test Container**. For more information, see [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md). + +7. You can also test and debug your control by creating a new project, such as a Windows Application, and placing it into a container. This process is demonstrated as part of [Walkthrough: Authoring a Composite Control](walkthrough-authoring-a-composite-control-with-visual-csharp.md). + +8. As you add each feature, add features to your test project to exercise the new functionality. + +9. Repeat, refining the design. + +10. Package and deploy your control. For details, see [First look at deployment in Visual Studio](/visualstudio/deployment/deploying-applications-services-and-components). + +## See also + +- [How to: Inherit from the UserControl Class](how-to-inherit-from-the-usercontrol-class.md) +- [How to: Inherit from the Control Class](how-to-inherit-from-the-control-class.md) +- [How to: Inherit from Existing Windows Forms Controls](how-to-inherit-from-existing-windows-forms-controls.md) +- [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md new file mode 100644 index 0000000000..77ffabbb87 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md @@ -0,0 +1,57 @@ +--- +title: Bind ComboBox or ListBox Control to Data +description: Learn how to bind the Windows Forms ComboBox and ListBox to data to perform tasks like browsing data in a database, entering new data, or editing existing data. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data [Windows Forms], binding to controls" + - "list boxes [Windows Forms], data binding" + - "ComboBox control [Windows Forms], data binding" + - "data binding [Windows Forms], combo boxes" + - "ListBox control [Windows Forms], data binding" + - "combo boxes [Windows Forms], data binding" + - "bound controls [Windows Forms], combo boxes" + - "Windows Forms controls, data binding" + - "data-bound controls [Windows Forms], Windows Forms" +ms.assetid: dfd7f081-8bea-4a41-86a3-86a1934828ef +--- +# How to: Bind a Windows Forms ComboBox or ListBox Control to Data +You can bind the and to data to perform tasks such as browsing data in a database, entering new data, or editing existing data. + +### To bind a ComboBox or ListBox control + +1. Set the `DataSource` property to a data source object. Possible data sources include a bound to data, a data table, a data view, a dataset, a data view manager, an array, or any class that implements the interface. For more information, see [Data Sources Supported by Windows Forms](../data-sources-supported-by-windows-forms.md). + +2. If you are binding to a table, set the `DisplayMember` property to the name of a column in the data source. + + \- or - + + If you are binding to an , set the display member to a public property of the type in the list. + + ```vb + Private Sub BindComboBox() + ComboBox1.DataSource = DataSet1.Tables("Suppliers") + ComboBox1.DisplayMember = "ProductName" + End Sub + ``` + + ```csharp + private void BindComboBox() + { + comboBox1.DataSource = dataSet1.Tables["Suppliers"]; + comboBox1.DisplayMember = "ProductName"; + } + ``` + + > [!NOTE] + > If you are bound to a data source that does not implement the interface, such as an , the bound control's data will not be updated when the data source is updated. For example, if you have a combo box bound to an and data is added to the , these new items will not appear in the combo box. However, you can force the combo box to be updated by calling the and methods on the instance of the class to which the control is bound. + +## See also + +- +- +- [Windows Forms Data Binding](../windows-forms-data-binding.md) +- [Data Binding and Windows Forms](../data-binding-and-windows-forms.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-factory-object.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-factory-object.md new file mode 100644 index 0000000000..91313e9da5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-factory-object.md @@ -0,0 +1,38 @@ +--- +title: Bind Control to a Factory Object +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "controls [Windows Forms], binding" + - "factory objects [Windows Forms], binding to" + - "BindingSource component [Windows Forms], binding to a factory object" + - "BindingSource component [Windows Forms], examples" +ms.assetid: 7d59af89-ff82-41d8-a48a-f1fbae788b0d +--- +# How to: Bind a Windows Forms Control to a Factory Object +When you are building controls that interact with data, you will sometimes find it necessary to bind a control to an object or method that generates other objects. Such an object or method is called a factory. Your data source might be, for example, the return value from a method call, instead of an object in memory or a type. You can bind a control to this kind of data source as long as the source returns a collection. + + You can easily bind a control to a factory object by using the control. + +## Example + The following example demonstrates how to bind a control to a factory method by using a control. The factory method is named `GetOrdersByCustomerId`, and it returns all the orders for a given customer in the Northwind database. + + [!code-cpp[System.Windows.Forms.DataConnector.BindToFactory#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CPP/form1.cpp#1)] + [!code-csharp[System.Windows.Forms.DataConnector.BindToFactory#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnector.BindToFactory#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-type-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-type-using-the-designer.md new file mode 100644 index 0000000000..5f9a1c8819 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-type-using-the-designer.md @@ -0,0 +1,53 @@ +--- +title: Bind Control to a Type Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], binding to a type" + - "BindingSource component [Windows Forms], binding to a type" + - "types [Windows Forms], binding controls to" +ms.assetid: 5ab984b5-c2d0-4638-a572-1c84013e8746 +--- +# How to: Bind a Windows Forms Control to a Type Using the Designer + +When you are building controls that interact with data, you sometimes need to bind a control to a type, rather than an object. You typically need to bind a control to a type at design time, when data may not be available, but you still want your data-bound controls to display data from a type's public interface. The following procedures demonstrate how to create a new that is bound to a type, and then how to bind one of the type's properties to the property of a . + +### To bind the BindingSource to a type + +1. Create a Windows Forms project (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. In **Design** view, drag a component onto the form. + +3. In the **Properties** window, click the arrow for the property. + +4. In the **DataSource UI Type Editor**, click **Add Project Data Source**. + +5. On the **Choose a Data Source Type** page, select **Object** and click **Next**. + +6. Select the type to bind to: + + - If the type you want to bind to is in the current project, or the assembly that contains the type is already added as a reference, expand the nodes to find the type you want, and then select it. + + \-or- + + - If the type you want to bind to is in another assembly, not currently in the list of references, click **Add Reference**, and then click the **Projects** tab. Select the project that contains the business object you want and click **OK**. This project will appear in the list of assemblies, so you can expand the nodes to find the type you want, and then select it. + + > [!NOTE] + > If you want to bind to a type in a framework or Microsoft assembly, clear the **Hide assemblies that begin with Microsoft or System** check box. + +7. Click **Next**, and then click **Finish**. + +### To bind the control to the BindingSource + +1. Add a to the form. + +2. In the **Properties** window, expand the **(DataBindings)** node. + +3. Click the arrow next to the property. + +4. In the **DataSource UI Type Editor**, expand the node for the added previously, and select the property of the bound type you want to bind to the property of the . + +## See also + +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) +- [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-type.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-type.md new file mode 100644 index 0000000000..caf40f396f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-a-windows-forms-control-to-a-type.md @@ -0,0 +1,34 @@ +--- +title: Bind Control to a Type +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], binding to a type" + - "BindingSource component [Windows Forms], binding to a type" + - "types [Windows Forms], binding controls to" +ms.assetid: 94faeebb-d2bc-45d6-86d7-96a42661b43d +--- +# How to: Bind a Windows Forms Control to a Type +When you are building controls that interact with data, you will sometimes find it necessary to bind a control to a type, rather than an object. This situation arises especially at design time, when data may not be available, but your data-bound controls still need to display information from a type's public interface. For example, you may bind a control to an object exposed by a Web service and want the control to label its columns at design time with the member names of a custom type. + + You can easily bind a control to a type with the component. + +## Example + The following code example demonstrates how to bind a control to a custom type by using a component. When you run the example, you'll notice the has labeled columns that reflect the properties of a `Customer` object, before the control is populated with data. The example has an Add Customer button to add data to the control. When you click the button, a new `Customer` object is added to the . In a real-world scenario, the data might be obtained by a call to a Web service or other data source. + + [!code-csharp[System.Windows.Forms.DataConnector.BindingToType#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnector.BindingToType#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [BindingSource Component](bindingsource-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-data-to-the-maskedtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-data-to-the-maskedtextbox-control.md new file mode 100644 index 0000000000..3c1de5643a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-data-to-the-maskedtextbox-control.md @@ -0,0 +1,248 @@ +--- +title: "How to: Bind Data to the MaskedTextBox Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "MaskedTextBox control [Windows Forms]" + - "data binding [Windows Forms], MaskedTextBox control [Windows Forms]" + - "MaskedTextBox control [Windows Forms], binding data" +ms.assetid: 34b29f07-e8df-48d4-b08b-53fcca524708 +--- +# How to: Bind Data to the MaskedTextBox Control +You can bind data to a control just as you can to any other Windows Forms control. However, if the format of your data in the database does not match the format expected by your mask definition, you will need to reformat the data. The following procedure demonstrates how to do this using the and events of the class to display separate phone number and phone extension database fields as a single editable field. + + The following procedure requires that you have access to a SQL Server database with the Northwind sample database installed. + +### To bind data to a MaskedTextBox control + +1. Create a new Windows Forms project. + +2. Drag two controls onto your form; name them `FirstName` and `LastName`. + +3. Drag a control onto your form; name it `PhoneMask`. + +4. Set the property of `PhoneMask` to `(000) 000-0000 x9999`. + +5. Add the following namespace imports to the form. + + ```csharp + using System.Data.SqlClient; + ``` + + ```vb + Imports System.Data.SqlClient + ``` + +6. Right-click the form and choose **View Code**. Place this code anywhere in your form class. + + ```csharp + Binding currentBinding, phoneBinding; + DataSet employeesTable = new DataSet(); + SqlConnection sc; + SqlDataAdapter dataConnect; + + private void Form1_Load(object sender, EventArgs e) + { + DoMaskBinding(); + } + + private void DoMaskBinding() + { + try + { + sc = new SqlConnection("Data Source=CLIENTUE;Initial Catalog=NORTHWIND;Integrated Security=SSPI"); + sc.Open(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + return; + } + + dataConnect = new SqlDataAdapter("SELECT * FROM Employees", sc); + dataConnect.Fill(employeesTable, "Employees"); + + // Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects + // before adding them to the control - otherwise, we won't get a Format event on the + // initial load. + try + { + currentBinding = new Binding("Text", employeesTable, "Employees.FirstName"); + firstName.DataBindings.Add(currentBinding); + + currentBinding = new Binding("Text", employeesTable, "Employees.LastName"); + lastName.DataBindings.Add(currentBinding); + + phoneBinding =new Binding("Text", employeesTable, "Employees.HomePhone"); + // We must add the event handlers before we bind, or the Format event will not get called + // for the first record. + phoneBinding.Format += new ConvertEventHandler(phoneBinding_Format); + phoneBinding.Parse += new ConvertEventHandler(phoneBinding_Parse); + phoneMask.DataBindings.Add(phoneBinding); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + return; + } + } + ``` + + ```vb + Dim WithEvents CurrentBinding, PhoneBinding As Binding + Dim EmployeesTable As New DataSet() + Dim sc As SqlConnection + Dim DataConnect As SqlDataAdapter + + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + DoMaskedBinding() + End Sub + + Private Sub DoMaskedBinding() + Try + sc = New SqlConnection("Data Source=SERVERNAME;Initial Catalog=NORTHWIND;Integrated Security=SSPI") + sc.Open() + Catch ex As Exception + MessageBox.Show(ex.Message) + Exit Sub + End Try + + DataConnect = New SqlDataAdapter("SELECT * FROM Employees", sc) + DataConnect.Fill(EmployeesTable, "Employees") + + ' Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects + ' before adding them to the control - otherwise, we won't get a Format event on the + ' initial load. + Try + CurrentBinding = New Binding("Text", EmployeesTable, "Employees.FirstName") + firstName.DataBindings.Add(CurrentBinding) + CurrentBinding = New Binding("Text", EmployeesTable, "Employees.LastName") + lastName.DataBindings.Add(CurrentBinding) + PhoneBinding = New Binding("Text", EmployeesTable, "Employees.HomePhone") + PhoneMask.DataBindings.Add(PhoneBinding) + Catch ex As Exception + MessageBox.Show(ex.Message) + Application.Exit() + End Try + End Sub + ``` + +7. Add event handlers for the and events to combine and separate the `PhoneNumber` and `Extension` fields from the bound . + + ```csharp + private void phoneBinding_Format(Object sender, ConvertEventArgs e) + { + String ext; + + DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current; + if (currentRow["Extension"] == null) + { + ext = ""; + } else + { + ext = currentRow["Extension"].ToString(); + } + + e.Value = e.Value.ToString().Trim() + " x" + ext; + } + + private void phoneBinding_Parse(Object sender, ConvertEventArgs e) + { + String phoneNumberAndExt = e.Value.ToString(); + + int extIndex = phoneNumberAndExt.IndexOf("x"); + String ext = phoneNumberAndExt.Substring(extIndex).Trim(); + String phoneNumber = phoneNumberAndExt.Substring(0, extIndex).Trim(); + + //Get the current binding object, and set the new extension manually. + DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current; + // Remove the "x" from the extension. + currentRow["Extension"] = ext.Substring(1); + + //Return the phone number. + e.Value = phoneNumber; + } + ``` + + ```vb + Private Sub PhoneBinding_Format(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Format + Dim Ext As String + + Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView) + If (CurrentRow("Extension") Is Nothing) Then + Ext = "" + Else + Ext = CurrentRow("Extension").ToString() + End If + + e.Value = e.Value.ToString().Trim() & " x" & Ext + End Sub + + Private Sub PhoneBinding_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Parse + Dim PhoneNumberAndExt As String = e.Value.ToString() + + Dim ExtIndex As Integer = PhoneNumberAndExt.IndexOf("x") + Dim Ext As String = PhoneNumberAndExt.Substring(ExtIndex).Trim() + Dim PhoneNumber As String = PhoneNumberAndExt.Substring(0, ExtIndex).Trim() + + ' Get the current binding object, and set the new extension manually. + Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView) + ' Remove the "x" from the extension. + CurrentRow("Extension") = CObj(Ext.Substring(1)) + + ' Return the phone number. + e.Value = PhoneNumber + End Sub + ``` + +8. Add two controls to the form. Name them `previousButton` and `nextButton`. Double-click each button to add a event handler, and fill in the event handlers as shown in the following code example. + + ```csharp + private void previousButton_Click(object sender, EventArgs e) + { + BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position - 1; + } + + private void nextButton_Click(object sender, EventArgs e) + { + BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position + 1; + } + ``` + + ```vb + Private Sub PreviousButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousButton.Click + Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position - 1 + End Sub + + Private Sub NextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextButton.Click + Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position + 1 + End Sub + ``` + +9. Run the sample. Edit the data, and use the **Previous** and **Next** buttons to see that the data is properly persisted to the . + +## Example + The following code example is the full code listing that results from completing the previous procedure. + + [!code-cpp[MaskedTextBoxData#1](~/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/form1.cpp#1)] + [!code-csharp[MaskedTextBoxData#1](~/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/form1.cs#1)] + [!code-vb[MaskedTextBoxData#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/form1.vb#1)] + +## Compiling the Code + +- Create a Visual C# or Visual Basic project. + +- Add the and controls to the form, as described in the previous procedure. + +- Open the source code file for the project's default form. + +- Replace the source code in this file with the code listed in the previous "Code" section. + +- Compile the application. + +## See also + +- [Walkthrough: Working with the MaskedTextBox Control](walkthrough-working-with-the-maskedtextbox-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..2c9670dfc5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-data-to-the-windows-forms-datagridview-control.md @@ -0,0 +1,49 @@ +--- +title: Bind data to DataGridView Control +ms.date: "02/08/2019" +description: Learn how DataGridView control supports the standard Windows Forms data binding model so it can bind to a variety of data sources. +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data binding [Windows Forms], grids" + - "data binding [Windows Forms], DataGridView control" + - "DataGridView control [Windows Forms], data binding" +ms.assetid: 1660f69c-5711-45d2-abc1-e25bc6779124 +--- +# How to: Bind data to the Windows Forms DataGridView control + +The control supports the standard Windows Forms data binding model, so it can bind to a variety of data sources. Usually, you bind to a that manages the interaction with the data source. The can be any Windows Forms data source, which gives you great flexibility when choosing or modifying your data's location. For more information about data sources the control supports, see the [DataGridView control overview](datagridview-control-overview-windows-forms.md). + +Visual Studio has extensive support for data binding to the DataGridView control. For more information, see [How to: Bind data to the Windows Forms DataGridView control using the Designer](bind-data-to-the-datagrid-using-the-designer.md). + +To connect a DataGridView control to data: + +1. Implement a method to handle the details of retrieving the data. The following code example implements a `GetData` method that initializes a , and uses it to populate a . It then binds the to the . + +2. In the form's event handler, bind the control to the , and call the `GetData` method to retrieve the data. + +## Example + +This complete code example retrieves data from a database to populate a DataGridView control in a Windows form. The form also has buttons to reload data and submit changes to the database. + +This example requires: + +- Access to a Northwind SQL Server sample database. For more information about installing the Northwind sample database, see [Get the sample databases for ADO.NET code samples](https://docs.microsoft.com/dotnet/framework/data/adonet/sql/linq/downloading-sample-databases). + +- References to the System, System.Windows.Forms, System.Data, and System.Xml assemblies. + +To build and run this example, paste the code into the *Form1* code file in a new Windows Forms project. For information about building from the C# or Visual Basic command line, see [Command-line building with csc.exe](https://docs.microsoft.com/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe) or [Build from the command line](https://docs.microsoft.com/dotnet/visual-basic/reference/command-line-compiler/building-from-the-command-line). + +Populate the `connectionString` variable in the example with the values for your Northwind SQL Server sample database connection. Windows Authentication, also called integrated security, is a more secure way to connect to the database than storing a password in the connection string. For more information about connection security, see [Protect connection information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + +[!code-csharp[System.Windows.Forms.DataGridViewBoundEditable](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/CS/datagridviewboundeditable.cs)] +[!code-vb[System.Windows.Forms.DataGridViewBoundEditable](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/VB/datagridviewboundeditable.vb)] + +## See also + +- +- +- +- [Display data in the Windows Forms DataGridView control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [Protect connection information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-objects-to-windows-forms-datagridview-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-objects-to-windows-forms-datagridview-controls.md new file mode 100644 index 0000000000..adf8558399 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-objects-to-windows-forms-datagridview-controls.md @@ -0,0 +1,30 @@ +--- +title: Bind Objects to DataGridView Controls +description: Learn how to how to bind a collection of objects to a Windows Forms DataGridView control so that each object displays as a separate row. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], object binding" + - "data grids [Windows Forms], object binding" + - "object binding [Windows Forms], DataGridView control" +ms.assetid: cb8f29fa-577e-4e2b-883f-3a01c6189b9c +--- +# How to: Bind Objects to Windows Forms DataGridView Controls +The following code example demonstrates how to bind a collection of objects to a control so that each object displays as a separate row. This example also illustrates how to display a property with an enumeration type in a so that the combo box drop-down list contains the enumeration values. + +## Example + [!code-csharp[System.Windows.Forms.DataGridView._CollectionBound#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/CS/collectionbound.cs#00)] + [!code-vb[System.Windows.Forms.DataGridView._CollectionBound#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/VB/collectionbound.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Access Objects Bound to Windows Forms DataGridView Rows](how-to-access-objects-bound-to-windows-forms-datagridview-rows.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md new file mode 100644 index 0000000000..ce2d077a71 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md @@ -0,0 +1,105 @@ +--- +title: Bind DataGrid Control to a Data Source +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "datasets [Windows Forms], binding to DataGrid control" + - "data binding [Windows Forms], DataGrid control" + - "DataGrid control [Windows Forms], data binding" + - "bound controls [Windows Forms], DataGrid control" + - "Windows Forms controls, data binding" + - "bound controls [Windows Forms]" + - "data-bound controls [Windows Forms], DataGrid" +ms.assetid: 128cdb07-dfd3-4d60-9d6a-902847667c36 +--- +# How to: Bind the Windows Forms DataGrid Control to a Data Source +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + The Windows Forms control is specifically designed to display information from a data source. You bind the control at run time by calling the method. Although you can display data from a variety of data sources, the most typical sources are datasets and data views. + +### To data-bind the DataGrid control programmatically + +1. Write code to fill the dataset. + + If the data source is a dataset or a data view based on a dataset table, add code to the form to fill the dataset. + + The exact code you use depends on where the dataset is getting data. If the dataset is being populated directly from a database, you typically call the `Fill` method of a data adapter, as in the following example, which populates a dataset called `DsCategories1`: + + ```vb + sqlDataAdapter1.Fill(DsCategories1) + ``` + + ```csharp + sqlDataAdapter1.Fill(DsCategories1); + ``` + + ```cpp + sqlDataAdapter1->Fill(dsCategories1); + ``` + + If the dataset is being filled from an XML Web service, you typically create an instance of the service in your code and then call one of its methods to return a dataset. You then merge the dataset from the XML Web service into your local dataset. The following example shows how you can create an instance of an XML Web service called `CategoriesService`, call its `GetCategories` method, and merge the resulting dataset into a local dataset called `DsCategories1`: + + ```vb + Dim ws As New MyProject.localhost.CategoriesService() + ws.Credentials = System.Net.CredentialCache.DefaultCredentials + DsCategories1.Merge(ws.GetCategories()) + ``` + + ```csharp + MyProject.localhost.CategoriesService ws = new MyProject.localhost.CategoriesService(); + ws.Credentials = System.Net.CredentialCache.DefaultCredentials; + DsCategories1.Merge(ws.GetCategories()); + ``` + + ```cpp + MyProject::localhost::CategoriesService^ ws = + new MyProject::localhost::CategoriesService(); + ws->Credentials = System::Net::CredentialCache::DefaultCredentials; + dsCategories1->Merge(ws->GetCategories()); + ``` + +2. Call the control's method, passing it the data source and a data member. If you do not need to explicitly pass a data member, pass an empty string. + + > [!NOTE] + > If you are binding the grid for the first time, you can set the control's and properties. However, you cannot reset these properties once they have been set. Therefore, it is recommended that you always use the method. + + The following example shows how you can programmatically bind to the Customers table in a dataset called `DsCustomers1`: + + ```vb + DataGrid1.SetDataBinding(DsCustomers1, "Customers") + ``` + + ```csharp + DataGrid1.SetDataBinding(DsCustomers1, "Customers"); + ``` + + ```cpp + dataGrid1->SetDataBinding(dsCustomers1, "Customers"); + ``` + + If the Customers table is the only table in the dataset, you could alternatively bind the grid this way: + + ```vb + DataGrid1.SetDataBinding(DsCustomers1, "") + ``` + + ```csharp + DataGrid1.SetDataBinding(DsCustomers1, ""); + ``` + + ```cpp + dataGrid1->SetDataBinding(dsCustomers1, ""); + ``` + +3. (Optional) Add the appropriate table styles and column styles to the grid. If there are no table styles, you will see the table, but with minimal formatting and with all columns visible. + +## See also + +- [DataGrid Control Overview](datagrid-control-overview-windows-forms.md) +- [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) +- [DataGrid Control](datagrid-control-windows-forms.md) +- [Windows Forms Data Binding](../windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-to-a-web-service-using-the-windows-forms-bindingsource.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-to-a-web-service-using-the-windows-forms-bindingsource.md new file mode 100644 index 0000000000..e19c05f0fa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-to-a-web-service-using-the-windows-forms-bindingsource.md @@ -0,0 +1,70 @@ +--- +title: Bind to a Web Service Using BindingSource +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Web services [Windows Forms], binding controls" + - "BindingSource component [Windows Forms], binding to a Web service" + - "examples [Windows Forms], BindingSource component" + - "controls [Windows Forms], binding to Web service" + - "BindingSource component [Windows Forms], examples" +ms.assetid: ee261207-4573-4cb9-a8cb-5185037e0fba +--- +# How to: Bind to a Web Service Using the Windows Forms BindingSource +If you want to bind a Windows Form control to the results obtained from calling an XML Web service, you can use a component. This procedure is similar to binding a component to a type. You must create a client-side proxy that contains the methods and types exposed by the Web service. You generate a client-side proxy from the Web service (.asmx) itself, or its Web Services Description Language (WSDL) file. Additionally, your client-side proxy must expose the fields of complex types used by the Web service as public properties. You then bind the to one of the types exposed in the Web service proxy. + +### To create and bind to a client-side proxy + +1. Create a Windows Form in the directory of your choice, with an appropriate namespace. + +2. Add a component to the form. + +3. Open the Windows Software Development Kit (SDK) command prompt, and navigate to the same directory that your form is located in. + +4. Using the WSDL tool, enter `wsdl` and the URL for the .asmx or WSDL file for the Web service, followed by the namespace of your application, and optionally the language you are working in. + + The following code example uses the Web service located at `http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx`. For example, for C# type `wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService`, or for Visual Basic type `wsdl http://webservices.eraserver.net.zipcoderesolver/zipcoderesolver.asmx /n:BindToWebService /language:VB`. Passing the path as an argument to the WSDL tool will generate a client-side proxy in the same directory and namespace as your application, in the specified language. If you are using Visual Studio, add the file to your project. + +5. Select a type in the client-side proxy to bind to. + + This is typically a type returned by a method offered by the Web service. The fields of the chosen type must be exposed as public properties for binding purposes. + + [!code-cpp[System.Windows.Forms.DataConnectorWebService#4](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp#4)] + [!code-csharp[System.Windows.Forms.DataConnectorWebService#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs#4)] + [!code-vb[System.Windows.Forms.DataConnectorWebService#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb#4)] + +6. Set the property of the to the type you want that is contained in the Web service client-side proxy. + + [!code-cpp[System.Windows.Forms.DataConnectorWebService#2](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp#2)] + [!code-csharp[System.Windows.Forms.DataConnectorWebService#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs#2)] + [!code-vb[System.Windows.Forms.DataConnectorWebService#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb#2)] + +### To bind controls to the BindingSource that is bound to a Web service + +- Bind controls to the , passing the public property of the Web service type that you want as a parameter. + + [!code-cpp[System.Windows.Forms.DataConnectorWebService#3](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp#3)] + [!code-csharp[System.Windows.Forms.DataConnectorWebService#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs#3)] + [!code-vb[System.Windows.Forms.DataConnectorWebService#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb#3)] + +## Example + The following code example demonstrates how to bind a component to a Web service, and then how to bind a text box to the component. When you click the button, a Web service method is called and the results will appear in `textbox1`. + + [!code-cpp[System.Windows.Forms.DataConnectorWebService#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp#1)] + [!code-csharp[System.Windows.Forms.DataConnectorWebService#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnectorWebService#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb#1)] + +## Compiling the Code + This is a complete example that includes a `Main` method, and a shortened version of client-side proxy code. + + This example requires: + +- References to the System, System.Drawing, System.Web.Services, System.Windows.Forms and System.Xml assemblies. + +## See also + +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-windows-forms-controls-to-dbnull-database-values.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-windows-forms-controls-to-dbnull-database-values.md new file mode 100644 index 0000000000..035d1af162 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-bind-windows-forms-controls-to-dbnull-database-values.md @@ -0,0 +1,33 @@ +--- +title: Bind Controls to DBNull Database Values +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "BindingSource component [Windows Forms], binding to DBNull values" + - "examples [Windows Forms], BindingSource component" + - "controls [Windows Forms], binding to DBNull values" +ms.assetid: 96494e6f-5f40-4f83-af97-bbd7192c2af8 +--- +# How to: Bind Windows Forms Controls to DBNull Database Values +When you bind Windows Forms controls to a data source and the data source returns a value, you can substitute an appropriate value without handling, formatting, or parsing events. The property will convert to a specified object when formatting or parsing the data source values. + +## Example + The following example demonstrates how to bind a value in two different situations. The first demonstrates how to set the for a string property; the second demonstrates how to set the for an image property. + + [!code-csharp[System.Windows.Forms.BindingDBNull#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.BindingDBNull#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/VB/form1.vb#1)] + + The types of the bound property and the property must be the same or an error will result, and no further values will be processed. In this situation, an exception will not be thrown. + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [BindingSource Component](bindingsource-component.md) +- [How to: Handle Errors and Exceptions that Occur with Databinding](how-to-handle-errors-and-exceptions-that-occur-with-databinding.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-monthcalendar-control-appearance.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-monthcalendar-control-appearance.md new file mode 100644 index 0000000000..030f857db4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-monthcalendar-control-appearance.md @@ -0,0 +1,105 @@ +--- +title: Change MonthCalendar Control's Appearance +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], calendar controls" + - "MonthCalendar control [Windows Forms], formatting display" +ms.assetid: d09b95c9-e108-4608-9b31-b9100c0677bf +--- +# How to: Change the Windows Forms MonthCalendar Control's Appearance +The Windows Forms control allows you to customize the calendar's appearance in many ways. For example, you can set the color scheme and choose to display or hide week numbers and the current date. + +### To change the month calendar's color scheme + +- Set properties such as , and . The property also determines the font color for the days of the week. The property determines the color of the dates that precede and follow the displayed month or months. + + ```vb + MonthCalendar1.TitleBackColor = System.Drawing.Color.Blue + MonthCalendar1.TrailingForeColor = System.Drawing.Color.Red + MonthCalendar1.TitleForeColor = System.Drawing.Color.Yellow + ``` + + ```csharp + monthCalendar1.TitleBackColor = System.Drawing.Color.Blue; + monthCalendar1.TrailingForeColor = System.Drawing.Color.Red; + monthCalendar1.TitleForeColor = System.Drawing.Color.Yellow; + ``` + + ```cpp + monthCalendar1->TitleBackColor = System::Drawing::Color::Blue; + monthCalendar1->TrailingForeColor = System::Drawing::Color::Red; + monthCalendar1->TitleForeColor = System::Drawing::Color::Yellow; + ``` + + > [!NOTE] + > Starting with Windows Vista and depending on the theme, setting some properties might not change the appearance of the calendar. For example, if Windows is set to use the Aero theme, setting the , , , or properties has no effect. This is because an updated version of the calendar is rendered with an appearance that is derived at run time from the current operating system theme. If you want to use these properties and enable the earlier version of the calendar, you can disable visual styles for your application. Disabling visual styles might affect the appearance and behavior of other controls in your application. To disable visual styles in Visual Basic, open the Project Designer and uncheck the **Enable XP visual styles** check box. To disable visual styles in C#, open Program.cs and comment out `Application.EnableVisualStyles();`. For more information about visual styles, see [Enabling Visual Styles](/windows/desktop/controls/cookbook-overview). + +### To display the current date at the bottom of the control + +- Set the property to `true`. The example below toggles between displaying and omitting today's date when the form is double-clicked. + + ```vb + Private Sub Form1_DoubleClick(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles MyBase.DoubleClick + ' Toggle between True and False. + MonthCalendar1.ShowToday = Not MonthCalendar1.ShowToday + End Sub + ``` + + ```csharp + private void Form1_DoubleClick(object sender, System.EventArgs e) + { + // Toggle between True and False. + monthCalendar1.ShowToday = !monthCalendar1.ShowToday; + } + ``` + + ```cpp + private: + System::Void Form1_DoubleClick(System::Object ^ sender, + System::EventArgs ^ e) + { + // Toggle between True and False. + monthCalendar1->ShowToday = !monthCalendar1->ShowToday; + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.DoubleClick += new System.EventHandler(this.Form1_DoubleClick); + ``` + + ```cpp + this->DoubleClick += gcnew System::EventHandler(this, + &Form1::Form1_DoubleClick); + ``` + +### To display week numbers + +- Set the property to `true`. You can set this property either in code or in the Properties window. + + Week numbers appear in a separate column to the left of the first day of the week. + + ```vb + MonthCalendar1.ShowWeekNumbers = True + ``` + + ```csharp + monthCalendar1.ShowWeekNumbers = true; + ``` + + ```cpp + monthCalendar1->ShowWeekNumbers = true; + ``` + +## See also + +- [MonthCalendar Control](monthcalendar-control-windows-forms.md) +- [How to: Select a Range of Dates in the Windows Forms MonthCalendar Control](how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md) +- [How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control](display-specific-days-in-bold-with-wf-monthcalendar-control.md) +- [How to: Display More than One Month in the Windows Forms MonthCalendar Control](display-more-than-one-month-wf-monthcalendar-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-styles-on-an-element-in-the-managed-html-document-object-model.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-styles-on-an-element-in-the-managed-html-document-object-model.md new file mode 100644 index 0000000000..c2f635b769 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-styles-on-an-element-in-the-managed-html-document-object-model.md @@ -0,0 +1,77 @@ +--- +title: "How to: Change Styles on an Element in the Managed HTML Document Object Model" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "managed HTML DOM [Windows Forms], changing styles on elements" +ms.assetid: 154e8d9f-3e2d-4e8b-a6f3-c85a070e9cc1 +--- + +# How to: Change Styles on an Element in the Managed HTML Document Object Model + +You can use styles in HTML to control the appearance of a document and its elements. and support properties that take style strings of the following format: + +`name1:value1;...;nameN:valueN;` + +Here is a `DIV` with a style string that sets the font to Arial and all text to bold: + +```html +
+Hello, world! +
+``` + +The problem with manipulating styles using the property is that it can prove cumbersome to add to and remove individual style settings from the string. For example, it would become a complex procedure for you to render the previous text in italics whenever the user positions the cursor over the `DIV`, and take italics off when the cursor leaves the `DIV`. Time would become an issue if you need to manipulate a large number of styles in this manner. + +The following procedure contains code that you can use to easily manipulate styles on HTML documents and elements. The procedure requires that you know how to perform basic tasks in Windows Forms, such as creating a new project and adding a control to a form. + +### To process style changes in a Windows Forms application + +1. Create a new Windows Forms project. + +2. Create a new class file ending in the extension appropriate for your programming language. + +3. Copy the `StyleGenerator` class code in the Example section of this topic into the class file, and save the code. + +4. Save the following HTML to a file named Test.htm. + + ```html + + + +
+ Hello, world! +

+ +

+ Hello again, world! +

+ + + + ``` + +5. Add a control named `webBrowser1` to the main form of your project. + +6. Add the following code to your project's code file. + + > [!IMPORTANT] + > Ensure that the `webBrowser1_DocumentCompleted` event handler is configured as a listener for the event. In Visual Studio, double-click on the control; in a text editor, configure the listener programmatically. + + [!code-csharp[ManagedDOMStyles#2](~/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.cs#2)] + [!code-vb[ManagedDOMStyles#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.vb#2)] + +7. Run the project. Run your cursor over the first `DIV` to observe the effects of the code. + +## Example + +The following code example shows the full code for the `StyleGenerator` class, which parses an existing style value, supports adding, changing, and removing styles, and returns a new style value with the requested changes. + +[!code-csharp[ManagedDOMStyles#1](~/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/StyleGenerator.cs#1)] +[!code-vb[ManagedDOMStyles#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/StyleGenerator.vb#1)] + +## See also + +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-colordialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-colordialog-component.md new file mode 100644 index 0000000000..c2229a8464 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-colordialog-component.md @@ -0,0 +1,50 @@ +--- +title: Change the Appearance of ColorDialog Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ColorDialog component [Windows Forms], examples" + - "ColorDialog component [Windows Forms], formatting appearance" + - "color dialog box [Windows Forms], configuring appearance" +ms.assetid: bba4e262-1cd7-4f63-89cf-330a36f7b539 +--- +# How to: Change the Appearance of the Windows Forms ColorDialog Component +You can configure the appearance of the Windows Forms component with a number of its properties. The dialog box has two sections — one that shows basic colors and one that allows the user to define custom colors. + + Most of the properties restrict what colors the user can select from the dialog box. If the property is set to `true`, the user is allowed to define custom colors. The property is `true` if the dialog box is expanded to define custom colors; otherwise the user must click a "Define Custom Colors" button. When the property is set to `true`, the dialog box displays all available colors in the set of basic colors. If the property is set to `true`, the user cannot select dithered colors; only solid colors are available to select. + + If the property is set to `true`, a Help button appears on the dialog box. When the user clicks the Help button, the component's event is raised. + +### To configure the appearance of the color dialog box + +1. Set the , , , and properties to the desired values. + + ```vb + ColorDialog1.AllowFullOpen = True + ColorDialog1.AnyColor = True + ColorDialog1.SolidColorOnly = False + ColorDialog1.ShowHelp = True + ``` + + ```csharp + colorDialog1.AllowFullOpen = true; + colorDialog1.AnyColor = true; + colorDialog1.SolidColorOnly = false; + colorDialog1.ShowHelp = true; + ``` + + ```cpp + colorDialog1->AllowFullOpen = true; + colorDialog1->AnyColor = true; + colorDialog1->SolidColorOnly = false; + colorDialog1->ShowHelp = true; + ``` + +## See also + +- +- [ColorDialog Component](colordialog-component-windows-forms.md) +- [ColorDialog Component Overview](colordialog-component-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md new file mode 100644 index 0000000000..b2066fc0bb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md @@ -0,0 +1,126 @@ +--- +title: Change the Appearance of LinkLabel Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "LinkLabel properties" + - "LinkLabel control [Windows Forms], changing appearance of links" + - "links [Windows Forms], changing appearance" + - "examples [Windows Forms], LinkLabel control" + - "LinkLabel control [Windows Forms], examples" +ms.assetid: fdc5854f-5162-4457-8cbe-1042feb2d132 +--- +# How to: Change the Appearance of the Windows Forms LinkLabel Control +You can change the text displayed by the control to suit a variety of purposes. For example, it is common practice to indicate to the user that text can be clicked by setting the text to appear in a specific color with an underline. After the user clicks the text, the color changes to a different color. To control this behavior, you can set five different properties: the , , , , and properties. + +### To change the appearance of a LinkLabel control + +1. Set the and properties to the colors you want. + + This can be done either programmatically or at design time in the **Properties** window. + + ```vb + ' You can set the color using decimal values for red, green, and blue + LinkLabel1.LinkColor = Color.FromArgb(0, 0, 255) + ' Or you can set the color using defined constants + LinkLabel1.VisitedLinkColor = Color.Purple + ``` + + ```csharp + // You can set the color using decimal values for red, green, and blue + linkLabel1.LinkColor = Color.FromArgb(0, 0, 255); + // Or you can set the color using defined constants + linkLabel1.VisitedLinkColor = Color.Purple; + ``` + + ```cpp + // You can set the color using decimal values for red, green, and blue + linkLabel1->LinkColor = Color::FromArgb(0, 0, 255); + // Or you can set the color using defined constants + linkLabel1->VisitedLinkColor = Color::Purple; + ``` + +2. Set the property to an appropriate caption. + + This can be done either programmatically or at design time in the **Properties** window. + + ```vb + LinkLabel1.Text = "Click here to see more." + ``` + + ```csharp + linkLabel1.Text = "Click here to see more."; + ``` + + ```cpp + linkLabel1->Text = "Click here to see more."; + ``` + +3. Set the property to determine which part of the caption will be indicated as a link. + + The value is represented with a containing two numbers, the starting character position and the number of characters. This can be done either programmatically or at design time in the **Properties** window. + + ```vb + LinkLabel1.LinkArea = new LinkArea(6,4) + ``` + + ```csharp + linkLabel1.LinkArea = new LinkArea(6,4); + ``` + + ```cpp + linkLabel1->LinkArea = LinkArea(6,4); + ``` + +4. Set the property to , , or . + + If it is set to , the part of the caption determined by will only be underlined when the pointer rests on it. + +5. In the event handler, set the property to `true`. + + When a link has been visited, it is common practice to change its appearance in some way, usually by color. The text will change to the color specified by the property. + + ```vb + Protected Sub LinkLabel1_LinkClicked (ByVal sender As Object, _ + ByVal e As EventArgs) Handles LinkLabel1.LinkClicked + ' Change the color of the link text + ' by setting LinkVisited to True. + LinkLabel1.LinkVisited = True + ' Then do whatever other action is appropriate + End Sub + ``` + + ```csharp + protected void LinkLabel1_LinkClicked(object sender, System.EventArgs e) + { + // Change the color of the link text by setting LinkVisited + // to True. + linkLabel1.LinkVisited = true; + // Then do whatever other action is appropriate + } + ``` + + ```cpp + private: + System::Void linkLabel1_LinkClicked(System::Object ^ sender, + System::Windows::Forms::LinkLabelLinkClickedEventArgs ^ e) + { + // Change the color of the link text by setting LinkVisited + // to True. + linkLabel1->LinkVisited = true; + // Then do whatever other action is appropriate + } + ``` + +## See also + +- +- +- +- +- [LinkLabel Control Overview](linklabel-control-overview-windows-forms.md) +- [How to: Link to an Object or Web Page with the Windows Forms LinkLabel Control](link-to-an-object-or-web-page-with-wf-linklabel-control.md) +- [LinkLabel Control](linklabel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md new file mode 100644 index 0000000000..3d318418bf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md @@ -0,0 +1,68 @@ +--- +title: Change the Appearance of TabControl +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "icons [Windows Forms], displaying on tabs" + - "TabControl control [Windows Forms], changing page appearance" + - "tabs [Windows Forms], controlling appearance" + - "buttons [Windows Forms], displaying tabs as" +ms.assetid: 7c6cc443-ed62-4d26-b94d-b8913b44f773 +--- +# How to: Change the Appearance of the Windows Forms TabControl +You can change the appearance of tabs in Windows Forms by using properties of the and the objects that make up the individual tabs on the control. By setting these properties, you can display images on tabs, display tabs vertically instead of horizontally, display multiple rows of tabs, and enable or disable tabs programmatically. + +### To display an icon on the label part of a tab + +1. Add an control to the form. + +2. Add images to the image list. + + For more information about image lists, see [ImageList Component](imagelist-component-windows-forms.md) and [How to: Add or Remove Images with the Windows Forms ImageList Component](how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md). + +3. Set the property of the to the control. + +4. Set the property of the to the index of an appropriate image in the list. + +### To create multiple rows of tabs + +1. Add the number of tab pages you want. + +2. Set the property of the to `true`. + +3. If the tabs do not already appear in multiple rows, set the property of the to be narrower than all the tabs. + +### To arrange tabs on the side of the control + +- Set the property of the to or . + +### To programmatically enable or disable all controls on a tab + +1. Set the property of the to `true` or `false`. + + ```vb + TabPage1.Enabled = False + ``` + + ```csharp + tabPage1.Enabled = false; + ``` + + ```cpp + tabPage1->Enabled = false; + ``` + +### To display tabs as buttons + +- Set the property of the to or . + +## See also + +- [TabControl Control](tabcontrol-control-windows-forms.md) +- [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) +- [How to: Add a Control to a Tab Page](how-to-add-a-control-to-a-tab-page.md) +- [How to: Disable Tab Pages](how-to-disable-tab-pages.md) +- [How to: Add and Remove Tabs with the Windows Forms TabControl](how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-toolstrip-text-and-images-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-toolstrip-text-and-images-in-windows-forms.md new file mode 100644 index 0000000000..c32de2a209 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-appearance-of-toolstrip-text-and-images-in-windows-forms.md @@ -0,0 +1,77 @@ +--- +title: "How to: Change the Appearance of ToolStrip Text and Images" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], appearance" + - "toolbars [Windows Forms], images" + - "examples [Windows Forms], toolbars" + - "toolbars [Windows Forms], appearance" + - "ToolStrip control [Windows Forms], images" + - "ToolStrip control [Windows Forms], text" + - "toolbars [Windows Forms], text" +ms.assetid: d62dc9d1-2edd-4dfa-aed7-1335d6e13d86 +--- +# How to: Change the Appearance of ToolStrip Text and Images in Windows Forms +You can control whether text and images are displayed on a and how they are aligned relative to each other and the . + +### To define what is displayed on a ToolStripItem + +- Set the property to the desired value. The possibilities are `Image`, `ImageAndText`, `None`, and `Text`. The default is `ImageAndText`. + + ```vb + ToolStripButton2.DisplayStyle = _ + System.Windows.Forms.ToolStripItemDisplayStyle.Image + ``` + + ```csharp + toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + ``` + +### To align text on a ToolStripItem + +- Set the property to the desired value. The possibilities are any combination of top, middle, and bottom with left, center, and right. The default is `MiddleCenter`. + + ```vb + ToolStripSplitButton1.TextAlign = _ + System.Drawing.ContentAlignment.MiddleRight + ``` + + ```csharp + toolStripSplitButton1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + ``` + +### To align an image on a ToolStripItem + +- Set the property to the desired value. The possibilities are any combination of top, middle, and bottom with left, center, and right. The default is `MiddleLeft`. + + ```vb + ToolStripSplitButton1.ImageAlign = _ + System.Drawing.ContentAlignment.MiddleRight + ``` + + ```csharp + toolStripSplitButton1.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; + ``` + +### To define how ToolStripItem text and images are displayed relative to each other + +- Set the property to the desired value. The possibilities are `ImageAboveText`, `ImageBeforeText`, `Overlay`, `TextAboveImage`, and `TextBeforeImage`. The default is `ImageBeforeText`. + + ```vb + ToolStripButton1.TextImageRelation = _ + System.Windows.Forms.TextImageRelation.ImageAboveText + ``` + + ```csharp + toolStripButton1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; + ``` + +## See also + +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-delay-of-the-windows-forms-tooltip-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-delay-of-the-windows-forms-tooltip-component.md new file mode 100644 index 0000000000..a6fc9551e3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-delay-of-the-windows-forms-tooltip-component.md @@ -0,0 +1,43 @@ +--- +title: Change the Delay of ToolTip Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ToolTip component [Windows Forms], delay values" + - "tooltips [Windows Forms], delay values" + - "examples [Windows Forms], tooltips" +ms.assetid: 08979ba7-dd84-477b-ab17-8d06e759be99 +--- +# How to: Change the Delay of the Windows Forms ToolTip Component +There are multiple delay values that you can set for a Windows Forms component. The unit of measure for all these properties is milliseconds. The property determines how long the user must point at the associated control for the ToolTip string to appear. The property sets the number of milliseconds it takes for subsequent ToolTip strings to appear as the mouse moves from one ToolTip-associated control to another. The property determines the length of time the ToolTip string is shown. You can set these values individually, or by setting the value of the property; the other delay properties are set based on the value assigned to the property. For example, when is set to a value N, is set to N, is set to the value of divided by five (or N/5), and is set to a value that is five times the value of the property (or 5N). + +### To set the delay + +1. Set the following properties as shown in this example. + + ```vb + ToolTip1.InitialDelay = 500 + ToolTip1.ReshowDelay = 100 + ToolTip1.AutoPopDelay = 5000 + ``` + + ```csharp + ToolTip1.InitialDelay = 500; + ToolTip1.ReshowDelay = 100; + ToolTip1.AutoPopDelay = 5000; + ``` + + ```cpp + toolTip1->InitialDelay = 500; + toolTip1->ReshowDelay = 100; + toolTip1->AutoPopDelay = 5000; + ``` + +## See also + +- [ToolTip Component Overview](tooltip-component-overview-windows-forms.md) +- [How to: Set ToolTips for Controls on a Windows Form at Design Time](how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md) +- [ToolTip Component](tooltip-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..83781be918 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,38 @@ +--- +title: Change the Order of Columns in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "columns [Windows Forms], changing order" + - "DataGridView control [Windows Forms], column order" + - "data grids [Windows Forms], changing column order" +ms.assetid: 5e9ac3bc-b0f0-48cb-a3d5-b005af905395 +--- +# How to: Change the Order of Columns in the Windows Forms DataGridView Control +When you use a to display data from a data source, the columns in the data source's schema sometimes do not appear in the order you would like to display them. You can change the displayed order of the columns by using the property of the class. + + The following code example repositions some of the columns automatically generated when binding to the Customers table in the Northwind sample database. For more information about how to bind the control to a database table, see [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md). + + There is support for this task in Visual Studio. Also see [How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer](change-the-order-of-columns-in-the-datagrid-using-the-designer.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#040](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#040)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#040](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#040)] + +## Compiling the Code + This example requires: + +- A control named `customersDataGridView` that is bound to a table with the indicated column names, such as the `Customers` table in the Northwind sample database. + +- References to the , , , and assemblies. + +## See also + +- +- +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Bind Data to the Windows Forms DataGridView Control](how-to-bind-data-to-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-spacing-and-alignment-of-toolstrip-items-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-spacing-and-alignment-of-toolstrip-items-in-windows-forms.md new file mode 100644 index 0000000000..c253a8d11c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-change-the-spacing-and-alignment-of-toolstrip-items-in-windows-forms.md @@ -0,0 +1,87 @@ +--- +title: "How to: Change the Spacing and Alignment of ToolStrip Items" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], aligning items" + - "examples [Windows Forms], toolbars" + - "toolbars [Windows Forms], aligning items" +ms.assetid: cd483466-0f49-43df-addf-e2b5fcd64027 +--- +# How to: Change the Spacing and Alignment of ToolStrip Items in Windows Forms +The control fully supports layout features such as sizing, the spacing of controls relative to each other, the arrangement of controls on the , and the spacing of controls relative to the . + + Because the default value of the property is `true`, controls are sized automatically unless you set the property to `false`. + +### To manually size a ToolStripItem + +1. Set the property to `false` for the associated control. + + ```vb + ToolStripButton1.AutoSize = False + ``` + + ```csharp + toolStripButton1.AutoSize = false; + ``` + +2. Set the property the way you want for the associated . + +### To set the spacing of a ToolStripItem + +1. Insert the desired values, in pixels, into the property of the associated control. + + The values of the property specify the spacing between the item and adjacent items in this order: Left, Top, Right, and Bottom. + + ```vb + ToolStripTextBox1.Margin = New System.Windows.Forms.Padding _ + (3, 0, 3, 0) + ``` + + ```csharp + toolStripTextBox1.Margin = new System.Windows.Forms.Padding + (3, 0, 3, 0); + ``` + +### To align a ToolStripItem to the right side of the ToolStrip + +1. Set the property to for the associated control. By default, is set to , which aligns controls to the left side of the . + + ```vb + ToolStripSplitButton1.Alignment = _ + System.Windows.Forms.ToolStripItemAlignment.Right + ``` + + ```csharp + toolStripSplitButton1.Alignment = + System.Windows.Forms.ToolStripItemAlignment.Right; + ``` + +### To arrange ToolStrip items on the ToolStrip + +- Set the property to the value of that you want. + + ```vb + ToolStripDropDown1.LayoutStyle = _ + System.Windows.Forms.ToolStripLayoutStyle.Flow + ``` + + ```csharp + toolStripDropDown1.LayoutStyle = + System.Windows.Forms.ToolStripLayoutStyle.Flow; + ``` + +## See also + +- +- +- +- +- +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-choose-folders-with-the-windows-forms-folderbrowserdialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-choose-folders-with-the-windows-forms-folderbrowserdialog-component.md new file mode 100644 index 0000000000..d44c890a00 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-choose-folders-with-the-windows-forms-folderbrowserdialog-component.md @@ -0,0 +1,69 @@ +--- +title: Choose Folders with FolderBrowserDialog Component +description: Learn how to use the Windows Forms FolderBrowserDialog component within Windows applications you create to prompt users to select a folder. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "directories [Windows Forms], choosing" + - "FolderBrowserDialog component [Windows Forms], choosing directories" + - "folders [Windows Forms], selecting" + - "folders [Windows Forms], choosing" + - "directories [Windows Forms], selecting" +ms.assetid: 4593670e-7c7d-4661-b46b-4ffb63258adb +--- +# How to: Choose Folders with the Windows Forms FolderBrowserDialog Component + +Often, within Windows applications you create, you will have to prompt users to select a folder, most frequently to save a set of files. The Windows Forms component allows you to easily accomplish this task. + +### To choose folders with the FolderBrowserDialog component + +1. In a procedure, check the component's property to see how the dialog box was closed and get the value of the component's property. + +2. If you need to set the top-most folder that will appear within the tree view of the dialog box, set the property, which takes a member of the enumeration. + +3. Additionally, you can set the property, which specifies the text string that appears at the top of the folder-browser tree view. + + In the example below, the component is used to select a folder, similar to when you create a project in Visual Studio and are prompted to select a folder to save it in. In this example, the folder name is then displayed in a control on the form. It is a good idea to place the location in an editable area, such as a control, so that users may edit their selection in case of error or other issues. This example assumes a form with a component and a control. + + ```vb + Public Sub ChooseFolder() + If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then + TextBox1.Text = FolderBrowserDialog1.SelectedPath + End If + End Sub + ``` + + ```csharp + public void ChooseFolder() + { + if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) + { + textBox1.Text = folderBrowserDialog1.SelectedPath; + } + } + ``` + + ```cpp + public: + void ChooseFolder() + { + if (folderBrowserDialog1->ShowDialog() == DialogResult::OK) + { + textBox1->Text = folderBrowserDialog1->SelectedPath; + } + } + ``` + + > [!IMPORTANT] + > To use this class, your assembly requires a privilege level granted by the property, which is part of the enumeration. If you are running in a partial-trust context, the process might throw an exception because of insufficient privileges. For more information, see [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics). + +For information on how to save files, see [How to: Save Files Using the SaveFileDialog Component](how-to-save-files-using-the-savefiledialog-component.md). + +## See also + +- +- [FolderBrowserDialog Component Overview (Windows Forms)](folderbrowserdialog-component-overview-windows-forms.md) +- [FolderBrowserDialog Component](folderbrowserdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-configure-contextmenustrip-check-margins-and-image-margins.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-configure-contextmenustrip-check-margins-and-image-margins.md new file mode 100644 index 0000000000..d1c64e7ddd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-configure-contextmenustrip-check-margins-and-image-margins.md @@ -0,0 +1,34 @@ +--- +title: "How to: Configure ContextMenuStrip Check Margins and Image Margins" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "context menus [Windows Forms], configuring check and image margins" + - "ContextMenuStrips [Windows Forms], configuring check and image margins" + - "margins [Windows Forms], setting check and image in Windows Forms ContextMenuStrips" +ms.assetid: 3391c4c2-0c9e-4aa4-9492-13ff7644bdf2 +--- +# How to: Configure ContextMenuStrip Check Margins and Image Margins +You can customize a by setting the and properties in various combinations. + +## Example + The following code example demonstrates how to set and customize the check and image margins. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#60](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#60)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#60](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#60)] + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) +- [How to: Enable Check Margins and Image Margins in ContextMenuStrip Controls](how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-configure-menustrip-check-margins-and-image-margins.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-configure-menustrip-check-margins-and-image-margins.md new file mode 100644 index 0000000000..8b3f282a27 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-configure-menustrip-check-margins-and-image-margins.md @@ -0,0 +1,33 @@ +--- +title: "How to: Configure MenuStrip Check Margins and Image Margins" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "margins [Windows Forms], setting in MenuStrip controls" + - "menus [Windows Forms], setting margins" + - "MenuStrip control [Windows Forms], configuring check and image margins" +ms.assetid: 45a9075d-4bea-4ce2-9b2c-7619aa39f8ce +--- +# How to: Configure MenuStrip Check Margins and Image Margins +You can customize a by setting the and properties in various combinations. + +## Example + The following code example demonstrates how to set and customize the check margins and image margins. The procedure is the same for a or a . + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#60](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#60)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#60](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#60)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) +- [How to: Enable Check Margins and Image Margins in ContextMenuStrip Controls](how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md new file mode 100644 index 0000000000..de6fe59f2d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md @@ -0,0 +1,67 @@ +--- +title: Control the Insertion Point in TextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "TextBox control [Windows Forms], insertion point" + - "insertion points [Windows Forms], TextBox controls" + - "text boxes [Windows Forms], controlling insertion point" +ms.assetid: 5bee7d34-5121-429e-ab1f-d8ff67bc74c1 +--- +# How to: Control the Insertion Point in a Windows Forms TextBox Control +When a Windows Forms control first receives the focus, the default insertion within the text box is to the left of any existing text. The user can move the insertion point with the keyboard or the mouse. If the text box loses and then regains the focus, the insertion point will be wherever the user last placed it. + + In some cases, this behavior can be disconcerting to the user. In a word processing application, the user might expect new characters to appear after any existing text. In a data entry application, the user might expect new characters to replace any existing entry. The and properties enable you to modify the behavior to suit your purpose. + +### To control the insertion point in a TextBox control + +1. Set the property to an appropriate value. Zero places the insertion point immediately to the left of the first character. + +2. (Optional) Set the property to the length of the text you want to select. + + The code below always returns the insertion point to 0. The `TextBox1_Enter` event handler must be bound to the control; for more information, see [Creating Event Handlers in Windows Forms](../creating-event-handlers-in-windows-forms.md). + + ```vb + Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter + TextBox1.SelectionStart = 0 + TextBox1.SelectionLength = 0 + End Sub + ``` + + ```csharp + private void textBox1_Enter(Object sender, System.EventArgs e) { + textBox1.SelectionStart = 0; + textBox1.SelectionLength = 0; + } + ``` + + ```cpp + private: + void textBox1_Enter(System::Object ^ sender, + System::EventArgs ^ e) + { + textBox1->SelectionStart = 0; + textBox1->SelectionLength = 0; + } + ``` + +## Making the Insertion Point Visible by Default + The insertion point is visible by default in a new form only if the control is first in the tab order. Otherwise, the insertion point appears only if you give the the focus with either the keyboard or the mouse. + +#### To make the text box insertion point visible by default on a new form + +- Set the control's property to `0`. + +## See also + +- +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) +- [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) +- [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) +- [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) +- [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) +- [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-copy-toolstripmenuitems.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-copy-toolstripmenuitems.md new file mode 100644 index 0000000000..eddc5744ae --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-copy-toolstripmenuitems.md @@ -0,0 +1,43 @@ +--- +title: "How to: Copy ToolStripMenuItems" +ms.date: "03/30/2017" +helpviewer_keywords: + - "menu items [Windows Forms], copying and pasting" + - "MenuStrip control [Windows Forms], arranging items" + - "ToolStripMenuItems [Windows Forms], copying and pasting" +ms.assetid: 17ef4207-e92e-4db2-b648-27246e6517ad +--- +# How to: Copy ToolStripMenuItems +At design time, you can copy entire top-level menus and their submenu items to a different place on the . You can also copy individual menu items between top-level menus or change the position of menu items within a menu. + +### To copy a top-level menu and its submenu items to another top-level location + +1. Left-click the menu that you want to copy and press CTRL+C, or right-click the menu and select **Copy** from the shortcut menu. + +2. Left-click the top-level menu that is after the intended new location and press CTRL+V, or right-click the top-level menu item that is before the intended new location and select **Paste** from the shortcut menu. + + The menu that you copied is inserted before the selected top-level menu. + +### To copy a top-level menu and its submenu items to a drop-down location + +1. Left-click the menu that you want to move and press CTRL+C, or right-click the menu and select **Copy** from the shortcut menu. + +2. In the destination top-level menu, left-click the submenu item that is above the intended new location and press CTRL+V, or right-click the submenu item that is above the intended new location and select **Paste** from the shortcut menu. + + The menu that you copied is inserted before the selected submenu item. + +### To copy a submenu item to another menu + +1. Left-click the submenu item that you want to copy and press CTRL+C, or right-click the submenu item and choose **Copy** from the shortcut menu. + +2. Left-click the menu that will contain the submenu item that you cut. + +3. Left-click the submenu item that is before the intended new location and press CTRL+V, or right-click the submenu item that is before the intended new location and select **Paste** from the shortcut menu. + + The submenu item that you copied is inserted before the selected submenu item. + +## See also + +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-border-around-a-windows-forms-control-using-padding.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-border-around-a-windows-forms-control-using-padding.md new file mode 100644 index 0000000000..898909662e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-border-around-a-windows-forms-control-using-padding.md @@ -0,0 +1,28 @@ +--- +title: Create Border Around a Control Using Padding +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "margins" + - "controls [Windows Forms], Margin property" + - "padding [Windows Forms], Windows Forms" + - "controls [Windows Forms], Padding property" + - "controls [Windows Forms], outlining" + - "Padding property [Windows Forms]" + - "margins [Windows Forms], Windows Forms" + - "Margin property [Windows Forms]" +ms.assetid: bac7ed4d-a163-4259-98bd-155a36345890 +--- +# How to: Create a Border Around a Windows Forms Control Using Padding +The following code example demonstrates how to create a border or outline around a control. The example sets the value of a control’s property to 5 and sets the property of a child control to . The of the control is set to , which creates a blue border around the control. + +## Example + [!code-csharp[System.Windows.Forms.Padding#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Padding/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.Padding#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Padding/VB/Form1.vb#1)] + +## See also + +- +- [Margin and Padding in Windows Forms Controls](margin-and-padding-in-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-lookup-table-with-the-windows-forms-bindingsource-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-lookup-table-with-the-windows-forms-bindingsource-component.md new file mode 100644 index 0000000000..6e8c712cdc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-lookup-table-with-the-windows-forms-bindingsource-component.md @@ -0,0 +1,93 @@ +--- +title: Create a Lookup Table with BindingSource Component +ms.date: "03/30/2017" +helpviewer_keywords: + - "lookup tables" + - "tables [Windows Forms], creating lookup tables" + - "BindingSource component [Windows Forms], creating a lookup table" + - "BindingSource component [Windows Forms], examples" +ms.assetid: 622fce80-879d-44be-abbf-8350ec22ca2b +--- +# How to: Create a Lookup Table with the Windows Forms BindingSource Component +A lookup table is a table of data that has a column that displays data from records in a related table. In the following procedures, a control is used to display the field with the foreign-key relationship from the parent to the child table. + + To help visualize these two tables and this relationship, here is an example of a parent and child table: + + CustomersTable (parent table) + +|CustomerID|CustomerName| +|----------------|------------------| +|712|Paul Koch| +|713|Tamara Johnston| + + OrdersTable (child table) + +|OrderID|OrderDate|CustomerID| +|-------------|---------------|----------------| +|903|February 12, 2004|712| +|904|February 13, 2004|713| + + In this scenario, one table, CustomersTable, stores the actual information you want to display and save. But to save space, the table leaves out data that adds clarity. The other table, OrdersTable, contains only appearance-related information about which customer ID number is equivalent to which order date and order ID. There is no mention of the customers' names. + + Four important properties are set on the [ComboBox Control](combobox-control-windows-forms.md) control to create the lookup table. + +- The property contains the name of the table. + +- The property contains the data column of that table that you want to display for the control text (the customer's name). + +- The property contains the data column of that table with the stored information (the ID number in the parent table). + +- The property provides the lookup value for the child table, based on the . + + The procedures below show you how to lay out your form as a lookup table and bind data to the controls on it. To successfully complete the procedures, you must have a data source with parent and child tables that have a foreign-key relationship, as mentioned previously. + +### To create the user interface + +1. From the **ToolBox**, drag a control onto the form. + + This control will display the column from parent table. + +2. Drag other controls to display details from the child table. The format of the data in the table should determine which controls you choose. For more information, see [Windows Forms Controls by Function](windows-forms-controls-by-function.md). + +3. Drag a control onto the form; this will allow you to navigate the data in the child table. + +### To connect to the data and bind it to controls + +1. Select the and click the Smart Task glyph to display the Smart Task dialog box. + +2. Select **Use data bound items**. + +3. Click the arrow next to the **Data Source** drop-down box. If a data source has previously been configured for the project or form, it will appear; otherwise, complete the following steps (This example uses the Customers and Orders tables of the Northwind sample database and refers to them in parentheses). + + 1. Click **Add Project Data Source** to connect to data and create a data source. + + 2. On the **Data Source Configuration Wizard** welcome page, click **Next**. + + 3. Select **Database** on the **Choose a Data Source Type** page. + + 4. Select a data connection from the list of available connections on the **Choose Your Data Connection** page. If your desired data connection is not available, select **New Connection** to create a new data connection. + + 5. Click **Yes, save the connection** to save the connection string in the application configuration file. + + 6. Select the database objects to bring into your application. In this case, select a parent table and child table (for example, Customers and Orders) with a foreign key relationship. + + 7. Replace the default dataset name if you want. + + 8. Click **Finish**. + +4. In the **Display Member** drop-down box, select the column name (for example, ContactName) to be displayed in the combo box. + +5. In the **Value Member** drop-down box, select the column (for example, CustomerID) to perform the lookup operation in the child table. + +6. In the **Selected Value** drop-down box, navigate to **Project Data Sources** and the dataset you just created that contains the parent and child tables. Select the same property of the child table that is the Value Member of the parent table (for example, Orders.CustomerID). The appropriate , data set, and table adapter components will be created and added to the form. + +7. Bind the control to the of the child table (for example, `OrdersBindingSource`). + +8. Bind the controls other than the and control to the details fields from the child table's (for example, `OrdersBindingSource`) that you want to display. + +## See also + +- +- [BindingSource Component](bindingsource-component.md) +- [ComboBox Control](combobox-control-windows-forms.md) +- [Bind controls to data in Visual Studio](/visualstudio/data-tools/bind-controls-to-data-in-visual-studio) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-multipane-user-interface-with-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-multipane-user-interface-with-windows-forms.md new file mode 100644 index 0000000000..6e1039d55c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-multipane-user-interface-with-windows-forms.md @@ -0,0 +1,177 @@ +--- +title: Create a Multipane User Interface +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "SplitContainer control [Windows Forms], examples" + - "ListView control [Windows Forms], examples" + - "RichTextBox control [Windows Forms], examples" + - "Panel control [Windows Forms], examples" + - "TreeView control [Windows Forms], examples" + - "Splitter control [Windows Forms], examples" +ms.assetid: e79f6bcc-3740-4d1e-b46a-c5594d9b7327 +--- +# How to: Create a Multipane User Interface with Windows Forms +In the following procedure, you will create a multipane user interface that is similar to the one used in Microsoft Outlook, with a **Folder** list, a **Messages** pane, and a **Preview** pane. This arrangement is achieved chiefly through docking controls with the form. + + When you dock a control, you determine which edge of the parent container a control is fastened to. Thus, if you set the property to , the right edge of the control will be docked to the right edge of its parent control. Additionally, the docked edge of the control is resized to match that of its container control. For more information about how the property works, see [How to: Dock Controls on Windows Forms](how-to-dock-controls-on-windows-forms.md). + + This procedure focuses on arranging the and the other controls on the form, not on adding functionality to make the application mimic Microsoft Outlook. + + To create this user interface, you place all the controls within a control, which contains a control in the left-hand panel. The right-hand panel of the control contains a second control with a control above a control. These controls enable independent resizing of the other controls on the form. You can adapt the techniques in this procedure to craft custom user interfaces of your own. + +### To create an Outlook-style user interface programmatically + +1. Within a form, declare each control that comprises your user interface. For this example, use the , , , and controls to mimic the Microsoft Outlook user interface. + + ```vb + Private WithEvents treeView1 As System.Windows.Forms.TreeView + Private WithEvents listView1 As System.Windows.Forms.ListView + Private WithEvents richTextBox1 As System.Windows.Forms.RichTextBox + Private WithEvents splitContainer1 As _ + System.Windows.Forms.SplitContainer + Private WithEvents splitContainer2 As _ + System.Windows.Forms.SplitContainer + ``` + + ```csharp + private System.Windows.Forms.TreeView treeView1; + private System.Windows.Forms.ListView listView1; + private System.Windows.Forms.RichTextBox richTextBox1; + private System.Windows.Forms. SplitContainer splitContainer2; + private System.Windows.Forms. SplitContainer splitContainer1; + ``` + +2. Create a procedure that defines your user interface. The following code sets the properties so that the form will resemble the user interface in Microsoft Outlook. However, by using other controls or docking them differently, it is just as easy to create other user interfaces that are equally flexible. + + ```vb + Public Sub CreateOutlookUI() + ' Create an instance of each control being used. + Me.components = New System.ComponentModel.Container() + Me.treeView1 = New System.Windows.Forms.TreeView() + Me.listView1 = New System.Windows.Forms.ListView() + Me.richTextBox1 = New System.Windows.Forms.RichTextBox() + Me.splitContainer1 = New System.Windows.Forms.SplitContainer() + Me.splitContainer2= New System.Windows.Forms. SplitContainer() + + ' Should you develop this into a working application, + ' use the AddHandler method to hook up event procedures here. + + ' Set properties of TreeView control. + ' Use the With statement to avoid repetitive code. + With Me.treeView1 + .Dock = System.Windows.Forms.DockStyle.Fill + .TabIndex = 0 + .Nodes.Add("treeView") + End With + + ' Set properties of ListView control. + With Me.listView1 + .Dock = System.Windows.Forms.DockStyle.Top + .TabIndex = 2 + .Items.Add("listView") + End With + + ' Set properties of RichTextBox control. + With Me.richTextBox1 + .Dock = System.Windows.Forms.DockStyle.Fill + .TabIndex = 3 + .Text = "richTextBox1" + End With + + ' Set properties of the first SplitContainer control. + With Me.splitContainer1 + .Dock = System.Windows.Forms.DockStyle.Fill + .TabIndex = 1 + .SplitterWidth = 4 + .SplitterDistance = 150 + .Orientation = Orientation.Horizontal + .Panel1.Controls.Add(Me.listView1) + .Panel2.Controls.Add(Me.richTextBox1) + End With + + ' Set properties of the second SplitContainer control. + With Me.splitContainer2 + .Dock = System.Windows.Forms.DockStyle.Fill + .TabIndex = 4 + .SplitterWidth = 4 + .SplitterDistance = 100 + .Panel1.Controls.Add(Me.treeView1) + .Panel2.Controls.Add(Me.SplitContainer1) + End With + + ' Add the main SplitContainer control to the form. + Me.Controls.Add(Me.splitContainer2) + Me.Text = "Intricate UI Example" + End Sub + ``` + + ```csharp + public void createOutlookUI() + { + // Create an instance of each control being used. + treeView1 = new System.Windows.Forms.TreeView(); + listView1 = new System.Windows.Forms.ListView(); + richTextBox1 = new System.Windows.Forms.RichTextBox(); + splitContainer2 = new System.Windows.Forms.SplitContainer(); + splitContainer1 = new System.Windows.Forms.SplitContainer(); + + // Insert code here to hook up event methods. + + // Set properties of TreeView control. + treeView1.Dock = System.Windows.Forms.DockStyle.Fill; + treeView1.TabIndex = 0; + treeView1.Nodes.Add("treeView"); + + // Set properties of ListView control. + listView1.Dock = System.Windows.Forms.DockStyle.Top; + listView1.TabIndex = 2; + listView1.Items.Add("listView"); + + // Set properties of RichTextBox control. + richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; + richTextBox1.TabIndex = 3; + richTextBox1.Text = "richTextBox1"; + + // Set properties of first SplitContainer control. + splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; + splitContainer2.TabIndex = 1; + splitContainer2.SplitterWidth = 4; + splitContainer2.SplitterDistance = 150; + splitContainer2.Orientation = Orientation.Horizontal; + splitContainer2.Panel1.Controls.Add(this.listView1); + splitContainer2.Panel1.Controls.Add(this.richTextBox1); + + // Set properties of second SplitContainer control. + splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; + splitContainer2.TabIndex = 4; + splitContainer2.SplitterWidth = 4; + splitContainer2.SplitterDistance = 100; + splitContainer2.Panel1.Controls.Add(this.treeView1); + splitContainer2.Panel1.Controls.Add(this.splitContainer1); + + // Add the main SplitContainer control to the form. + this.Controls.Add(this.splitContainer2); + this.Text = "Intricate UI Example"; + } + ``` + +3. In Visual Basic, add a call to the procedure you just created in the `New()` procedure. In Visual C#, add this line of code to the constructor for the form class. + + ```vb + ' Add this to the New procedure. + CreateOutlookUI() + ``` + + ```csharp + // Add this to the form class's constructor. + createOutlookUI(); + ``` + +## See also + +- +- [SplitContainer Control](splitcontainer-control-windows-forms.md) +- [How to: Create a Multipane User Interface with Windows Forms Using the Designer](create-a-multipane-user-interface-with-wf-using-the-designer.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md new file mode 100644 index 0000000000..495dbdc132 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md @@ -0,0 +1,79 @@ +--- +title: Create a Password Text Box with TextBox Control +description: Learn how to cerate a Windows Forms text that displays placeholder characters while a user types a string. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "TextBox control [Windows Forms], entering passwords" + - "password boxes [Windows Forms], creating" + - "PasswordChar property in text boxes" + - "passwords [Windows Forms], input mask" + - "passwords [Windows Forms], password text box" +ms.assetid: d105d6b9-3d50-44cd-80d8-2c0e2f486727 +--- +# How to: Create a Password Text Box with the Windows Forms TextBox Control + +A password box is a Windows Forms text box that displays placeholder characters while a user types a string. + +### To create a password text box + +1. Set the property of the control to a specific character. + + The property specifies the character displayed in the text box. For example, if you want asterisks displayed in the password box, specify * for the property in the Properties window. Then, regardless of what character a user types in the text box, an asterisk is displayed. + +2. (Optional) Set the property. The property determines how many characters can be typed in the text box. If the maximum length is exceeded, the system emits a beep and the text box does not accept any more characters. Note that you may not wish to do this as the maximum length of a password may be of use to hackers who are trying to guess the password. + + The following code example shows how to initialize a text box that will accept a string up to 14 characters long and display asterisks in place of the string. The `InitializeMyControl` procedure will not execute automatically; it must be called. + + > [!IMPORTANT] + > Using the property on a text box can help ensure that other people will not be able to determine a user's password if they observe the user entering it. This security measure does not cover any sort of storage or transmission of the password that can occur due to your application logic. Because the text entered is not encrypted in any way, you should treat it as you would any other confidential data. Even though it does not appear as such, the password is still being treated as a plain-text string (unless you have implemented some additional security measure). + + ```vb + Private Sub InitializeMyControl() + ' Set to no text. + TextBox1.Text = "" + ' The password character is an asterisk. + TextBox1.PasswordChar = "*" + ' The control will allow no more than 14 characters. + TextBox1.MaxLength = 14 + End Sub + ``` + + ```csharp + private void InitializeMyControl() + { + // Set to no text. + textBox1.Text = ""; + // The password character is an asterisk. + textBox1.PasswordChar = '*'; + // The control will allow no more than 14 characters. + textBox1.MaxLength = 14; + } + ``` + + ```cpp + private: + void InitializeMyControl() + { + // Set to no text. + textBox1->Text = ""; + // The password character is an asterisk. + textBox1->PasswordChar = '*'; + // The control will allow no more than 14 characters. + textBox1->MaxLength = 14; + } + ``` + +## See also + +- +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) +- [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) +- [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) +- [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) +- [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) +- [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-professionally-styled-toolstrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-professionally-styled-toolstrip-control.md new file mode 100644 index 0000000000..20664fcca3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-professionally-styled-toolstrip-control.md @@ -0,0 +1,38 @@ +--- +title: "How to: Create a Professionally Styled ToolStrip Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStripProfessionalRenderer class [Windows Forms]" + - "ToolStripRenderer class [Windows Forms]" + - "ToolStrip control [Windows Forms]" +ms.assetid: c208b2f6-8105-474b-9075-d582e1792870 +--- +# How to: Create a Professionally Styled ToolStrip Control +You can give your application’s controls a professional appearance and behavior (look and feel) by writing your own class derived from the type. + + There is extensive support for this feature in Visual Studio. + + See [Walkthrough: Creating a Professionally Styled ToolStrip Control](walkthrough-creating-a-professionally-styled-toolstrip-control.md). + +## Example + The following code example demonstrates how to use controls to create a composite control that mimics the **Navigation Pane** provided by Microsoft® Outlook®. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) +- [How to: Provide Standard Menu Items to a Form](how-to-provide-standard-menu-items-to-a-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-read-only-text-box-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-read-only-text-box-windows-forms.md new file mode 100644 index 0000000000..308c392faa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-read-only-text-box-windows-forms.md @@ -0,0 +1,31 @@ +--- +title: "How to: Create a Read-Only Text Box" +description: Learn about transforming an editable Windows Forms text box into a read-only Windows Forms text box. +ms.date: "03/30/2017" +helpviewer_keywords: + - "TextBox control [Windows Forms], read-only" + - "read-only text boxes" + - "text boxes [Windows Forms], read-only" +ms.assetid: 60baa9ab-fa57-44ad-bb7c-61b05aa64296 +--- +# How to: Create a Read-Only Text Box (Windows Forms) + +You can transform an editable Windows Forms text box into a read-only control. For example, the text box may display a value that is usually edited but may not be currently, due to the state of the application. + +## To create a read-only text box + +1. Set the control's property to `true`. With the property set to `true`, users can still scroll and highlight text in a text box without allowing changes. A **Copy** command is functional in a text box, but **Cut** and **Paste** commands are not. + + > [!NOTE] + > The property only affects user interaction at run time. You can still change text box contents programmatically at run time by changing the property of the text box. + +## See also + +- +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) +- [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) +- [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) +- [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) +- [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) +- [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-resizable-windows-form-for-data-entry.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-resizable-windows-form-for-data-entry.md new file mode 100644 index 0000000000..1cb45c9ccb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-resizable-windows-form-for-data-entry.md @@ -0,0 +1,35 @@ +--- +title: "How to: Create a Resizable Windows Form for Data Entry" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "TableLayoutPanel control [Windows Forms]" + - "layout [Windows Forms], resizing" + - "forms [Windows Forms], creating resizable" + - "Windows Forms, resizable" +ms.assetid: babdf198-404c-485d-a914-ed370c6ecd99 +--- +# How to: Create a Resizable Windows Form for Data Entry +A good layout responds well to changes in the dimensions of its parent form. You can use the control to arrange the layout of your form to resize and position your controls in a consistent way as the form's dimensions change. The control is also useful when changes in the contents of your controls cause changes in the layout. The process covered in this procedure can be done within the Visual Studio environment. Also see [Walkthrough: Creating a Resizable Windows Form for Data Entry](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/991eahec(v=vs.100)). + +## Example + The following example demonstrates how to use a control to build a layout that responds well when the user resizes the form. It also demonstrates a layout that responds well to localization. + + [!code-cpp[System.Windows.Forms.TableLayoutPanel.DataEntryForm#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/basicdataentryform.cpp#1)] + [!code-csharp[System.Windows.Forms.TableLayoutPanel.DataEntryForm#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/CS/basicdataentryform.cs#1)] + [!code-vb[System.Windows.Forms.TableLayoutPanel.DataEntryForm#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/VB/basicdataentryform.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) +- [How to: Design a Windows Forms Layout that Responds Well to Localization](how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-windows-explorer-style-interface-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-windows-explorer-style-interface-on-a-windows-form.md new file mode 100644 index 0000000000..227a7788db --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-windows-explorer-style-interface-on-a-windows-form.md @@ -0,0 +1,49 @@ +--- +title: "How to: Create a Windows Explorer–Style Interface on a Windows Form" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Explorer [Windows Forms], creating with Windows Forms" + - "SplitContainer control [Windows Forms], Explorer-style interface" + - "forms [Windows Forms], Windows Explorer type" +ms.assetid: 9a3d5f4f-5dda-4350-9ad5-57ce5976dc47 +--- +# How to: Create a Windows Explorer–Style Interface on a Windows Form +Windows Explorer is a common user-interface choice for applications because of its ready familiarity. + + Windows Explorer is, essentially, a control and a control on separate panels. The panels are made resizable by a splitter. This arrangement of controls is very effective for displaying and browsing information. + + The following steps show how to arrange controls in a Windows Explorer-like form. They do not show how to add the file-browsing functionality of the Windows Explorer application. + +## To create a Windows Explorer-style Windows Form + +1. Create a new Windows Application project (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. From the **Toolbox**: + + 1. Drag a control onto your form. + + 2. Drag a control into **SplitterPanel1** (the panel of the control marked **Panel1**). + + 3. Drag a control into **SplitterPanel2** (the panel of the control marked **Panel2**). + +3. Select all three controls by pressing the CTRL key and clicking them in turn. When you select the control, click the splitter bar, rather than the panels. + + > [!NOTE] + > Do not use the **Select All** command on the **Edit** menu. If you do so, the property needed in the next step will not appear in the **Properties** window. + +4. In the **Properties** window, set the property to . + +5. Press F5 to run the application. + + The form displays a two-part user interface, similar to that of the Windows Explorer. + + > [!NOTE] + > When you drag the splitter, the panels resize themselves. + +## See also + +- +- [How to: Create a Multipane User Interface with Windows Forms](how-to-create-a-multipane-user-interface-with-windows-forms.md) +- [How to: Define Resize and Positioning Behavior in a Split Window](how-to-define-resize-and-positioning-behavior-in-a-split-window.md) +- [How to: Split a Window Horizontally](how-to-split-a-window-horizontally.md) +- [SplitContainer Control](splitcontainer-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-windows-forms-control-that-shows-progress.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-windows-forms-control-that-shows-progress.md new file mode 100644 index 0000000000..e192599c6f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-a-windows-forms-control-that-shows-progress.md @@ -0,0 +1,92 @@ +--- +title: Create Control That Shows Progress +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], progress tracking" + - "controls [Windows Forms], creating" + - "progress [Windows Forms], reporting [Windows Forms]" + - "FlashTrackBar custom control" +ms.assetid: 24c5a2e3-058c-4b8d-a217-c06e6a130c2f +--- +# How to: Create a Windows Forms Control That Shows Progress +The following code example shows a custom control called `FlashTrackBar` that can be used to show the user the level or the progress of an application. It uses a gradient to visually represent progress. + + The `FlashTrackBar` control illustrates the following concepts: + +- Defining custom properties. + +- Defining custom events. (`FlashTrackBar` defines the `ValueChanged` event.) + +- Overriding the method to provide logic to draw the control. + +- Computing the area available for drawing the control by using its property. `FlashTrackBar` does this in its `OptimizedInvalidate` method. + +- Implementing serialization or persistence for a property when it is changed in the Windows Forms Designer. `FlashTrackBar` defines the `ShouldSerializeStartColor` and `ShouldSerializeEndColor` methods for serializing its `StartColor` and `EndColor` properties. + + The following table shows the custom properties defined by `FlashTrackBar`. + +|Property|Description| +|--------------|-----------------| +|`AllowUserEdit`|Indicates whether the user can change the value of the flash track bar by clicking and dragging it.| +|`EndColor`|Specifies the ending color of the track bar.| +|`DarkenBy`|Specifies how much to darken the background with respect to the foreground gradient.| +|`Max`|Specifies the maximum value of the track bar.| +|`Min`|Specifies the minimum value of the track bar.| +|`StartColor`|Specifies the starting color of the gradient.| +|`ShowPercentage`|Indicates whether to display a percentage over the gradient.| +|`ShowValue`|Indicates whether to display the current value over the gradient.| +|`ShowGradient`|Indicates whether the track bar should display a color gradient showing the current value.| +|- `Value`|Specifies the current value of the track bar.| + + The following table shows additional members defined by `FlashTrackBar:` the property-changed event and the method that raises the event. + +|Member|Description| +|------------|-----------------| +|`ValueChanged`|The event that is raised when the `Value` property of the track bar changes.| +|`OnValueChanged`|The method that raises the `ValueChanged` event.| + +> [!NOTE] +> `FlashTrackBar` uses the class for event data and for the event delegate. + + To handle the corresponding *EventName* events, `FlashTrackBar` overrides the following methods that it inherits from : + +- + +- + +- + +- + +- + + To handle the corresponding property-changed events, `FlashTrackBar` overrides the following methods that it inherits from : + +- + +- + +- + +## Example + The `FlashTrackBar` control defines two UI type editors, `FlashTrackBarValueEditor` and `FlashTrackBarDarkenByEditor`, which are shown in the following code listings. The `HostApp` class uses the `FlashTrackBar` control on a Windows Form. + + [!code-csharp[System.Windows.Forms.FlashTrackBar#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#1)] + [!code-vb[System.Windows.Forms.FlashTrackBar#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#1)] + + [!code-csharp[System.Windows.Forms.FlashTrackBar#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarDarkenByEditor.cs#10)] + [!code-vb[System.Windows.Forms.FlashTrackBar#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarDarkenByEditor.vb#10)] + + [!code-csharp[System.Windows.Forms.FlashTrackBar#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarValueEditor.cs#20)] + [!code-vb[System.Windows.Forms.FlashTrackBar#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarValueEditor.vb#20)] + + [!code-csharp[System.Windows.Forms.FlashTrackBar#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/HostApp.cs#30)] + [!code-vb[System.Windows.Forms.FlashTrackBar#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/HostApp.vb#30)] + +## See also + +- [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)) +- [Windows Forms Control Development Basics](windows-forms-control-development-basics.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys-for-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys-for-windows-forms-controls.md new file mode 100644 index 0000000000..515a679a73 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys-for-windows-forms-controls.md @@ -0,0 +1,61 @@ +--- +title: Create Access Keys for Controls +ms.date: 08/20/2019 +dev_langs: + - "csharp" + - "vb" + - "cpp" +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 [Windows Forms], adding to dialog box 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" +ms.assetid: 4faa0991-28ec-4eca-91db-51dc2cd6a7ac +--- +# How to: Create access keys for Windows Forms controls + +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+P. + +Controls that cannot receive focus can't have access keys. + +## 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"; +``` + +```cpp +// Set the letter "P" as an access key. +button1->Text = "&Print"; +``` + +> [!NOTE] +> To use an ampersand in a caption without creating an access key, include two ampersands (&&). A single ampersand is displayed in the caption and no characters are underlined. + +## 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**. + +## See also + +- +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys-with-windows-forms-label-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys-with-windows-forms-label-controls.md new file mode 100644 index 0000000000..208862127d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-access-keys-with-windows-forms-label-controls.md @@ -0,0 +1,64 @@ +--- +title: Create Access Keys with Label Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "controls [Windows Forms], access keys" + - "dialog box controls [Windows Forms], mnemonics" + - "access keys [Windows Forms], creating for controls" + - "Label control [Windows Forms], creating access keys" + - "mnemonics [Windows Forms], adding to dialog box controls" + - "mnemonics" + - "Windows Forms controls, access keys" + - "UseMnemonic property [Windows Forms], Label control" + - "keyboard shortcuts [Windows Forms], creating for controls" + - "access keys [Windows Forms], Windows Forms" +ms.assetid: 5ee8f823-80be-4a4f-96a4-412671e2e306 +--- +# How to: Create Access Keys with Windows Forms Label Controls +Windows Forms controls can be used to define access keys for other controls. When you define an access key in a label control, the user can press the ALT key plus the character you designate to move the focus to the control that follows it in the tab order. Because labels cannot receive focus, focus automatically moves to the next control in the tab order. Use this technique to assign access keys to text boxes, combo boxes, list boxes, and data grids. + +### To assign an access key to a control with a label + +1. Draw the label first, and then draw the other control. + + -or- + + Draw the controls in any order and set the property of the label to one less than the other control. + +2. Set the label's property to `true`. + +3. Use an ampersand (&) in the label's property to assign the access key for the label. For more information, see [Creating Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md). + + > [!NOTE] + > You may want to display ampersands in a label control, rather than use them to create access keys. This may occur if you bind a label control to a field in a recordset where the data includes ampersands. To display ampersands in a label control, set the property to `false`. If you wish to display ampersands and also have an access key, set the property to `true` and indicate the access key with one ampersand (&) and the ampersand to display with two ampersands. + + ```vb + Label1.UseMnemonic = True + Label1.Text = "&Print" + Label2.UseMnemonic = True + Label2.Text = "&Copy && Paste" + ``` + + ```csharp + label1.UseMnemonic = true; + label1.Text = "&Print"; + label2.UseMnemonic = true; + label2.Text = "&Copy && Paste"; + ``` + + ```cpp + label1->UseMnemonic = true; + label1->Text = "&Print"; + label2->UseMnemonic = true; + label2->Text = "&Copy && Paste"; + ``` + +## See also + +- [How to: Size a Windows Forms Label Control to Fit Its Contents](how-to-size-a-windows-forms-label-control-to-fit-its-contents.md) +- [Label Control Overview](label-control-overview-windows-forms.md) +- [Label Control](label-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-html-document-viewer-in-a-windows-forms-application.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-html-document-viewer-in-a-windows-forms-application.md new file mode 100644 index 0000000000..c1ccf764c0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-html-document-viewer-in-a-windows-forms-application.md @@ -0,0 +1,44 @@ +--- +title: Create an HTML Document Viewer in a Windows Forms app +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "WebBrowser control [Windows Forms], creating an HTML document viewer" + - "document viewers" + - "Windows Forms, creating document viewers" +ms.assetid: 6a6338fe-f7ee-4f5e-9d8f-0465c57e9039 +--- +# How to: Create an HTML Document Viewer in a Windows Forms Application +You can use the control to display and print HTML documents without providing the full functionality of an Internet Web browser. This is useful when you want to take advantage of the formatting capabilities of HTML but do not want your users to load arbitrary Web pages that may contain untrusted Web controls or potentially malicious script code. You might want to restrict the capability of the control in this manner, for example, to use it as an HTML email viewer or to provide HTML-formatted help in your application. + +### To create an HTML document viewer + +1. Set the property to `false` to prevent the control from opening files dropped onto it. + + [!code-csharp[WebBrowserMisc#20](~/samples/snippets/csharp/VS_Snippets_Winforms/WebBrowserMisc/CS/WebBrowserMisc.cs#20)] + [!code-vb[WebBrowserMisc#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WebBrowserMisc/vb/WebBrowserMisc.vb#20)] + +2. Set the property to the location of the initial file to display. + + [!code-csharp[WebBrowserMisc#21](~/samples/snippets/csharp/VS_Snippets_Winforms/WebBrowserMisc/CS/WebBrowserMisc.cs#21)] + [!code-vb[WebBrowserMisc#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WebBrowserMisc/vb/WebBrowserMisc.vb#21)] + +## Compiling the Code + This example requires: + +- A control named `webBrowser1`. + +- References to the `System` and `System.Windows.Forms` assemblies. + +## See also + +- +- +- +- [WebBrowser Control Overview](webbrowser-control-overview.md) +- [WebBrowser Security](webbrowser-security.md) +- [How to: Navigate to a URL with the WebBrowser Control](how-to-navigate-to-a-url-with-the-webbrowser-control.md) +- [How to: Print with a WebBrowser Control](how-to-print-with-a-webbrowser-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md new file mode 100644 index 0000000000..aae4b8631b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md @@ -0,0 +1,34 @@ +--- +title: "How to: Create an MDI Form with Menu Merging and ToolStrip Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStripPanel control [Windows Forms]" + - "ToolStrip control [Windows Forms]" + - "MenuStrip control [Windows Forms]" +ms.assetid: 64992ed9-44af-4baf-b45f-863e6ab35711 +--- +# How to: Create an MDI Form with Menu Merging and ToolStrip Controls +The namespace supports multiple document interface (MDI) applications, and the control supports menu merging. MDI forms can also controls. + + There is extensive support for this feature in Visual Studio. + + Also see [Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls](walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md). + +## Example + The following code example demonstrates how to use controls with an MDI form. The form also supports menu merging with child menus. + + [!code-csharp[System.Windows.Forms.ToolStrip.MdiForm#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.MdiForm#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/VB/Form1.vb#1)] + +## Compiling the Code + This code example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-form-with-toolstrippanel-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-form-with-toolstrippanel-controls.md new file mode 100644 index 0000000000..dfd81cdeab --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-form-with-toolstrippanel-controls.md @@ -0,0 +1,41 @@ +--- +title: "How to: Create an MDI Form with ToolStripPanel Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStripPanel control [Windows Forms]" + - "MDI [Windows Forms], creating forms" + - "multiple document interface forms" + - "MDI forms [Windows Forms]" + - "ToolStrip control [Windows Forms]" + - "MDI forms [Windows Forms], creating" +ms.assetid: d198ef8e-f7c4-4b3f-a7f5-ce858cb90cec +--- +# How to: Create an MDI Form with ToolStripPanel Controls +You can create a multiple document interface (MDI) form that has controls framing it on all four sides. + +## Example + The following code example demonstrates how to use docked controls to frame an MDI window with four controls. + + In the example, the method attaches the controls to the corresponding controls. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#10)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#10)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md new file mode 100644 index 0000000000..a69457de4e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md @@ -0,0 +1,82 @@ +--- +title: "How to: Create an MDI Window List with MenuStrip" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "MDI [Windows Forms], creating window lists" + - "MenuStrip control [Windows Forms], creating window lists" +ms.assetid: 04fb414b-811f-4a83-aab6-b4a24646dec5 +--- +# How to: Create an MDI Window List with MenuStrip (Windows Forms) +Use the multiple-document interface (MDI) to create applications that can open several documents at the same time and copy and paste content from one document to the other. + + This procedure shows you how to create a list of all the active child forms on the parent's Window menu. + +### To create an MDI Window list on a MenuStrip + +1. Create a form and set its property to `true`. + +2. Add a to the form. + +3. Add two top-level menu items to the and set their properties to `&File` and `&Window`. + +4. Add a submenu item to the `&File` menu item and set its property to `&Open`. + +5. Set the property of the to the `&Window`. + +6. Add a form to the project and add the control you want to it, such as another . + +7. Create an event handler for the event of the `&New`. + +8. Within the event handler, insert code similar to the following to create and display new instances of `Form2` as MDI children of `Form1`. + + ```vb + Private Sub openToolStripMenuItem_Click(ByVal sender As _ + System.Object, ByVal e As System.EventArgs) Handles _ + openToolStripMenuItem.Click + Dim NewMDIChild As New Form2() + 'Set the parent form of the child window. + NewMDIChild.MdiParent = Me + 'Display the new form. + NewMDIChild.Show() + End Sub + ``` + + ```csharp + private void newToolStripMenuItem_Click(object sender, EventArgs e) + { + Form2 newMDIChild = new Form2(); + // Set the parent form of the child window. + newMDIChild.MdiParent = this; + // Display the new form. + newMDIChild.Show(); + } + ``` + +9. Place code like the following in the `&New` to register the event handler. + + ```vb + Private Sub newToolStripMenuItem_Click(sender As Object, e As _ + EventArgs) Handles newToolStripMenuItem.Click + ``` + + ```csharp + this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); + ``` + +## Compiling the Code + This example requires: + +- Two controls named `Form1` and `Form2`. + +- A control on `Form1` named `menuStrip1`, and a control on `Form2` named `menuStrip2`. + +- References to the and assemblies. + +## See also + +- [How to: Create MDI Parent Forms](../advanced/how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](../advanced/how-to-create-mdi-child-forms.md) +- [MenuStrip Control](menustrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-unbound-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-unbound-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..aef2187a83 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-an-unbound-windows-forms-datagridview-control.md @@ -0,0 +1,32 @@ +--- +title: Create an Unbound DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], unbound data" + - "DataGridView control [Windows Forms], displaying data without binding to a data source" + - "data [Windows Forms], unbound" +ms.assetid: b5d4b47d-9a28-4d88-9dba-0a3c90fba71d +--- +# How to: Create an Unbound Windows Forms DataGridView Control +The following code example demonstrates how to populate a control programmatically without binding it to a data source. This is useful when you have a small amount of data that you want to display in a table format. + + For a complete explanation of this code example, see [Walkthrough: Creating an Unbound Windows Forms DataGridView Control](walkthrough-creating-an-unbound-windows-forms-datagridview-control.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- [Walkthrough: Creating an Unbound Windows Forms DataGridView Control](walkthrough-creating-an-unbound-windows-forms-datagridview-control.md) +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-master-detail-lists-with-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-master-detail-lists-with-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..c3f5c77dd4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-master-detail-lists-with-the-windows-forms-datagrid-control.md @@ -0,0 +1,71 @@ +--- +title: Create Master-Detail Lists with DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "master-details lists" + - "DataGrid control [Windows Forms], master-details lists" + - "related tables [Windows Forms], displaying in DataGrid control" +ms.assetid: 20388c6a-94f9-4d96-be18-8c200491247f +--- +# How to: Create Master/Detail Lists with the Windows Forms DataGrid Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + If your contains a series of related tables, you can use two controls to display the data in a master/detail format. One is designated to be the master grid, and the second is designated to be the details grid. When you select an entry in the master list, all of the related child entries are shown in the details list. For example, if your contains a Customers table and a related Orders table, you would specify the Customers table to be the master grid and the Orders table to be the details grid. When a customer is selected from the master grid, all of the orders associated with that customer in the Orders table would be displayed in the details grid. + +### To set a master/detail relationship programmatically + +1. Create two new controls and set their properties. + +2. Add tables to the dataset. + +3. Declare a variable of type to represent the relation you want to create. + +4. Instantiate the relationship by specifying a name for the relationship and specifying the table, column, and item that will tie the two tables. + +5. Add the relationship to the object's collection. + +6. Use the method of the to bind each of the grids to the . + + The following example shows how to set a master/detail relationship between the Customers and Orders tables in a previously generated (`ds`). + + ```vb + Dim myDataRelation As DataRelation + myDataRelation = New DataRelation _ + ("CustOrd", ds.Tables("Customers").Columns("CustomerID"), _ + ds.Tables("Orders").Columns("CustomerID")) + ' Add the relation to the DataSet. + ds.Relations.Add(myDataRelation) + GridOrders.SetDataBinding(ds, "Customers") + GridDetails.SetDataBinding(ds, "Customers.CustOrd") + ``` + + ```csharp + DataRelation myDataRelation; + myDataRelation = new DataRelation("CustOrd", ds.Tables["Customers"].Columns["CustomerID"], ds.Tables["Orders"].Columns["CustomerID"]); + // Add the relation to the DataSet. + ds.Relations.Add(myDataRelation); + GridOrders.SetDataBinding(ds,"Customers"); + GridDetails.SetDataBinding(ds,"Customers.CustOrd"); + ``` + + ```cpp + DataRelation^ myDataRelation; + myDataRelation = gcnew DataRelation("CustOrd", + ds->Tables["Customers"]->Columns["CustomerID"], + ds->Tables["Orders"]->Columns["CustomerID"]); + // Add the relation to the DataSet. + ds->Relations->Add(myDataRelation); + GridOrders->SetDataBinding(ds, "Customers"); + GridDetails->SetDataBinding(ds, "Customers.CustOrd"); + ``` + +## See also + +- [DataGrid Control](datagrid-control-windows-forms.md) +- [DataGrid Control Overview](datagrid-control-overview-windows-forms.md) +- [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-toggle-buttons-in-toolstrip-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-toggle-buttons-in-toolstrip-controls.md new file mode 100644 index 0000000000..0770d53040 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-toggle-buttons-in-toolstrip-controls.md @@ -0,0 +1,36 @@ +--- +title: "How to: Create Toggle Buttons in ToolStrip Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toggle buttons [Windows Forms], creating" + - "examples [Windows Forms], toolbars" + - "ToolStrip control [Windows Forms], creating toggle buttons" +ms.assetid: d9c197df-4c65-43f2-beee-b68b52b2befc +--- +# How to: Create Toggle Buttons in ToolStrip Controls + +When a user clicks a toggle button, it appears sunken and retains the sunken appearance until the user clicks the button again. + +## To create a toggling ToolStripButton + +- Use code such as the following code example. This code assumes that your form contains a control, and that its collection contains a called `toolStripButton1`. It also assumes that you have an event handler called `toolStripButton1_CheckedChanged`. + + ```vb + toolStripButton1.CheckOnClick = True + toolStripButton1.CheckedChanged AddressOf _ + EventHandler(toolStripButton1_CheckedChanged); + ``` + + ```csharp + toolStripButton1.CheckOnClick = true; + toolStripButton1.CheckedChanged += new _ + EventHandler(toolStripButton1_CheckedChanged); + ``` + +## See also + +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-create-variable-sized-text-in-a-combobox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-variable-sized-text-in-a-combobox-control.md new file mode 100644 index 0000000000..819340c7e8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-create-variable-sized-text-in-a-combobox-control.md @@ -0,0 +1,71 @@ +--- +title: "How to: Create Variable Sized Text in a ComboBox Control" +ms.date: "03/30/2017" +dev_langs: + - "vb" +helpviewer_keywords: + - "text [Windows Forms], drawing in combo boxes" + - "examples [Windows Forms], ComboBox control" + - "combo boxes [Windows Forms], drawing text" + - "ComboBox control [Windows Forms], examples [C#]" + - "ComboBox control [Windows Forms], drawing custom text" +ms.assetid: ce39b9ea-e626-49fe-bd5a-f567f6d157df +--- +# How to: Create Variable Sized Text in a ComboBox Control +This example demonstrates custom drawing of text in a control. When an item meets a certain criteria, it is drawn in a larger font and turned red. + +## Example + +```vb +Private Sub ComboBox1_MeasureItem(ByVal sender As Object, ByVal e As _ +System.Windows.Forms.MeasureItemEventArgs) Handles ComboBox1.MeasureItem + Dim bFont As New Font("Arial", 8, FontStyle.Bold) + Dim lFont As New Font("Arial", 12, FontStyle.Bold) + Dim siText As SizeF + + If ComboBox1.Items().Item(e.Index) = "Two" Then + siText = e.Graphics.MeasureString(ComboBox1.Items().Item(e.Index), _ +lFont) + Else + siText = e.Graphics.MeasureString(ComboBox1.Items().Item(e.Index), bFont) + End If + + e.ItemHeight = siText.Height + e.ItemWidth = siText.Width +End Sub + +Private Sub ComboBox1_DrawItem(ByVal sender As Object, ByVal e As _ +System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem + Dim g As Graphics = e.Graphics + Dim bFont As New Font("Arial", 8, FontStyle.Bold) + Dim lFont As New Font("Arial", 12, FontStyle.Bold) + + If ComboBox1.Items().Item(e.Index) = "Two" Then + g.DrawString(ComboBox1.Items.Item(e.Index), lfont, Brushes.Red, _ +e.Bounds.X, e.Bounds.Y) + Else + g.DrawString(ComboBox1.Items.Item(e.Index), bFont, Brushes.Black, e.Bounds.X, e.Bounds.Y) + End If +End Sub +``` + +## Compiling the Code + This example requires: + +- A Windows form. + +- A control named `ListBox1` with three items in the property. In this example, the three items are named `"One", Two", and Three"`. The property of `ComboBox1` must be set to . + + > [!NOTE] + > This technique is also applicable to the control — you can substitute a for the . + +- References to the and namespaces. + +## See also + +- +- +- +- [Controls with Built-In Owner-Drawing Support](controls-with-built-in-owner-drawing-support.md) +- [ListBox Control](listbox-control-windows-forms.md) +- [ComboBox Control](combobox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-custom-draw-a-toolstrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-custom-draw-a-toolstrip-control.md new file mode 100644 index 0000000000..180b465cb1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-custom-draw-a-toolstrip-control.md @@ -0,0 +1,137 @@ +--- +title: "How to: Custom Draw a ToolStrip Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms], custom drawing" + - "drawing [Windows Forms], owner" + - "ProfessionalColorTable class [Windows Forms], overriding" + - "examples [Windows Forms], toolbars" + - "drawing [Windows Forms], custom" + - "toolbars [Windows Forms], changing colors" + - "ToolStrip control [Windows Forms], drawing" + - "ToolStrip control [Windows Forms], changing colors" + - "custom drawing" + - "owner drawing" +ms.assetid: 94e7d7bd-a752-441c-b5b3-7acf98881163 +--- +# How to: Custom Draw a ToolStrip Control +The controls have the following associated rendering (painting) classes: + +- provides the appearance and style of your operating system. + +- provides the appearance and style of Microsoft Office. + +- is the abstract base class for the other two rendering classes. + + To custom draw (also known as owner draw) a , you can override one of the renderer classes and change an aspect of the rendering logic. + + The following procedures describe various aspects of custom drawing. + +### To switch between the provided renderers + +- Set the property to the value you want. + + With , the static determines the renderer for your application. The other values of are , , and . + +### To change the Microsoft Office–style borders to straight + +- Override , but do not call the base class. + +> [!NOTE] +> There is a version of this method for , , and . + +### To change the ProfessionalColorTable + +- Override and change the colors you want. + + ```vb + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _ + System.EventArgs) Handles Me.Load + Dim t As MyColorTable = New MyColorTable + ToolStrip1.Renderer = New ToolStripProfessionalRenderer(t) + End Sub + + Class MyColorTable + Inherits ProfessionalColorTable + + Public Overrides ReadOnly Property ButtonPressedGradientBegin() As Color + Get + Return Color.Red + End Get + End Property + + Public Overrides ReadOnly Property ButtonPressedGradientMiddle() _ + As System.Drawing.Color + Get + Return Color.Blue + End Get + End Property + + Public Overrides ReadOnly Property ButtonPressedGradientEnd() _ + As System.Drawing.Color + Get + Return Color.Green + End Get + End Property + + Public Overrides ReadOnly Property ButtonSelectedGradientBegin() _ + As Color + Get + Return Color.Yellow + End Get + End Property + + Public Overrides ReadOnly Property ButtonSelectedGradientMiddle() As System.Drawing.Color + Get + Return Color.Orange + End Get + End Property + + Public Overrides ReadOnly Property ButtonSelectedGradientEnd() _ + As System.Drawing.Color + Get + Return Color.Violet + End Get + End Property + End Class + ``` + +### To change the rendering for all ToolStrip controls in your application + +1. Use the property to choose one of the provided renderers. + +2. Use to assign a custom renderer. + +3. Ensure that is set to the default value of . + +### To turn off the Microsoft Office colors for the entire application + +- Set to `false`. + +### To turn off the Microsoft Office colors for one ToolStrip control + +- Use code similar to the following code example. + + ```vb + Dim colorTable As ProfessionalColorTable() + colorTable.UseSystemColors = True + Dim toolStrip.Renderer As ToolStripProfessionalRenderer(colorTable) + ``` + + ```csharp + ProfessionalColorTable colorTable = new ProfessionalColorTable(); + colorTable.UseSystemColors = true; + toolStrip.Renderer = new ToolStripProfessionalRenderer(colorTable); + ``` + +## See also + +- +- +- +- [Controls with Built-In Owner-Drawing Support](controls-with-built-in-owner-drawing-support.md) +- [How to: Create and Set a Custom Renderer for the ToolStrip Control in Windows Forms](create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md) +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-colors-in-toolstrip-applications.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-colors-in-toolstrip-applications.md new file mode 100644 index 0000000000..414dc511aa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-colors-in-toolstrip-applications.md @@ -0,0 +1,33 @@ +--- +title: "How to: Customize Colors in ToolStrip Applications" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms], customizing colors" + - "colors [Windows Forms], customizing in ToolStrip controls [Windows Forms]" + - "ToolStrip control [Windows Forms], custom colors" +ms.assetid: e2752fe2-1afb-489e-ab96-b7805acd96bc +--- +# How to: Customize Colors in ToolStrip Applications +You can customize the appearance of your by using the class to use customized colors. + +## Example + The following code example demonstrates how to use a to define custom colors at run time. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#20)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#20)] + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..3f466603a8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,48 @@ +--- +title: Customize Data Formatting in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], formatting data" + - "DataGridView control [Windows Forms], cell styles" + - "cells [Windows Forms], changing colors in DataGridView control [Windows Forms]" + - "colors [Windows Forms], changing in DataGridView control [Windows Forms]" + - "data [Windows Forms], formatting in DataGridView control" + - "DataGridView control [Windows Forms], cell customization" + - "DataGridView control [Windows Forms], changing cell colors" + - "Windows Forms, changing colors of DataGridView cells" + - "DataGridView control [Windows Forms], substituting cell values for display" + - "data grids [Windows Forms], formatting data" +ms.assetid: a6e72c70-ce18-425f-828d-d57be6f96ab6 +--- +# How to: Customize Data Formatting in the Windows Forms DataGridView Control +The following code example demonstrates how to implement a handler for the event that changes how cells are displayed depending on their columns and values. + + Cells in the `Balance` column that contain negative numbers are given a red background. You can also format these cells as currency to display parentheses around negative values. For more information, see [How to: Format Data in the Windows Forms DataGridView Control](how-to-format-data-in-the-windows-forms-datagridview-control.md). + + Cells in the `Priority` column display images in place of corresponding textual cell values. The property of the is used both to get the textual cell value and to set the corresponding image display value. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewCustomizeDataFormatting#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/cs/customFormatting.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewCustomizeDataFormatting#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/vb/customFormatting.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +- images named `highPri.bmp`, `mediumPri.bmp`, and `lowPri.bmp` residing in the same directory as the executable file. + +## See also + +- +- +- +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Format Data in the Windows Forms DataGridView Control](how-to-format-data-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [Data Formatting in the Windows Forms DataGridView Control](data-formatting-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-item-addition-with-the-windows-forms-bindingsource.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-item-addition-with-the-windows-forms-bindingsource.md new file mode 100644 index 0000000000..1a910b80b8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-item-addition-with-the-windows-forms-bindingsource.md @@ -0,0 +1,39 @@ +--- +title: Customize Item Addition with BindingSource component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "controls [Windows Forms], creating new items" + - "BindingSource component [Windows Forms], customizing item addition with" + - "examples [Windows Forms], BindingSource component" + - "BindingSource component [Windows Forms], examples" +ms.assetid: 1aae11fc-6fb2-4cb9-b3d0-e0638fe77ef0 +--- +# How to: Customize Item Addition with the Windows Forms BindingSource +When you use a component to bind a Windows Forms control to a data source, you may find it necessary to customize the creation of new items. The component makes this straightforward by providing the event, which is typically raised when the bound control needs to create a new item. Your event handler can provide whatever custom behavior is required (for example, calling a method on a Web service or getting a new object from a class factory). + +> [!NOTE] +> When an item is added by handling the event, the addition cannot be canceled. + +## Example + The following example demonstrates how to bind a control to a class factory by using a component. When the user clicks the control's new row, the event is raised. The event handler creates a new `DemoCustomer` object, which is assigned to the property. This causes the new `DemoCustomer` object to be added to the component's list and to be displayed in the new row of the control. + + [!code-cpp[System.Windows.Forms.DataConnector.AddingNew#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CPP/form1.cpp#1)] + [!code-csharp[System.Windows.Forms.DataConnector.AddingNew#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnector.AddingNew#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-sorting-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-sorting-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..b93abf6da0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-customize-sorting-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,46 @@ +--- +title: Customize Sorting in a DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sorting [Windows Forms], DataGridView control" + - "DataGridView control [Windows Forms], sorting" + - "data grids [Windows Forms], customizing sorting" +ms.assetid: 92fb5c14-afab-4cf5-a97e-924fd9cb99f5 +--- +# How to: Customize Sorting in the Windows Forms DataGridView Control +The control provides automatic sorting but, depending on your needs, you might need to customize sort operations. For example, you can use programmatic sorting to create an alternate user interface (UI). Alternatively, you can handle the event or call the `Sort(IComparer)` overload of the method for greater sorting flexibility, such as sorting multiple columns. + + The following code examples demonstrate these three approaches to custom sorting. For more information, see [Column Sort Modes in the Windows Forms DataGridView Control](column-sort-modes-in-the-windows-forms-datagridview-control.md). + +## Programmatic Sorting + The following code example demonstrates a programmatic sort using the and properties to determine the direction of the sort, and the property to manually set the sort glyph. The `Sort(DataGridViewColumn,ListSortDirection)` overload of the method is used to sort data only in a single column. + + [!code-csharp[System.Windows.Forms.DataGridViewProgrammaticSort#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/CS/form1.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewProgrammaticSort#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/VB/form1.vb#00)] + +## Custom Sorting Using the SortCompare Event + The following code example demonstrates custom sorting using a event handler. The selected is sorted and, if there are duplicate values in the column, the ID column is used to determine the final order. + + [!code-csharp[System.Windows.Forms.DataGridView.SortCompare#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/CS/form1.cs#00)] + [!code-vb[System.Windows.Forms.DataGridView.SortCompare#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/VB/form1.vb#00)] + +## Custom Sorting Using the IComparer Interface + The following code example demonstrates custom sorting using the `Sort(IComparer)` overload of the method, which takes an implementation of the interface to perform a multiple-column sort. + + [!code-csharp[System.Windows.Forms.DataGridViewIComparerSort#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/CS/form1.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewIComparerSort#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/VB/form1.vb#00)] + +## Compiling the Code + These examples require: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- [Sorting Data in the Windows Forms DataGridView Control](sorting-data-in-the-windows-forms-datagridview-control.md) +- [Column Sort Modes in the Windows Forms DataGridView Control](column-sort-modes-in-the-windows-forms-datagridview-control.md) +- [How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control](set-the-sort-modes-for-columns-wf-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-define-an-icon-for-a-toolbar-button-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-an-icon-for-a-toolbar-button-using-the-designer.md new file mode 100644 index 0000000000..c168e2be67 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-an-icon-for-a-toolbar-button-using-the-designer.md @@ -0,0 +1,41 @@ +--- +title: "How to: Define an Icon for a ToolBar Button Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "toolbars [Windows Forms], adding icons to buttons" + - "examples [Windows Forms], toolbars" + - "images [Windows Forms], toolbar buttons" + - "buttons [Windows Forms], images" + - "icons [Windows Forms], toolbar buttons" + - "ToolBar control [Windows Forms], adding icons to buttons" +ms.assetid: d848f38e-67f2-49d4-8e88-01c845c06c02 +--- +# How to: Define an Icon for a ToolBar Button Using the Designer + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + buttons are able to display icons within them for easy identification by users. This is achieved through adding images to the component and associating it with the control. + +The following procedure requires a **Windows Application** project with a form containing a control and an component. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### To set an icon for a toolbar button at design time + +1. Add images to the component. For more information, see [How to: Add or Remove ImageList Images with the Designer](how-to-add-or-remove-imagelist-images-with-the-designer.md). + +2. Select the control on your form. + +3. In the **Properties** window, set the control's property to the component. + +4. Click the control's property to select it, and click the ellipsis (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button to open the **ToolBarButton Collection Editor**. + +5. Use the **Add** button to add buttons to the control. + +6. In the **Properties** window that appears in the pane on the right side of the **ToolBarButton Collection Editor**, set the property of each toolbar button to one of the values in the list, which is drawn from the images you added to the component. + +## See also + +- +- [How to: Trigger Menu Events for Toolbar Buttons](how-to-trigger-menu-events-for-toolbar-buttons.md) +- [ToolBar Control](toolbar-control-windows-forms.md) +- [ImageList Component](imagelist-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-define-an-icon-for-a-toolbar-button.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-an-icon-for-a-toolbar-button.md new file mode 100644 index 0000000000..4d0a3e8976 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-an-icon-for-a-toolbar-button.md @@ -0,0 +1,117 @@ +--- +title: "How to: Define an Icon for a ToolBar Button" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "toolbars [Windows Forms], adding icons to buttons" + - "buttons [Windows Forms], icons" + - "examples [Windows Forms], toolbars" + - "images [Windows Forms], toolbar buttons" + - "icons [Windows Forms], toolbar buttons" + - "ToolBar control [Windows Forms], adding icons to buttons" +ms.assetid: 84db98b4-8566-49ce-b2c8-1fd66a5eb3a0 +--- +# How to: Define an Icon for a ToolBar Button +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + buttons are able to display icons within them for easy identification by users. This is achieved through adding images to the [ImageList Component](imagelist-component-windows-forms.md) component and then associating the component with the control. + +### To set an icon for a toolbar button programmatically + +1. In a procedure, instantiate an component and a control. + +2. In the same procedure, assign an image to the component. + +3. In the same procedure, assign the control to the control and assign the property of the individual toolbar buttons. + + In the following code example, the path set for the location of the image is the **My Documents** folder. This is done, because you can assume that most computers running the Windows operating system will include this directory. This also allows users with minimal system access levels to safely run the application. The example below assumes a form with a control already added. + + Following the steps above, you should have written code similar to that displayed below. + + ```vb + Public Sub InitializeMyToolBar() + ' Instantiate an ImageList component and a ToolBar control. + Dim ToolBar1 as New ToolBar + Dim ImageList1 as New ImageList + ' Assign an image to the ImageList component. + ' You should replace the bold image + ' in the sample below with an icon of your own choosing. + Dim myImage As System.Drawing.Image = _ + Image.FromFile Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Image.gif") + ImageList1.Images.Add(myImage) + ' Create a ToolBarButton. + Dim ToolBarButton1 As New ToolBarButton() + ' Add the ToolBarButton to the ToolBar. + ToolBar1.Buttons.Add(toolBarButton1) + ' Assign an ImageList to the ToolBar. + ToolBar1.ImageList = ImageList1 + ' Assign the ImageIndex property of the ToolBarButton. + ToolBarButton1.ImageIndex = 0 + End Sub + ``` + + ```csharp + public void InitializeMyToolBar() + { + // Instantiate an ImageList component and a ToolBar control. + ToolBar toolBar1 = new ToolBar(); + ImageList imageList1 = new ImageList(); + // Assign an image to the ImageList component. + // You should replace the bold image + // in the sample below with an icon of your own choosing. + // Note the escape character used (@) when specifying the path. + Image myImage = Image.FromFile + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Image.gif"); + imageList1.Images.Add(myImage); + // Create a ToolBarButton. + ToolBarButton toolBarButton1 = new ToolBarButton(); + // Add the ToolBarButton to the ToolBar. + toolBar1.Buttons.Add(toolBarButton1); + // Assign an ImageList to the ToolBar. + toolBar1.ImageList = imageList1; + // Assign ImageIndex property of the ToolBarButton. + toolBarButton1.ImageIndex = 0; + } + ``` + + ```cpp + public: + void InitializeMyToolBar() + { + // Instantiate an ImageList component and a ToolBar control. + ToolBar ^ toolBar1 = gcnew ToolBar(); + ImageList ^ imageList1 = gcnew ImageList(); + // Assign an image to the ImageList component. + // You should replace the bold image + // in the sample below with an icon of your own choosing. + Image ^ myImage = Image::FromFile(String::Concat + (System::Environment::GetFolderPath + (System::Environment::SpecialFolder::Personal), + "\\Image.gif")); + imageList1->Images->Add(myImage); + // Create a ToolBarButton. + ToolBarButton ^ toolBarButton1 = gcnew ToolBarButton(); + // Add the ToolBarButton to the ToolBar. + toolBar1->Buttons->Add(toolBarButton1); + // Assign an ImageList to the ToolBar. + toolBar1->ImageList = imageList1; + // Assign ImageIndex property of the ToolBarButton. + toolBarButton1->ImageIndex = 0; + } + ``` + +## See also + +- +- [How to: Trigger Menu Events for Toolbar Buttons](how-to-trigger-menu-events-for-toolbar-buttons.md) +- [ToolBar Control](toolbar-control-windows-forms.md) +- [ImageList Component](imagelist-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-define-resize-and-positioning-behavior-in-a-split-window.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-resize-and-positioning-behavior-in-a-split-window.md new file mode 100644 index 0000000000..268e0a3166 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-resize-and-positioning-behavior-in-a-split-window.md @@ -0,0 +1,63 @@ +--- +title: "How to: Define Resize and Positioning Behavior in a Split Window" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "split windows [Windows Forms], resizing" + - "splitter windows [Windows Forms], resizing" + - "SplitContainer control [Windows Forms], resizing" +ms.assetid: 9bf73f36-ed2d-4a02-b15a-0770eff4fdfa +--- +# How to: Define Resize and Positioning Behavior in a Split Window +The panels of the control lend themselves well to being resized and manipulated by users. However, there will be times when you will want to programmatically control the splitter—where it is positioned and to what degree it can be moved. + + The property and the other properties on the control give you precise control over the behavior of your user interface to suit your needs. These properties are listed in the following table. + +|Name|Description| +|----------|-----------------| +| property|Determines if the splitter is movable by means of the keyboard or mouse.| +| property|Determines the distance in pixels from the left or upper edge to the movable splitter bar.| +| property|Determines the minimum distance, in pixels, that the splitter can be moved by the user.| + + The example below modifies the property to create a "snapping splitter" effect; when the user drags the splitter, it increments in units of 10 pixels rather than the default 1. + +### To define SplitContainer resize behavior + +1. In a procedure, set the property to the desired size, so that the 'snapping' behavior of the splitter is achieved. + + In the following code example, within the form's event, the splitter within the control is set to jump 10 pixels when dragged. + + ```vb + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles MyBase.Load + Dim splitSnapper as new SplitContainer() + splitSnapper.SplitterIncrement = 10 + splitSnapper.Dock = DockStyle.Fill + splitSnapper.Parent = me + End Sub + ``` + + ```csharp + private void Form1_Load(System.Object sender, System.EventArgs e) + { + SplitContainer splitSnapper = new SplitContainer(); + splitSnapper.SplitterIncrement = 10; + splitSnapper.Dock = DockStyle.Fill; + splitSnapper.Parent = this; + } + ``` + + (Visual C#) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.Load += new System.EventHandler(this.Form1_Load); + ``` + + Moving the splitter slightly to the left or right will have no discernible effect; however, when the mouse pointer goes 10 pixels in either direction, the splitter will snap to the new position. + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-define-z-ordering-of-docked-toolstrip-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-z-ordering-of-docked-toolstrip-controls.md new file mode 100644 index 0000000000..cf629b2ef2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-define-z-ordering-of-docked-toolstrip-controls.md @@ -0,0 +1,44 @@ +--- +title: "How to: Define Z-Ordering of Docked ToolStrip Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStrip control [Windows Forms]" + - "MenuStrip control [Windows Forms]" + - "toolbars [Windows Forms], specifying z-order" + - "z-order" +ms.assetid: 8b595429-ba9f-46af-9c55-3d5cc53f7fff +--- +# How to: Define Z-Ordering of Docked ToolStrip Controls +To position a control correctly with docking, you must position the control correctly in the form's z-order. + +## Example + The following code example demonstrates how to arrange a control and a docked control by specifying the z-order. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#21)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#21)] + + The z-order is determined by the order in which the and + + controls are added to the form's collection. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#23)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#23)] + + Reverse the order of these calls to the method and view the effect on the layout. + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..b58c3ebcbe --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md @@ -0,0 +1,124 @@ +--- +title: Delete or Hide Columns in DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], deleting columns" + - "DataGrid control [Windows Forms], deleting columns" + - "data grids [Windows Forms], hiding columns" + - "columns [Windows Forms], hiding" + - "columns [Windows Forms], deleting in data grids" + - "DataGrid control [Windows Forms], hiding columns" +ms.assetid: bcd0dd96-6687-4c48-b0e1-d5287b93ac91 +--- +# How to: Delete or Hide Columns in the Windows Forms DataGrid Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + You can programmatically delete or hide columns in the Windows Forms control by using the properties and methods of the and objects (which are members of the class). + + The deleted or hidden columns still exist in the data source the grid is bound to, and can still be accessed programmatically. They are just no longer visible in the datagrid. + +> [!NOTE] +> If your application does not access certain columns of data, and you do not want them displayed in the datagrid, then it is probably not necessary to include them in the data source in the first place. + +### To delete a column from the DataGrid programmatically + +1. In the declarations area of your form, declare a new instance of the class. + +2. Set the property to the table in your data source that you want to apply the style to. The following example uses the property, which it assumes is already set. + +3. Add the new object to the datagrid's table styles collection. + +4. Call the method of the 's collection, specifying the column index of the column to delete. + + ```vb + ' Declare a new DataGridTableStyle in the + ' declarations area of your form. + Dim ts As DataGridTableStyle = New DataGridTableStyle() + + Sub DeleteColumn() + ' Set the DataGridTableStyle.MappingName property + ' to the table in the data source to map to. + ts.MappingName = DataGrid1.DataMember + + ' Add it to the datagrid's TableStyles collection + DataGrid1.TableStyles.Add(ts) + + ' Delete the first column (index 0) + DataGrid1.TableStyles(0).GridColumnStyles.RemoveAt(0) + End Sub + ``` + + ```csharp + // Declare a new DataGridTableStyle in the + // declarations area of your form. + DataGridTableStyle ts = new DataGridTableStyle(); + + private void deleteColumn() + { + // Set the DataGridTableStyle.MappingName property + // to the table in the data source to map to. + ts.MappingName = dataGrid1.DataMember; + + // Add it to the datagrid's TableStyles collection + dataGrid1.TableStyles.Add(ts); + + // Delete the first column (index 0) + dataGrid1.TableStyles[0].GridColumnStyles.RemoveAt(0); + } + ``` + +### To hide a column in the DataGrid programmatically + +1. In the declarations area of your form, declare a new instance of the class. + +2. Set the property of the to the table in your data source that you want to apply the style to. The following code example uses the property, which it assumes is already set. + +3. Add the new object to the datagrid's table styles collection. + +4. Hide the column by setting its `Width` property to 0, specifying the column index of the column to hide. + + ```vb + ' Declare a new DataGridTableStyle in the + ' declarations area of your form. + Dim ts As DataGridTableStyle = New DataGridTableStyle() + + Sub HideColumn() + ' Set the DataGridTableStyle.MappingName property + ' to the table in the data source to map to. + ts.MappingName = DataGrid1.DataMember + + ' Add it to the datagrid's TableStyles collection + DataGrid1.TableStyles.Add(ts) + + ' Hide the first column (index 0) + DataGrid1.TableStyles(0).GridColumnStyles(0).Width = 0 + End Sub + ``` + + ```csharp + // Declare a new DataGridTableStyle in the + // declarations area of your form. + DataGridTableStyle ts = new DataGridTableStyle(); + + private void hideColumn() + { + // Set the DataGridTableStyle.MappingName property + // to the table in the data source to map to. + ts.MappingName = dataGrid1.DataMember; + + // Add it to the datagrid's TableStyles collection + dataGrid1.TableStyles.Add(ts); + + // Hide the first column (index 0) + dataGrid1.TableStyles[0].GridColumnStyles[0].Width = 0; + } + ``` + +## See also + +- [How to: Change Displayed Data at Run Time in the Windows Forms DataGrid Control](change-displayed-data-at-run-time-wf-datagrid-control.md) +- [How to: Add Tables and Columns to the Windows Forms DataGrid Control](how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md new file mode 100644 index 0000000000..b67551464d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md @@ -0,0 +1,54 @@ +--- +title: Design a localization-friendly layout +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "TableLayoutPanel control [Windows Forms]" + - "application design [Windows Forms], localization" + - "Windows Forms, localization" + - "localization [Windows Forms], Windows Forms layout" +ms.assetid: d13eff2d-701c-4b6e-8838-3885cbfb7223 +--- +# How to: Design a Windows Forms Layout that Responds Well to Localization +Creating forms that are ready to be localized greatly speeds development for international markets. You can use the control to implement layouts that respond gracefully as controls resize due to changes in their property values. + +## Example + This form demonstrates how to create a layout that proportionally adjusts when you translate displayed string values into other languages. This process of translation is called *localization*. For more information, see [Localization](https://docs.microsoft.com/dotnet/standard/globalization-localization/localization). + + There is extensive support for this task in Visual Studio. See also [Walkthrough: Creating a Layout That Adjusts Proportion for Localization](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/7k9fa71y(v=vs.100)). + + [!code-csharp[System.Windows.Forms.TableLayoutPanel.LocalizableForm#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/CS/localizableform.cs#1)] + [!code-vb[System.Windows.Forms.TableLayoutPanel.LocalizableForm#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/VB/localizableform.vb#1)] + +## Additional resources + +1. [How to: Align and Stretch a Control in a TableLayoutPanel Control](how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md) + +2. [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) + +3. [How to: Span Rows and Columns in a TableLayoutPanel Control](how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md) + +4. [How to: Edit Columns and Rows in a TableLayoutPanel Control](how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md) + +5. [Walkthrough: Perform common tasks using designer actions](perform-common-tasks-design-actions.md) + +6. [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) + +7. [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md) + +8. [How to: Support Localization on Windows Forms Using AutoSize and the TableLayoutPanel Control](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/1zkt8b33(v=vs.100)) + +9. [Walkthrough: Creating a Resizable Windows Form for Data Entry](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/991eahec(v=vs.100)) + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- [Localization](https://docs.microsoft.com/dotnet/standard/globalization-localization/localization) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-designate-a-windows-forms-button-as-the-accept-button.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-designate-a-windows-forms-button-as-the-accept-button.md new file mode 100644 index 0000000000..66b1cc9078 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-designate-a-windows-forms-button-as-the-accept-button.md @@ -0,0 +1,53 @@ +--- +title: Designate a Button as the Accept Button +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "buttons [Windows Forms], default on Windows Forms" + - "Accept button on Windows Forms" + - "Button control [Windows Forms], designating as default" + - "Windows Forms controls, default button on form" +ms.assetid: 22cc9da6-b913-4e04-9554-dee443ac5c3a +--- +# How to: Designate a Windows Forms Button as the Accept Button +On any Windows Form, you can designate a control to be the accept button, also known as the default button. Whenever the user presses the ENTER key, the default button is clicked regardless of which other control on the form has the focus. + +> [!NOTE] +> The exceptions to this are when the control with focus is another button — in that case, the button with the focus will be clicked — or a multiline text box, or a custom control that traps the ENTER key. + +### To designate the accept button + +1. Set the form's property to the appropriate control. + + ```vb + Private Sub SetDefault(ByVal myDefaultBtn As Button) + Me.AcceptButton = myDefaultBtn + End Sub + ``` + + ```csharp + private void SetDefault(Button myDefaultBtn) + { + this.AcceptButton = myDefaultBtn; + } + ``` + + ```cpp + private: + void SetDefault(Button ^ myDefaultBtn) + { + this->AcceptButton = myDefaultBtn; + } + ``` + +## See also + +- +- [Button Control Overview](button-control-overview-windows-forms.md) +- [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [How to: Designate a Windows Forms Button as the Cancel Button](how-to-designate-a-windows-forms-button-as-the-cancel-button.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-designate-a-windows-forms-button-as-the-cancel-button.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-designate-a-windows-forms-button-as-the-cancel-button.md new file mode 100644 index 0000000000..eaf22f6628 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-designate-a-windows-forms-button-as-the-cancel-button.md @@ -0,0 +1,48 @@ +--- +title: Designate a Button as the Cancel Button +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "buttons [Windows Forms], cancel buttons" + - "Button control [Windows Forms], designating as cancel button" +ms.assetid: 252f0834-e54b-44d9-96f7-ee5f50e94f2c +--- +# How to: Designate a Windows Forms Button as the Cancel Button +On any Windows Form, you can designate a control to be the cancel button. A cancel button is clicked whenever the user presses the ESC key, regardless of which other control on the form has the focus. Such a button is usually programmed to enable the user to quickly exit an operation without committing to any action. + +### To designate the cancel button + +1. Set the form's property to the appropriate control. + + ```vb + Private Sub SetCancelButton(ByVal myCancelBtn As Button) + Me.CancelButton = myCancelBtn + End Sub + ``` + + ```csharp + private void SetCancelButton(Button myCancelBtn) + { + this.CancelButton = myCancelBtn; + } + ``` + + ```cpp + private: + void SetCancelButton(Button ^ myCancelBtn) + { + this->CancelButton = myCancelBtn; + } + ``` + +## See also + +- +- [Button Control Overview](button-control-overview-windows-forms.md) +- [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [How to: Designate a Windows Forms Button as the Accept Button](how-to-designate-a-windows-forms-button-as-the-accept-button.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-detect-when-the-mouse-pointer-is-over-a-toolstripitem.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-detect-when-the-mouse-pointer-is-over-a-toolstripitem.md new file mode 100644 index 0000000000..18f172259c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-detect-when-the-mouse-pointer-is-over-a-toolstripitem.md @@ -0,0 +1,24 @@ +--- +title: "How to: Detect When the Mouse Pointer Is Over a ToolStripItem" +ms.date: "03/30/2017" +helpviewer_keywords: + - "toolbars [Windows Forms], detecting mouse movement" + - "ToolStrip control [Windows Forms], detecting mouse movement" + - "ToolStripItem class [Windows Forms], detecting mouse movement" + - "mouse [Windows Forms], detecting movement on toolbars" +ms.assetid: d38b5082-aba7-4f6c-841b-bd9714e307fd +--- +# How to: Detect When the Mouse Pointer Is Over a ToolStripItem +Use the following procedure to detect when the mouse pointer is over a . + +### To detect when the pointer is over a ToolStripItem + +- Use the property for items in which is `true`. + + This will prevent you from having to synchronize the and events. + +## See also + +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-checked-items-in-the-windows-forms-checkedlistbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-checked-items-in-the-windows-forms-checkedlistbox-control.md new file mode 100644 index 0000000000..42d1d396ee --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-checked-items-in-the-windows-forms-checkedlistbox-control.md @@ -0,0 +1,111 @@ +--- +title: Determine Checked Items in CheckedListBox Control +description: Learn how to determine checked items in the Windows Forms CheckedListBox control by iterating through the collection stored in the CheckedItems property. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "check boxes [Windows Forms], determining checked state" + - "CheckedListBox control [Windows Forms], determining checked state" +ms.assetid: 178b477d-27c9-489c-8914-44a9623a4d41 +--- +# How to: Determine Checked Items in the Windows Forms CheckedListBox Control +When presenting data in a Windows Forms control, you can either iterate through the collection stored in the property, or step through the list using the method to determine which items are checked. The method takes an item index number as its argument and returns `true` or `false`. Contrary to what you might expect, the and properties do not determine which items are checked; they determine which items are highlighted. + +### To determine checked items in a CheckedListBox control + +1. Iterate through the collection, starting at 0 since the collection is zero-based. Note that this method will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like "Checked Item 1 = MyListItem2". + + ```vb + ' Determine if there are any items checked. + If CheckedListBox1.CheckedItems.Count <> 0 Then + ' If so, loop through all checked items and print results. + Dim x As Integer + Dim s As String = "" + For x = 0 To CheckedListBox1.CheckedItems.Count - 1 + s = s & "Checked Item " & (x + 1).ToString & " = " & CheckedListBox1.CheckedItems(x).ToString & ControlChars.CrLf + Next x + MessageBox.Show(s) + End If + ``` + + ```csharp + // Determine if there are any items checked. + if(checkedListBox1.CheckedItems.Count != 0) + { + // If so, loop through all checked items and print results. + string s = ""; + for(int x = 0; x < checkedListBox1.CheckedItems.Count ; x++) + { + s = s + "Checked Item " + (x+1).ToString() + " = " + checkedListBox1.CheckedItems[x].ToString() + "\n"; + } + MessageBox.Show(s); + } + ``` + + ```cpp + // Determine if there are any items checked. + if(checkedListBox1->CheckedItems->Count != 0) + { + // If so, loop through all checked items and print results. + String ^ s = ""; + for(int x = 0; x < checkedListBox1->CheckedItems->Count; x++) + { + s = String::Concat(s, "Checked Item ", (x+1).ToString(), + " = ", checkedListBox1->CheckedItems[x]->ToString(), + "\n"); + } + MessageBox::Show(s); + } + ``` + + - or - + +2. Step through the collection, starting at 0 since the collection is zero-based, and call the method for each item. Note that this method will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like "Item 2 = MyListItem2". + + ```vb + Dim i As Integer + Dim s As String + s = "Checked Items:" & ControlChars.CrLf + For i = 0 To (CheckedListBox1.Items.Count - 1) + If CheckedListBox1.GetItemChecked(i) = True Then + s = s & "Item " & (i + 1).ToString & " = " & CheckedListBox1.Items(i).ToString & ControlChars.CrLf + End If + Next + MessageBox.Show(s) + ``` + + ```csharp + int i; + string s; + s = "Checked items:\n" ; + for (i = 0; i <= (checkedListBox1.Items.Count-1); i++) + { + if (checkedListBox1.GetItemChecked(i)) + { + s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n"; + } + } + MessageBox.Show (s); + ``` + + ```cpp + int i; + String ^ s; + s = "Checked items:\n" ; + for (i = 0; i <= (checkedListBox1->Items->Count-1); i++) + { + if (checkedListBox1->GetItemChecked(i)) + { + s = String::Concat(s, "Item ", (i+1).ToString(), " = ", + checkedListBox1->Item[i]->ToString(), "\n"); + } + } + MessageBox::Show(s); + ``` + +## See also + +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-page-properties-using-the-pagesetupdialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-page-properties-using-the-pagesetupdialog-component.md new file mode 100644 index 0000000000..b11122cce5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-page-properties-using-the-pagesetupdialog-component.md @@ -0,0 +1,88 @@ +--- +title: "How to: Determine Page Properties Using the PageSetupDialog Component" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "page properties" + - "page setup" + - "PageSetupDialog component" +ms.assetid: 6dae05bc-c0fd-4357-bb93-841a1631d98f +--- +# How to: Determine Page Properties Using the PageSetupDialog Component +The [PageSetupDialog](pagesetupdialog-component-windows-forms.md) component presents layout, paper size, and other page layout choices to the user for a document. + + You need to specify an instance of the class—this is the document to be printed. Additionally, users must have a printer installed on their computer, either locally or through a network, as this is partly how the component determines the page formatting choices presented to the user. + + An important aspect of working with the component is how it interacts with the class. The class is used to specify settings that modify the way a page will be printed, such as paper orientation, the size of the page, and the margins. Each of these settings is represented as a property of the class. The class modifies these property values for a given instance of the class that is associated with the document (and is represented as a property). + +### To set page properties using the PageSetupDialog component + +1. Use the method to display the dialog box, specifying the to use. + + In the example below, the control's event handler opens an instance of the component. An existing document is specified in the property, and its property is set to `false`. + + The example assumes your form has a control, a component named `myDocument`, and a component. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Button1.Click + ' The print document 'myDocument' used below + ' is merely for an example. + 'You will have to specify your own print document. + PageSetupDialog1.Document = myDocument + ' Sets the print document's color setting to false, + ' so that the page will not be printed in color. + PageSetupDialog1.Document.DefaultPageSettings.Color = False + PageSetupDialog1.ShowDialog() + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + // The print document 'myDocument' used below + // is merely for an example. + // You will have to specify your own print document. + pageSetupDialog1.Document = myDocument; + // Sets the print document's color setting to false, + // so that the page will not be printed in color. + pageSetupDialog1.Document.DefaultPageSettings.Color = false; + pageSetupDialog1.ShowDialog(); + } + ``` + + ```cpp + private: + System::Void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + // The print document 'myDocument' used below + // is merely for an example. + // You will have to specify your own print document. + pageSetupDialog1->Document = myDocument; + // Sets the print document's color setting to false, + // so that the page will not be printed in color. + pageSetupDialog1->Document->DefaultPageSettings->Color = false; + pageSetupDialog1->ShowDialog(); + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + + ```cpp + this->button1->Click += gcnew + System::EventHandler(this, &Form1::button1_Click); + ``` + +## See also + +- +- [How to: Create Standard Windows Forms Print Jobs](../advanced/how-to-create-standard-windows-forms-print-jobs.md) +- [PageSetupDialog Component](pagesetupdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-which-treeview-node-was-clicked-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-which-treeview-node-was-clicked-windows-forms.md new file mode 100644 index 0000000000..7443465eb2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-determine-which-treeview-node-was-clicked-windows-forms.md @@ -0,0 +1,57 @@ +--- +title: "How to: Determine Which TreeView Node Was Clicked" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "TreeNode" +helpviewer_keywords: + - "examples [Windows Forms], TreeView control" + - "tree nodes in TreeView control [Windows Forms], determining node clicked" + - "TreeView control [Windows Forms], determining node clicked" +ms.assetid: 06a4a191-d918-42af-9f49-956c93eff261 +--- +# How to: Determine Which TreeView Node Was Clicked (Windows Forms) +When working with the Windows Forms control, a common task is to determine which node was clicked, and respond appropriately. + +### To determine which TreeView node was clicked + +1. Use the object to return a reference to the clicked node object. + +2. Determine which node was clicked by checking the class, which contains data related to the event. + + ```vb + Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, _ + ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect + ' Determine by checking the Node property of the TreeViewEventArgs. + MessageBox.Show(e.Node.Text) + End Sub + ``` + + ```csharp + protected void treeView1_AfterSelect (object sender, + System.Windows.Forms.TreeViewEventArgs e) + { + // Determine by checking the Text property. + MessageBox.Show(e.Node.Text); + } + ``` + + ```cpp + private: + void treeView1_AfterSelect(System::Object ^ sender, + System::Windows::Forms::TreeViewEventArgs ^ e) + { + // Determine by checking the Text property. + MessageBox::Show(e->Node->Text); + } + ``` + + > [!NOTE] + > As an alternative, you can use the of the or event to get the and coordinate values of the where the click occurred. Then, use the control's method to determine which node was clicked. + +## See also + +- [TreeView Control](treeview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-develop-a-simple-windows-forms-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-develop-a-simple-windows-forms-control.md new file mode 100644 index 0000000000..5e6121e422 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-develop-a-simple-windows-forms-control.md @@ -0,0 +1,104 @@ +--- +title: Develop a Simple Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms]" + - "custom controls [Windows Forms], creating simple controls using code" + - "Control class [Windows Forms], Windows Forms" +ms.assetid: 86cbe435-45b7-4cb4-9b5a-47418369758d +--- +# How to: Develop a Simple Windows Forms Control + +This section walks you through the key steps for authoring a custom Windows Forms control. The simple control developed in this walkthrough allows the alignment of its property to be changed. It does not raise or handle events. + +### To create a simple custom control + +1. Define a class that derives from . + + ```vb + Public Class FirstControl + Inherits Control + + End Class + ``` + + ```csharp + public class FirstControl:Control {} + ``` + +2. Define properties. (You are not required to define properties, because a control inherits many properties from the class, but most custom controls generally do define additional properties.) The following code fragment defines a property named `TextAlignment` that `FirstControl` uses to format the display of the property inherited from . For more information about defining properties, see [Properties Overview](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/65zdfbdt(v%3dvs.120)). + + [!code-csharp[System.Windows.Forms.FirstControl#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs#3)] + [!code-vb[System.Windows.Forms.FirstControl#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb#3)] + + When you set a property that changes the visual display of the control, you must invoke the method to redraw the control. is defined in the base class . + +3. Override the protected method inherited from to provide rendering logic to your control. If you do not override , your control will not be able to draw itself. In the following code fragment, the method displays the property inherited from with the alignment specified by the `alignmentValue` field. + + [!code-csharp[System.Windows.Forms.FirstControl#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs#4)] + [!code-vb[System.Windows.Forms.FirstControl#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb#4)] + +4. Provide attributes for your control. Attributes enable a visual designer to display your control and its properties and events appropriately at design time. The following code fragment applies attributes to the `TextAlignment` property. In a designer such as Visual Studio, the attribute (shown in the code fragment) causes the property to be displayed under a logical category. The attribute causes a descriptive string to be displayed at the bottom of the **Properties** window when the `TextAlignment` property is selected. For more information about attributes, see [Design-Time Attributes for Components](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/tk67c2t8(v=vs.120)). + + [!code-csharp[System.Windows.Forms.FirstControl#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs#5)] + [!code-vb[System.Windows.Forms.FirstControl#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb#5)] + +5. (optional) Provide resources for your control. You can provide a resource, such as a bitmap, for your control by using a compiler option (`/res` for C#) to package resources with your control. At run time, the resource can be retrieved using the methods of the class. For more information about creating and using resources, see the [Resources in Desktop Apps](https://docs.microsoft.com/dotnet/framework/resources/index). + +6. Compile and deploy your control. To compile and deploy `FirstControl,` execute the following steps: + + 1. Save the code in the following sample to a source file (such as FirstControl.cs or FirstControl.vb). + + 2. Compile the source code into an assembly and save it in your application's directory. To accomplish this, execute the following command from the directory that contains the source file. + + ```console + vbc -t:library -out:[path to your application's directory]/CustomWinControls.dll -r:System.dll -r:System.Windows.Forms.dll -r:System.Drawing.dll FirstControl.vb + ``` + + ```console + csc -t:library -out:[path to your application's directory]/CustomWinControls.dll -r:System.dll -r:System.Windows.Forms.dll -r:System.Drawing.dll FirstControl.cs + ``` + + The `/t:library` compiler option tells the compiler that the assembly you are creating is a library (and not an executable). The `/out` option specifies the path and name of the assembly. The`/r` option provides the name of the assemblies that are referenced by your code. In this example, you create a private assembly that only your applications can use. Hence, you have to save it in your application's directory. For more information about packaging and deploying a control for distribution, see [Deployment](https://docs.microsoft.com/dotnet/framework/deployment/index). + +The following sample shows the code for `FirstControl`. The control is enclosed in the namespace `CustomWinControls`. A namespace provides a logical grouping of related types. You can create your control in a new or existing namespace. In C#, the `using` declaration (in Visual Basic, `Imports`) allows types to be accessed from a namespace without using the fully qualified name of the type. In the following example, the `using` declaration allows code to access the class from as simply instead of having to use the fully qualified name . + +[!code-csharp[System.Windows.Forms.FirstControl#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs#1)] +[!code-vb[System.Windows.Forms.FirstControl#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb#1)] + +## Using the Custom Control on a Form + +The following example shows a simple form that uses `FirstControl`. It creates three instances of `FirstControl`, each with a different value for the `TextAlignment` property. + +#### To compile and run this sample + +1. Save the code in the following example to a source file (SimpleForm.cs or SimpleForms.vb). + +2. Compile the source code into an executable assembly by executing the following command from the directory that contains the source file. + + ```console + vbc -r:CustomWinControls.dll -r:System.dll -r:System.Windows.Forms.dll -r:System.Drawing.dll SimpleForm.vb + ``` + + ```console + csc -r:CustomWinControls.dll -r:System.dll -r:System.Windows.Forms.dll -r:System.Drawing.dll SimpleForm.cs + ``` + + CustomWinControls.dll is the assembly that contains the class `FirstControl`. This assembly must be in the same directory as the source file for the form that accesses it (SimpleForm.cs or SimpleForms.vb). + +3. Execute SimpleForm.exe using the following command. + + ```console + SimpleForm + ``` + +[!code-csharp[System.Windows.Forms.FirstControl#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/SimpleForm.cs#10)] +[!code-vb[System.Windows.Forms.FirstControl#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/SimpleForm.vb#10)] + +## See also + +- [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) +- [Events in Windows Forms Controls](events-in-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-tab-pages.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-tab-pages.md new file mode 100644 index 0000000000..3782401435 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-tab-pages.md @@ -0,0 +1,103 @@ +--- +title: "How to: Disable Tab Pages" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "tab pages [Windows Forms], hiding in forms" + - "TabControl control [Windows Forms], disabling pages" +ms.assetid: adcc6618-8a34-4ee1-bbe3-47e732de6a59 +--- +# How to: Disable Tab Pages +On some occasions, you will want to restrict access to data that is available within your Windows Forms application. One example of this might be when you have data displayed in the tab pages of a tab control; administrators could have information on a tab page that you would want to restrict from guest or lower-level users. + +### To disable tab pages programmatically + +1. Write code to handle the tab control's event. This is the event that is raised when the user switches from one tab to the next. + +2. Check credentials. Depending upon the information presented, you may want to check the user name the user has logged in with or some other form of credentials before allowing the user to view the tab. + +3. If the user has appropriate credentials, display the tab that was clicked. If the user does not have appropriate credentials, display a message box or some other user interface indicating that they do not have access, and return to the initial tab. + + > [!NOTE] + > When you implement this functionality in your production applications, you can perform this credential check during the form's event. This will allow you to hide the tab before any user interface is shown, which is a much cleaner approach to programming. The methodology used below (checking credentials and disabling the tab during the event) is for illustrative purposes. + +4. Optionally, if you have more than two tab pages, display a tab page different from the original. + + In the example below, a control is used in lieu of checking the credentials, as the criteria for access to the tab will vary by application. When the event is raised, if the credential check is true (that is, the check box is checked) and the selected tab is `TabPage2` (the tab with the confidential information, in this example), then `TabPage2` is displayed. Otherwise, `TabPage3` is displayed and a message box is shown to the user, indicating they did not have appropriate access privileges. The code below assumes a form with a control (`CredentialCheck`) and a control with three tab pages. + + ```vb + Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged + ' Check Credentials Here + + If CredentialCheck.Checked = True And _ + TabControl1.SelectedTab Is TabPage2 Then + TabControl1.SelectedTab = TabPage2 + ElseIf CredentialCheck.Checked = False _ + And TabControl1.SelectedTab Is TabPage2 Then + MessageBox.Show _ + ("Unable to load tab. You have insufficient access privileges.") + TabControl1.SelectedTab = TabPage3 + End If + End Sub + ``` + + ```csharp + private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e) + { + // Check Credentials Here + + if ((CredentialCheck.Checked == true) && (tabControl1.SelectedTab == tabPage2)) + { + tabControl1.SelectedTab = tabPage2; + } + else if ((CredentialCheck.Checked == false) && (tabControl1.SelectedTab == tabPage2)) + { + MessageBox.Show("Unable to load tab. You have insufficient access privileges."); + tabControl1.SelectedTab = tabPage3; + } + } + ``` + + ```cpp + private: + System::Void tabControl1_SelectedIndexChanged( + System::Object ^ sender, + System::EventArgs ^ e) + { + // Check Credentials Here + if ((CredentialCheck->Checked == true) && + (tabControl1->SelectedTab == tabPage2)) + { + tabControl1->SelectedTab = tabPage2; + } + else if ((CredentialCheck->Checked == false) && + (tabControl1->SelectedTab == tabPage2)) + { + MessageBox::Show(String::Concat("Unable to load tab. ", + "You have insufficient access privileges.")); + tabControl1->SelectedTab = tabPage3; + } + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.tabControl1.SelectedIndexChanged += + new System.EventHandler(this.tabControl1_SelectedIndexChanged); + ``` + + ```cpp + this->tabControl1->SelectedIndexChanged += + gcnew System::EventHandler(this, &Form1::tabControl1_SelectedIndexChanged); + ``` + +## See also + +- [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) +- [How to: Add a Control to a Tab Page](how-to-add-a-control-to-a-tab-page.md) +- [How to: Add and Remove Tabs with the Windows Forms TabControl](how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md) +- [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-toolstripmenuitems-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-toolstripmenuitems-using-the-designer.md new file mode 100644 index 0000000000..7759643b9b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-toolstripmenuitems-using-the-designer.md @@ -0,0 +1,26 @@ +--- +title: "How to: Disable ToolStripMenuItems Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStripMenuItems [Windows Forms], disabling in designer" + - "MenuStrip control [Windows Forms], disabling menu items in designer" + - "menu items [Windows Forms], disabling" + - "menus [Windows Forms], disabling items" +ms.assetid: 985e311e-7d67-4205-b5a3-d045b68a4a03 +--- +# How to: Disable ToolStripMenuItems Using the Designer +You can limit or broaden the commands a user may make by enabling and disabling menu items in response to user activities. Menu items are enabled by default when they are created, but this can be adjusted through the property. You can manipulate this property at design time in the **Properties** window or programmatically by setting it in code. For more information, see [How to: Disable ToolStripMenuItems](how-to-disable-toolstripmenuitems.md). + +## To disable a menu item at design time + +1. With the menu item selected on the form, set the property to `false`. + + > [!TIP] + > Disabling the first or top-level menu item in a menu disables all the menu items contained within the menu. Likewise, disabling a menu item that has submenu items disables the submenu items. If all the commands on a given menu are unavailable to the user, it is considered good programming practice to both hide and disable the entire menu, as this presents a clean user interface. You should both hide and disable the menu, as hiding alone does not prevent access to a menu command via a shortcut key. Set the property of a top-level menu item to `false` to hide the entire menu. + +## See also + +- +- +- [How to: Hide ToolStripMenuItems](how-to-hide-toolstripmenuitems.md) +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-toolstripmenuitems.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-toolstripmenuitems.md new file mode 100644 index 0000000000..f1c3826930 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-disable-toolstripmenuitems.md @@ -0,0 +1,44 @@ +--- +title: "How to: Disable ToolStripMenuItems" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ToolStripMenuItems [Windows Forms], enabling" + - "ToolStripMenuItems [Windows Forms], disabling" + - "menu items [Windows Forms], disabling" + - "disabling menu items" + - "menu items [Windows Forms], enabling" + - "menus [Windows Forms], disabling menu items" +ms.assetid: bcc1da84-50fd-41d2-8475-103b581d5654 +--- +# How to: Disable ToolStripMenuItems +You can limit or broaden the commands a user may make by enabling and disabling menu items in response to user activities. Menu items are enabled by default when they are created, but this can be adjusted through the property. You can manipulate this property at design time in the **Properties** window or programmatically by setting it in code. + +### To disable a menu item programmatically + +- Within the method where you set the properties of the menu item, add code to set the property to `false`. + + ```vb + MenuItem1.Enabled = False + ``` + + ```csharp + menuItem1.Enabled = false; + ``` + + ```cpp + menuItem1->Enabled = false; + ``` + + > [!TIP] + > Disabling the first or top-level menu item in a menu hides all the menu items contained within the menu, but does not disable them. Likewise, disabling a menu item that has submenu items hides the submenu items, but does not disable them. If all the commands on a given menu are unavailable to the user, it is considered good programming practice to both hide and disable the entire menu, as this presents a clean user interface. You should hide and disable the menu, and disable every item and submenu item in the menu, because hiding alone does not prevent access to a menu command via a shortcut key. Set the property of a top-level menu item to `false` to hide the entire menu. + +## See also + +- +- +- [How to: Hide ToolStripMenuItems](how-to-hide-toolstripmenuitems.md) +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md new file mode 100644 index 0000000000..824ee2de80 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md @@ -0,0 +1,31 @@ +--- +title: "How to: Display a Control in the Choose Toolbox Items Dialog Box" +ms.date: "08/23/2019" +helpviewer_keywords: + - "global assembly cache [Windows Forms], Choose Toolbox Items dialog box" + - "AssemblyFoldersEx [Windows Forms], Choose Toolbox Items dialog box" + - "controls [Windows Forms], display in Choose Toolbox Items dialog box" + - "assembly folder registration [Windows Forms], Choose Toolbox Items dialog box" + - "Choose Toolbox Items dialog box [Windows Forms], display control" +ms.assetid: 01ef6eba-d044-40f0-951d-78eff7ebd9a9 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Display a Control in the Choose Toolbox Items Dialog Box + +As you develop and distribute controls, you may want those controls to appear in the **Choose Toolbox Items** dialog box of Visual Studio, which is displayed when you right-click the **Toolbox** and select **Choose Items**. You can enable your control to appear in this dialog box by using the AssemblyFoldersEx registration procedure. + +To display your control in the Choose Toolbox Items dialog box: + +- Install your control assembly to the global assembly cache. For more information, see [How to: Install an Assembly into the Global Assembly Cache](https://docs.microsoft.com/dotnet/framework/app-domains/install-assembly-into-gac). + + -or- + +- Register your control and its associated design-time assemblies by using the AssemblyFoldersEx registration procedure. AssemblyFoldersEx is a registry location where third-party vendors store paths for each version of the framework that they support. Design-time resolution can look in this registry location to find reference assemblies. The registry script can specify the controls you want to appear in the Toolbox. + +## See also + +- [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md) +- [How to: Install an Assembly into the Global Assembly Cache](https://docs.microsoft.com/dotnet/framework/app-domains/install-assembly-into-gac) +- [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control.md new file mode 100644 index 0000000000..99bb65cdd6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control.md @@ -0,0 +1,41 @@ +--- +title: Display an Insertion Mark in ListView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ListView control [Windows Forms], drag operations" + - "graphics [Windows Forms], insertion marks" + - "drop and drag [Windows Forms], insertion marks" + - "insertion marks" +ms.assetid: 88d0a15b-25fd-4dc3-a685-297351311940 +--- +# How to: Display an Insertion Mark in a Windows Forms ListView Control +The insertion mark in the control shows users the point where dragged items will be inserted. When a user drags an item to a point between two other items, the insertion mark shows the item's expected new location. + + The following image shows an insertion mark: + + ![Screenshot that shows a ListView insertion mark.](./media/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control/listview-insertion-mark.gif "ListViewInsertion") + + The following code example demonstrates how to use this feature. + +## Example + [!code-cpp[System.Windows.Forms.ListView.InsertionMark#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp#1)] + [!code-csharp[System.Windows.Forms.ListView.InsertionMark#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CS/listviewinsertionmarkexample.cs#1)] + [!code-vb[System.Windows.Forms.ListView.InsertionMark#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/VB/listviewinsertionmarkexample.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [Walkthrough: Performing a Drag-and-Drop Operation in Windows Forms](../advanced/walkthrough-performing-a-drag-and-drop-operation-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-icons-for-the-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-icons-for-the-windows-forms-listview-control.md new file mode 100644 index 0000000000..394d648f57 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-icons-for-the-windows-forms-listview-control.md @@ -0,0 +1,40 @@ +--- +title: Display Icons for ListView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ListView control [Windows Forms], displaying icons" + - "icons [Windows Forms], displaying for ListView controls" + - "lists [Windows Forms], displaying icons" + - "ImageList component [Windows Forms], with ListView control" + - "list views [Windows Forms], displaying icons" +ms.assetid: 9d577542-8595-429b-99e5-078770ec9d35 +--- +# How to: Display Icons for the Windows Forms ListView Control +The Windows Forms control can display icons from three image lists. The List, Details, and SmallIcon views display images from the image list specified in the property. The LargeIcon view displays images from the image list specified in the property. A list view can also display an additional set of icons, set in the property, next to the large or small icons. For more information about image lists, see [ImageList Component](imagelist-component-windows-forms.md) and [How to: Add or Remove Images with the Windows Forms ImageList Component](how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md). + +### To display images in a list view + +1. Set the appropriate property—, , or —to the existing component you wish to use. + + These properties can be set in the designer with the Properties window, or in code. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#41](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#41)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#41](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#41)] + +2. Set the or property for each list item that has an associated icon. + + These properties can be set in code, or within the **ListViewItem Collection Editor**. To open the **ListViewItem Collection Editor**, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property on the **Properties** window. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#42](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#42)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#42](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#42)] + +## See also + +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) +- [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) +- [ImageList Component](imagelist-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..67a63b75cb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md @@ -0,0 +1,40 @@ +--- +title: Display Images in Cells of DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "cells [Windows Forms], displaying images" + - "data grids [Windows Forms], displaying in grids" + - "DataGridView control [Windows Forms], displaying images" + - "data grids [Windows Forms], displaying images in cells" +ms.assetid: 53b13d31-1b56-476d-9ab4-18bfac138a22 +--- +# How to: Display Images in Cells of the Windows Forms DataGridView Control +A picture or graphic is one of the values that you can display in a row of data. Frequently, these graphics take the form of an employee's photograph or a company logo. + + Incorporating pictures is simple when you display data within the control. The control natively handles any image format supported by the class, as well as the OLE picture format used by some databases. + + If the control's data source has a column of images, they will be displayed automatically by the control. + + The following code example demonstrates how to extract an icon from an embedded resource and convert it to a bitmap for display in every cell of an image column. For another example that replaces textual cell values with corresponding images, see [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#050](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#050)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#050](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#050)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- An embedded icon resource named `tree.ico`. + +- References to the , , and assemblies. + +## See also + +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) +- [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-option-buttons-in-a-menustrip-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-option-buttons-in-a-menustrip-windows-forms.md new file mode 100644 index 0000000000..e5d9d51092 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-option-buttons-in-a-menustrip-windows-forms.md @@ -0,0 +1,91 @@ +--- +title: "How to: Display Option Buttons in a MenuStrip" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "MenuStrip [Windows Forms], displaying option buttons" + - "displaying option buttons [Windows Forms], MenuStrip [Windows Forms]" + - "option buttons [Windows Forms], displaying in MenuStrip" +ms.assetid: 8b596af2-9ff8-4f7b-93d7-cba830e167f4 +--- +# How to: Display Option Buttons in a MenuStrip (Windows Forms) + +Option buttons, also known as radio buttons, are similar to check boxes except that users can select only one at a time. Although by default the class does not provide option-button behavior, the class does provide check-box behavior that you can customize to implement option-button behavior for menu items in a control. + +When the property of a menu item is `true`, users can click the item to toggle the display of a check mark. The property indicates the current state of the item. To implement basic option-button behavior, you must ensure that when an item is selected, you set the property for the previously selected item to `false`. + +The following procedures describe how to implement this and additional functionality in a class that inherits the class. The `ToolStripRadioButtonMenuItem` class overrides members such as and to provide the selection behavior and appearance of option buttons. Additionally, this class overrides the property so that options on a submenu are disabled unless the parent item is selected. + +## To implement option-button selection behavior + +1. Initialize the property to `true` to enable item selection. + + [!code-csharp[ToolStripRadioButtonMenuItem#110](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#110)] + [!code-vb[ToolStripRadioButtonMenuItem#110](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#110)] + +2. Override the method to clear the selection of the previously selected item when a new item is selected. + + [!code-csharp[ToolStripRadioButtonMenuItem#120](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#120)] + [!code-vb[ToolStripRadioButtonMenuItem#120](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#120)] + +3. Override the method to ensure that clicking an item that has already been selected will not clear the selection. + + [!code-csharp[ToolStripRadioButtonMenuItem#130](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#130)] + [!code-vb[ToolStripRadioButtonMenuItem#130](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#130)] + +## To modify the appearance of the option-button items + +1. Override the method to replace the default check-mark with an option button by using the class. + + [!code-csharp[ToolStripRadioButtonMenuItem#140](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#140)] + [!code-vb[ToolStripRadioButtonMenuItem#140](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#140)] + +2. Override the , , , and methods to track the state of the mouse and ensure that the method paints the correct option-button state. + + [!code-csharp[ToolStripRadioButtonMenuItem#150](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#150)] + [!code-vb[ToolStripRadioButtonMenuItem#150](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#150)] + +## To disable options on a submenu when the parent item is not selected + +1. Override the property so that the item is disabled when it has a parent item with both a value of `true` and a value of `false`. + + [!code-csharp[ToolStripRadioButtonMenuItem#160](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#160)] + [!code-vb[ToolStripRadioButtonMenuItem#160](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#160)] + +2. Override the method to subscribe to the event of the parent item. + + [!code-csharp[ToolStripRadioButtonMenuItem#170](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#170)] + [!code-vb[ToolStripRadioButtonMenuItem#170](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#170)] + +3. In the handler for the parent-item event, invalidate the item to update the display with the new enabled state. + + [!code-csharp[ToolStripRadioButtonMenuItem#180](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#180)] + [!code-vb[ToolStripRadioButtonMenuItem#180](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#180)] + +## Example + +The following code example provides the complete `ToolStripRadioButtonMenuItem` class, and a class and `Program` class to demonstrate the option-button behavior. + +[!code-csharp[ToolStripRadioButtonMenuItem#000](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs#000)] +[!code-vb[ToolStripRadioButtonMenuItem#000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb#000)] + +## Compiling the Code + +This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- +- [MenuStrip Control](menustrip-control-windows-forms.md) +- [How to: Implement a Custom ToolStripRenderer](how-to-implement-a-custom-toolstriprenderer.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-print-preview-in-windows-forms-applications.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-print-preview-in-windows-forms-applications.md new file mode 100644 index 0000000000..f542eba095 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-print-preview-in-windows-forms-applications.md @@ -0,0 +1,84 @@ +--- +title: Display Print Preview in Windows Forms apps +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "print preview [Windows Forms], displaying" + - "printing [Windows Forms], print preview" + - "examples [Windows Forms], print preview" +ms.assetid: e394134c-0886-4517-bd8d-edc4a3749eb5 +--- +# How to: Display Print Preview in Windows Forms Applications +You can use the control to enable users to display a document, often before it is to be printed. + + To do this, you need to specify an instance of the class; this is the document to be printed. For more information about using print preview with the component, see [How to: Print in Windows Forms Using Print Preview](../advanced/how-to-print-in-windows-forms-using-print-preview.md). + +> [!NOTE] +> To use the control at run time, users must have a printer installed on their computer, either locally or through a network, as this is partly how the component determines how a document will look when printed. + + The control uses the class. Additionally, the control uses the class, just as the component does. The print document specified in the control's property refers to instances of both the and classes, and these are used to render the document in the preview window. + +### To view pages using the PrintPreviewDialog control + +- Use the method to display the dialog box, specifying the to use. + + In the following code example, the control's event handler opens an instance of the control. The print document is specified in the property. In the example below, no print document is specified. + + The example requires that your form has a control, a component named `myDocument`, and a control. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Button1.Click + ' The print document 'myDocument' used below + ' is merely for an example. + ' You will have to specify your own print document. + PrintPreviewDialog1.Document = myDocument + PrintPreviewDialog1.ShowDialog() + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + // The print document 'myDocument' used below + // is merely for an example. + // You will have to specify your own print document. + printPreviewDialog1.Document = myDocument; + printPreviewDialog1.ShowDialog(); + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + // The print document 'myDocument' used below + // is merely for an example. + // You will have to specify your own print document. + printPreviewDialog1->Document = myDocument; + printPreviewDialog1->ShowDialog(); + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + + ```cpp + this->button1->Click += gcnew + System::EventHandler(this, &Form1::button1_Click); + ``` + +## See also + +- [PrintDocument Component](printdocument-component-windows-forms.md) +- [PrintPreviewDialog Control](printpreviewdialog-control-windows-forms.md) +- [Windows Forms Print Support](../advanced/windows-forms-print-support.md) +- [Windows Forms](../index.yml) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-scroll-bars-in-the-windows-forms-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-scroll-bars-in-the-windows-forms-richtextbox-control.md new file mode 100644 index 0000000000..e00f8a16ff --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-scroll-bars-in-the-windows-forms-richtextbox-control.md @@ -0,0 +1,41 @@ +--- +title: Display Scroll Bars in RichTextBox Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "text boxes [Windows Forms], displaying scroll bars" + - "scroll bars [Windows Forms], displaying in controls" + - "RichTextBox control [Windows Forms], displaying scroll bars" +ms.assetid: cdeb42e1-86e8-410c-ba46-18aec264ef5f +--- +# How to: Display Scroll Bars in the Windows Forms RichTextBox Control +By default, the Windows Forms control displays horizontal and vertical scroll bars as necessary. There are seven possible values for the property of the control, which are described in the table below. + +### To display scroll bars in a RichTextBox control + +1. Set the property to `true`. No type of scroll bar, including horizontal, will display if the property is set to `false`. + +2. Set the property to an appropriate value of the enumeration. + + |Value|Description| + |-----------|-----------------| + | (default)|Displays horizontal or vertical scroll bars, or both, only when text exceeds the width or length of the control.| + ||Never displays any type of scroll bar.| + ||Displays a horizontal scroll bar only when the text exceeds the width of the control. (For this to occur, the property must be set to `false`.)| + ||Displays a vertical scroll bar only when the text exceeds the height of the control.| + ||Displays a horizontal scroll bar when the property is set to `false`. The scroll bar appears dimmed when text does not exceed the width of the control.| + ||Always displays a vertical scroll bar. The scroll bar appears dimmed when text does not exceed the length of the control.| + ||Always displays a vertical scrollbar. Displays a horizontal scroll bar when the property is set to `false`. The scroll bars appear grayed when text does not exceed the width or length of the control.| + +3. Set the property to an appropriate value. + + |Value|Description| + |-----------|-----------------| + |`false`|Text in the control is not automatically adjusted to fit the width of the control, so it will scroll to the right until a line break is reached. Use this value if you chose horizontal scroll bars or both, above.| + |`true` (default)|Text in the control is automatically adjusted to fit the width of the control. The horizontal scrollbar will not appear. Use this value if you chose vertical scroll bars or none, above, to display one or more paragraphs.| + +## See also + +- +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-side-aligned-tabs-with-tabcontrol.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-side-aligned-tabs-with-tabcontrol.md new file mode 100644 index 0000000000..0d4c756471 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-side-aligned-tabs-with-tabcontrol.md @@ -0,0 +1,39 @@ +--- +title: "How to: Display Side-Aligned Tabs with TabControl" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "tab pages [Windows Forms], displaying side-aligned tabs" + - "tabs [Windows Forms], displaying side-aligned tabs" + - "TabControl control [Windows Forms], displaying side-aligned tabs" +ms.assetid: 110d5abd-3ae3-4ded-95bf-778aaac798a0 +--- +# How to: Display Side-Aligned Tabs with TabControl +The property of supports displaying tabs vertically (along the left or right edge of the control), as opposed to horizontally (across the top or bottom of the control). By default, this vertical display results in a poor user experience, because the property of the object does not display in the tab when visual styles are enabled. There is also no direct way to control the direction of the text within the tab. You can use owner draw on to improve this experience. + + The following procedure shows how to render right-aligned tabs, with the tab text running from left to right, by using the "owner draw" feature. + +### To display right-aligned tabs + +1. Add a to your form. + +2. Set the property to . + +3. Set the property to , so that all tabs are the same width. + +4. Set the property to the preferred fixed size for the tabs. Keep in mind that the property behaves as though the tabs were on top, although they are right-aligned. As a result, in order to make the tabs wider, you must change the property, and in order to make them taller, you must change the property. + + For best result with the code example below, set the of the tabs to 25 and the to 100. + +5. Set the property to . + +6. Define a handler for the event of that renders the text from left to right. + + [!code-csharp[TabControl.RightAlignedTabs#1](~/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.cs#1)] + [!code-vb[TabControl.RightAlignedTabs#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.vb#1)] + +## See also + +- [TabControl Control](tabcontrol-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md new file mode 100644 index 0000000000..e6270f0861 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md @@ -0,0 +1,32 @@ +--- +title: Display Subitems in Columns with ListView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "list items" + - "Details view" + - "ListView control [Windows Forms], adding ListSubItems" + - "subitems" +ms.assetid: e465f044-cde7-4fd9-a687-788a73a0f554 +--- +# How to: Display Subitems in Columns with the Windows Forms ListView Control +The Windows Forms control can display additional text, or subitems, for each item in the Details view. The first column displays the item text, for example an employee number. The second, third, and subsequent columns display the first, second, and subsequent associated subitems. + +### To add subitems to a list item + +1. Add any columns needed. Because the first column will display the item's property, you need one more column than there are subitems. For more information on adding columns, see [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md). + +2. Call the method of the collection returned by the property of an item. The code example below sets the employee name and department for a list item. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#61](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#61)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#61](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#61)] + +## See also + +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) +- [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md) +- [How to: Display Icons for the Windows Forms ListView Control](how-to-display-icons-for-the-windows-forms-listview-control.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-the-printdialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-the-printdialog-component.md new file mode 100644 index 0000000000..751dcd82c3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-the-printdialog-component.md @@ -0,0 +1,27 @@ +--- +title: "How to display the PrintDialog component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Print dialog box [Windows Forms], displaying" + - "PrintDialog component [Windows Forms], displaying" + - "printing [Windows Forms], displaying print dialog box" +ms.assetid: 745a8db7-0526-4b21-b09d-18e13ed32014 +--- +# How to display the PrintDialog component + +The component is the standard Windows print dialog box that many of your users will be familiar with. Because your users will be immediately comfortable with it, it would be beneficial for you to use the component. + +## To display the PrintDialog component + +- Call the method from within the code of your application. + + Once the component is shown, users will interact with it, setting the properties of the print job. These are saved in the class (and the class, if the user accesses the [PageSetupDialog Component](pagesetupdialog-component-windows-forms.md) through the component) associated with that print job. You can then make calls to the properties they set to determine the specifics of the print job. + +## See also + +- [How to: Create Standard Windows Forms Print Jobs](../advanced/how-to-create-standard-windows-forms-print-jobs.md) +- [How to: Capture User Input from a PrintDialog at Run Time](../advanced/how-to-capture-user-input-from-a-printdialog-at-run-time.md) +- [PrintPreviewDialog Control](printpreviewdialog-control-windows-forms.md) +- [PrintDialog Component](printdialog-component-windows-forms.md) +- [Windows Forms Print Support](../advanced/windows-forms-print-support.md) +- [Windows Forms Controls](index.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-time-with-the-datetimepicker-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-time-with-the-datetimepicker-control.md new file mode 100644 index 0000000000..2366479306 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-time-with-the-datetimepicker-control.md @@ -0,0 +1,42 @@ +--- +title: "How to: Display Time with the DateTimePicker Control" +description: Learn how to use the Windows Forms DateTimePicker control to enable users to select a date and time, and to display that date and time in the specified format. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "time [Windows Forms], displaying in DateTimePicker control" + - "examples [Windows Forms], DateTimePicker control" + - "DateTimePicker control [Windows Forms], displaying time" +ms.assetid: 0c1c8b40-1b50-4301-a90c-39516775ccb1 +--- +# How to: Display Time with the DateTimePicker Control +If you want your application to enable users to select a date and time, and to display that date and time in the specified format, use the control. The following procedure shows how to use the control to display the time. + +### To display the time with the DateTimePicker control + +1. Set the property to + + [!code-csharp[System.Windows.Forms.DateTimePickerTimeOnly#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.DateTimePickerTimeOnly#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/VB/Form1.vb#2)] + +2. Set the property for the to `true`. + + [!code-csharp[System.Windows.Forms.DateTimePickerTimeOnly#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.DateTimePickerTimeOnly#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/VB/Form1.vb#3)] + +## Example + The following code sample shows how to create a that enables users to choose a time only. + + [!code-csharp[System.Windows.Forms.DateTimePickerTimeOnly#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.DateTimePickerTimeOnly#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [DateTimePicker Control](datetimepicker-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-display-web-style-links-with-the-windows-forms-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-web-style-links-with-the-windows-forms-richtextbox-control.md new file mode 100644 index 0000000000..3069253a03 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-display-web-style-links-with-the-windows-forms-richtextbox-control.md @@ -0,0 +1,120 @@ +--- +title: Display Web-Style Links with RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "text boxes [Windows Forms], displaying Web links" + - "examples [Windows Forms], text boxes" + - "RichTextBox control [Windows Forms], linking to Web pages" +ms.assetid: 95089a37-a202-4f7a-94ee-6ee312908851 +--- +# How to: Display Web-Style Links with the Windows Forms RichTextBox Control + +The Windows Forms control can display Web links as colored and underlined. You can write code that opens a browser window showing the Web site specified in the link text when the link is clicked. + +### To link to a Web page with the RichTextBox control + +1. Set the property to a string that includes a valid URL (for example, "https://www.microsoft.com/"). + +2. Make sure the property is set to `true` (the default). + +3. Create a new global instance of the object. + +4. Write an event handler for the event that sends the browser the desired text. + + In the example below, the event opens an instance of Internet Explorer to the URL specified in the property of the control. This example assumes a form with a control. + + > [!IMPORTANT] + > In calling the method, you will encounter a exception if you are running the code in a partial-trust context because of insufficient privileges. For more information, see [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics). + + ```vb + Public p As New System.Diagnostics.Process + Private Sub RichTextBox1_LinkClicked _ + (ByVal sender As Object, ByVal e As _ + System.Windows.Forms.LinkClickedEventArgs) _ + Handles RichTextBox1.LinkClicked + ' Call Process.Start method to open a browser + ' with link text as URL. + p = System.Diagnostics.Process.Start("IExplore.exe", e.LinkText) + End Sub + ``` + + ```csharp + public System.Diagnostics.Process p = new System.Diagnostics.Process(); + + private void richTextBox1_LinkClicked(object sender, + System.Windows.Forms.LinkClickedEventArgs e) + { + // Call Process.Start method to open a browser + // with link text as URL. + p = System.Diagnostics.Process.Start("IExplore.exe", e.LinkText); + } + ``` + + ```cpp + public: + System::Diagnostics::Process ^ p; + + private: + void richTextBox1_LinkClicked(System::Object ^ sender, + System::Windows::Forms::LinkClickedEventArgs ^ e) + { + // Call Process.Start method to open a browser + // with link text as URL. + p = System::Diagnostics::Process::Start("IExplore.exe", + e->LinkText); + } + ``` + + (Visual C++) You must initialize process `p`, which you can do by including the following statement in the constructor of your form: + + ```cpp + p = gcnew System::Diagnostics::Process(); + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.richTextBox1.LinkClicked += new + System.Windows.Forms.LinkClickedEventHandler + (this.richTextBox1_LinkClicked); + ``` + + ```cpp + this->richTextBox1->LinkClicked += gcnew + System::Windows::Forms::LinkClickedEventHandler + (this, &Form1::richTextBox1_LinkClicked); + ``` + + It is important to immediately stop the process you have created once you have finished working with it. Referring to the code presented above, your code to stop the process might look like this: + + ```vb + Public Sub StopWebProcess() + p.Kill() + End Sub + ``` + + ```csharp + public void StopWebProcess() + { + p.Kill(); + } + ``` + + ```cpp + public: void StopWebProcess() + { + p->Kill(); + } + ``` + +## See also + +- +- +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-dock-controls-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-dock-controls-on-windows-forms.md new file mode 100644 index 0000000000..a7f5928396 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-dock-controls-on-windows-forms.md @@ -0,0 +1,46 @@ +--- +title: Dock Controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], docking" + - "Explorer-style applications [Windows Forms], creating" + - "Windows Forms controls, filling client area" +ms.assetid: bc11f2e4-e90a-4830-b0e2-f43b6e2b8bec +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Dock controls on Windows Forms + +You can dock controls to the edges of your form or have them fill the control's container (either a form or a container control). For example, Windows Explorer docks its control to the left side of the window and its control to the right side of the window. Use the property for all visible Windows Forms controls to define the docking mode. + +> [!NOTE] +> Controls are docked in reverse z-order. + +The property interacts with the property. For more information, see [AutoSize Property Overview](autosize-property-overview.md). + +## To dock a control + +1. In Visual Studio, select the control that you want to dock. + +2. In the **Properties** window, click the arrow to the right of the property. + + An editor is displayed that shows a series of boxes representing the edges and the center of the form. + +3. Click the button that represents the edge of the form where you want to dock the control. To fill the contents of the control's form or container control, click the center box. Click **(none)** to disable docking. + + The control is automatically resized to fit the boundaries of the docked edge. + + > [!NOTE] + > Inherited controls must be `Protected` to be able to be docked. To change the access level of a control, set its **Modifier** property in the **Properties** window. + +## See also + +- [Windows Forms Controls](index.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) +- [How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md) +- [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) +- [AutoSize Property Overview](autosize-property-overview.md) +- [How to: Anchor Controls on Windows Forms](how-to-anchor-controls-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-download-a-file-in-the-background.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-download-a-file-in-the-background.md new file mode 100644 index 0000000000..d6b1bd893c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-download-a-file-in-the-background.md @@ -0,0 +1,64 @@ +--- +title: "How to: Download a File in the Background" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "BackgroundWorker component" + - "background tasks" + - "Asynchronous Pattern" + - "forms [Windows Forms], multithreading" + - "components [Windows Forms], asynchronous" + - "forms [Windows Forms], background operations" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: 9b7bc5ae-051c-4904-9720-18f6667388bd +--- +# How to: Download a File in the Background +Downloading a file is a common task, and it is often useful to run this potentially time-consuming operation on a separate thread. Use the component to accomplish this task with very little code. + +## Example + The following code example demonstrates how to use a component to load an XML file from a URL. When the user clicks the **Download** button, the event handler calls the method of a component to start the download operation. The button is disabled for the duration of the download, and then enabled when the download is complete. A displays the contents of the file. + + [!code-csharp[System.ComponentModel.BackgroundWorker.IsBusy#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs#1)] + [!code-vb[System.ComponentModel.BackgroundWorker.IsBusy#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb#1)] + + **Downloading the file** + + The file is downloaded on the component's worker thread, which runs the event handler. This thread starts when your code calls the method. + + [!code-csharp[System.ComponentModel.BackgroundWorker.IsBusy#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs#3)] + [!code-vb[System.ComponentModel.BackgroundWorker.IsBusy#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb#3)] + + **Waiting for a BackgroundWorker to finish** + + The `downloadButton_Click` event handler demonstrates how to wait for a component to finish its asynchronous task. + + If you only want the application to respond to events and do not want to do any work in the main thread while you wait for the background thread to complete, just exit the handler. + + If you want to continue doing work in the main thread, use the property to determine whether the thread is still running. In the example, a progress bar is updated while the download is processing. Be sure to call the method to keep the UI responsive. + + [!code-csharp[System.ComponentModel.BackgroundWorker.IsBusy#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs#2)] + [!code-vb[System.ComponentModel.BackgroundWorker.IsBusy#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb#2)] + + **Displaying the result** + + The `backgroundWorker1_RunWorkerCompleted` method handles the event and is called when the background operation is completed. This method first checks the property. If is `null`, then this method displays the contents of the file. It then enables the download button, which was disabled when the download began, and it resets the progress bar. + + [!code-csharp[System.ComponentModel.BackgroundWorker.IsBusy#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs#4)] + [!code-vb[System.ComponentModel.BackgroundWorker.IsBusy#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb#4)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing, System.Windows.Forms, and System.Xml assemblies. + +## Robust Programming + Always check the property in your event handler before attempting to access the property or any other object that may have been affected by the event handler. + +## See also + +- +- [How to: Run an Operation in the Background](how-to-run-an-operation-in-the-background.md) +- [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md new file mode 100644 index 0000000000..68fe51d298 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md @@ -0,0 +1,43 @@ +--- +title: "How to: Edit Columns and Rows in a TableLayoutPanel Control" +description: Learn how to use the Column and Row Styles dialog box to edit the rows and columns of your Windows Forms controls. +ms.date: "03/30/2017" +f1_keywords: + - "net.ComponentModel.StyleCollectionEditor" +helpviewer_keywords: + - "columns [Windows Forms], editing" + - "TableLayoutPanel control [Windows Forms], editing" + - "rows [Windows Forms], editing" +ms.assetid: c367ed43-40dc-49eb-9e0f-ba70e83dfec0 +--- +# How to: Edit Columns and Rows in a TableLayoutPanel Control + +You can use the collection editor of the control, called the **Column and Row Styles** dialog box, to edit the rows and columns of your controls. + +> [!NOTE] +> If you want a control to span multiple rows or columns, set the `RowSpan` and `ColumnSpan` properties on the control. For more information, see [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md). +> +> If you want to align a control within a cell, or if you want a control to stretch within a cell, use the control's property. For more information, see [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md). + +## To edit rows and columns + +1. Drag a control from the **Toolbox** onto your form. + +2. Click the control's designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) and select **Edit Rows and Columns** to open the **Column and Row Styles** dialog box. You can also right click on the control and select **Edit Rows and Columns** from the shortcut menu. + +3. To add or remove columns, select **Columns** from the **Member type** drop-down list box. + +4. To add or remove rows, select **Rows** from the **Member type** drop-down list box. + +5. Click the **Add** button to add a row or column to the end of the **Member** list. + +6. Click the **Insert** button to add a row or column before the currently selected item in the list. + +7. If you are adding a row or column, select the **Size Type** for the new row or column. For more information, see . + +8. To remove a row or column, click the **Remove** button to delete the currently selected item in the **Member** list. + +## See also + +- +- [TableLayoutPanel Control](tablelayoutpanel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-autocomplete-in-toolstrip-controls-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-autocomplete-in-toolstrip-controls-in-windows-forms.md new file mode 100644 index 0000000000..a59ef11eaa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-autocomplete-in-toolstrip-controls-in-windows-forms.md @@ -0,0 +1,95 @@ +--- +title: "How to: Enable AutoComplete in ToolStrip Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "AutoComplete [Windows Forms], examples" + - "toolbars [Windows Forms], AutoComplete" + - "examples [Windows Forms], toolbars" + - "AutoComplete [Windows Forms], enabling in toolbars" + - "ToolStripComboBox class [Windows Forms], examples" + - "ToolStrip control [Windows Forms], AutoComplete" +ms.assetid: fd66d085-1af1-45d4-930a-cde944da2e16 +--- +# How to: Enable AutoComplete in ToolStrip Controls in Windows Forms +The following procedure combines a with a that can be dropped down to show a list of items, such as recently visited Web sites. If the user types a character that matches the first character of one of the items in the list, the item is immediately displayed. + +> [!NOTE] +> Automatic completion works with `ToolStrip` controls in the same way that it works with traditional controls such as and . + +### To enable AutoComplete in a ToolStrip control + +1. Create a control and add items to it. + + ```vb + ToolStrip1 = New System.Windows.Forms.ToolStrip + ToolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem()_ + {ToolStripLabel1, ToolStripComboBox1}) + ``` + + ```csharp + toolStrip1 = new System.Windows.Forms.ToolStrip(); + toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] + {toolStripLabel1, toolStripComboBox1}); + ``` + +2. Set the property of the label and the combo box to so that the list is always available regardless of the form's size. + + ```vb + ToolStripLabel1.Overflow = _ + System.Windows.Forms.ToolStripItemOverflow.Never + ToolStripComboBox1.Overflow = _ + System.Windows.Forms.ToolStripItemOverflow.Never + ``` + + ```csharp + toolStripLabel1.Overflow = _ + System.Windows.Forms.ToolStripItemOverflow.Never + toolStripComboBox1.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never + ``` + +3. Add words to the Items collection of the control. + + ```vb + ToolStripComboBox1.Items.AddRange(New Object() {"First Item", _ + "Second Item", "Third Item"}) + ``` + + ```csharp + toolStripComboBox1.Items.AddRange(new object[] {"First item", "Second item", "Third item"}); + ``` + +4. Set the property of the combo box to . + + ```vb + ToolStripComboBox1.AutoCompleteMode = _ + System.Windows.Forms.AutoCompleteMode.Append + ``` + + ```csharp + toolStripComboBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append; + ``` + +5. Set the property of the combo box to . + + ```vb + ToolStripComboBox1.AutoCompleteSource = _ + System.Windows.Forms.AutoCompleteSource.ListItems + ``` + + ```csharp + toolStripComboBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; + ``` + +## See also + +- +- +- +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md new file mode 100644 index 0000000000..a0261ca88c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md @@ -0,0 +1,39 @@ +--- +title: "How to: Enable Check Margins and Image Margins in ContextMenuStrip Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ShowCheckMargin property [Windows Forms]" + - "ShowImageMargin property [Windows Forms]" + - "ToolStrip control [Windows Forms]" + - "MenuStrip control [Windows Forms]" +ms.assetid: eb584e71-59da-4012-aaca-dbe1c7c7a156 +--- +# How to: Enable Check Margins and Image Margins in ContextMenuStrip Controls +You can customize the objects in your control with check marks and custom images. + +## Example + The following code example demonstrates how to create menu items that have check marks and custom images. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#60](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#60)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#60](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#60)] + + Set the and properties to specify when check marks and custom images appear in your menu items. + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..77d4c483a9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,37 @@ +--- +title: Enable Column Reordering in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], column order" + - "data grids [Windows Forms], reordering columns" + - "columns [Windows Forms], reordering" +ms.assetid: cc20eae3-e4db-493f-95ce-a4215e29472a +--- +# How to: Enable Column Reordering in the Windows Forms DataGridView Control +When you enable column reordering in the control, users can move a column to a new position by dragging the column header with the mouse. In the control, the property value determines whether users can move columns to different positions. + + There is support for this task in Visual Studio. Also see [How to: Enable Column Reordering in the Windows Forms DataGridView Control Using the Designer](enable-column-reordering-in-the-datagrid-using-the-designer.md). + +### To enable column reordering programmatically + +- Set the property to `true`. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#060](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#060)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#060](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#060)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) +- [How to: Freeze Columns in the Windows Forms DataGridView Control](how-to-freeze-columns-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-reordering-of-toolstrip-items-at-run-time-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-reordering-of-toolstrip-items-at-run-time-in-windows-forms.md new file mode 100644 index 0000000000..38522f224f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-reordering-of-toolstrip-items-at-run-time-in-windows-forms.md @@ -0,0 +1,37 @@ +--- +title: "How to: Enable Reordering of ToolStrip Items at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], examples" + - "examples [Windows Forms], toolbars" + - "toolbars [Windows Forms], rearranging controls" + - "ToolStrip control [Windows Forms], reordering items" +ms.assetid: 8480b69a-379f-4dc2-8dcf-365ed93692b2 +--- +# How to: Enable Reordering of ToolStrip Items at Run Time in Windows Forms +You can enable the user to rearrange controls on the . + +### To enable ToolStripItem rearrangement at run time + +- Set the property to `true`. By default, is `false`. + + At run time, the user holds down the ALT key and the left mouse button to drag a to a different location on the . + + ```vb + toolStrip1.AllowItemReorder = True + ``` + + ```csharp + toolStrip1.AllowItemReorder = true; + ``` + +## See also + +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-the-tab-key-to-move-out-of-a-toolstrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-the-tab-key-to-move-out-of-a-toolstrip-control.md new file mode 100644 index 0000000000..4f11a16b1f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-the-tab-key-to-move-out-of-a-toolstrip-control.md @@ -0,0 +1,23 @@ +--- +title: "How to: Enable the TAB Key to Move Out of a ToolStrip Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], moving between" + - "TAB key [Windows Forms], enabling" + - "ToolStrip control [Windows Forms], moving from" +ms.assetid: 40f9e88b-09a3-428e-8da8-c00bb65079c6 +--- +# How to: Enable the TAB Key to Move Out of a ToolStrip Control +Use the following procedure to enable the user to press the TAB key to move out of a to the next control in the tab order. + + The accepts the first press of the TAB key, and the arrow keys select items within the . When the user presses the TAB key a second time, it takes the user to the next control in the tab order. + +### To enable the user to press the TAB key to move out of a ToolStrip to the next control + +- Set the property of the to `true`. + +## See also + +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-tile-view-in-a-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-tile-view-in-a-windows-forms-listview-control.md new file mode 100644 index 0000000000..86dcacd126 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-enable-tile-view-in-a-windows-forms-listview-control.md @@ -0,0 +1,55 @@ +--- +title: Enable Tile View in ListView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "tile view feature" + - "tiling" + - "Windows Forms, controls" + - "ListView control [Windows Forms], tile view" +ms.assetid: c20e67a3-2d94-413d-9fcf-ecbd0fe251da +--- +# How to: Enable Tile View in a Windows Forms ListView Control +With the tile view feature of the control, you can provide a visual balance between graphical and textual information. The textual information displayed for an item in tile view is the same as the column information defined for details view. Tile view works in combination with either the grouping or insertion mark features in the control. + + The tile view uses a 32 x 32 pixel icon and several lines of text, as shown in the following images. + + ![Tile View in a ListView Control](./media/how-to-enable-tile-view-in-a-windows-forms-listview-control/tile-view-in-listview-control.gif "Tile view icons and text") + + To enable tile view, set the property to . You can adjust the size of the tiles by setting the property, and the number of text lines displayed in the tile by adjusting the collection. + +### To set tile view programmatically + +1. Use the enumeration of the control. + + ```vb + ListView1.View = View.Tile + ``` + + ```csharp + listView1.View = View.Tile; + ``` + +## Example + The following complete code example demonstrates Tile view with tiles modified to show three lines of text. The tile size has been adjusted to prevent line-wrapping. + + [!code-cpp[System.Windows.Forms.ListView.Tiling#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CPP/listviewtilingexample.cpp#1)] + [!code-csharp[System.Windows.Forms.ListView.Tiling#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CS/listviewtilingexample.cs#1)] + [!code-vb[System.Windows.Forms.ListView.Tiling#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/VB/listviewtilingexample.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +- An icon file named book.ico in the same directory as the executable file. + +## See also + +- +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-expose-properties-of-constituent-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-expose-properties-of-constituent-controls.md new file mode 100644 index 0000000000..76d74bd060 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-expose-properties-of-constituent-controls.md @@ -0,0 +1,58 @@ +--- +title: "How to: Expose Properties of Constituent Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "user controls [Windows Forms], exposing constituent controls" + - "controls [Windows Forms], constituent" + - "custom controls [Windows Forms], exposing properties" + - "constituent controls" +ms.assetid: 5c1ec98b-aa48-4823-986e-4712551cfdf1 +--- +# How to: Expose Properties of Constituent Controls +The controls that make up a composite control are called *constituent controls*. These controls are normally declared private, and thus cannot be accessed by the developer. If you want to make properties of these controls available to future users, you must expose them to the user. A property of a constituent control is exposed by creating a property in the user control, and using the `get` and `set` accessors of that property to effect the change in the private property of the constituent control. + + Consider a hypothetical user control with a constituent button named `MyButton`. In this example, when the user requests the `ConstituentButtonBackColor` property, the value stored in the property of `MyButton` is delivered. When the user assigns a value to this property, that value is automatically passed to the property of `MyButton` and the `set` code will execute, changing the color of `MyButton`. + + The following example shows how to expose the property of the constituent button: + +```vb +Public Property ButtonColor() as System.Drawing.Color + Get + Return MyButton.BackColor + End Get + Set(Value as System.Drawing.Color) + MyButton.BackColor = Value + End Set +End Property +``` + +```csharp +public Color ButtonColor +{ + get + { + return(myButton.BackColor); + } + set + { + myButton.BackColor = value; + } +} +``` + +### To expose a property of a constituent control + +1. Create a public property for your user control. + +2. In the `get` section of the property, write code that retrieves the value of the property you want to expose. + +3. In the `set` section of the property, write code that passes the value of the property to the exposed property of the constituent control. + +## See also + +- +- [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-format-data-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-format-data-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..331dd0a55d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-format-data-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,74 @@ +--- +title: Format Data in DataGridView Control +description: Learn how to format cell values using the DefaultCellStyle property of a Windows Forms DataGridView control and of specific columns in a control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], formatting data" + - "data [Windows Forms], formatting in DataGridView control" + - "data grids [Windows Forms], enabling wordwrap" + - "currency values [Windows Forms], formatting in data grids" + - "data grids [Windows Forms], currency values" + - "data grids [Windows Forms], formatting data" + - "data grids [Windows Forms], text alignment" + - "data grids [Windows Forms], date values" + - "cells [Windows Forms], text alignment" +ms.assetid: 8c33543c-9c08-4636-a65a-fdf714a529b7 +--- +# How to: Format Data in the Windows Forms DataGridView Control +The following procedures demonstrate basic formatting of cell values using the property of a control and of specific columns in a control. For information about advanced data formatting, see [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md). + +### To format currency and date values + +- Set the property of a . The following code example sets the format for specific columns using the property of the columns. Values in the `UnitPrice` column appear in the current culture-specific currency format, with negative values surrounded by parentheses. Values in the `ShipDate` column appear in the current culture-specific short date format. For more information about values, see [Formatting Types](https://docs.microsoft.com/dotnet/standard/base-types/formatting-types). + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#071](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#071)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#071](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#071)] + +### To customize the display of null database values + +- Set the property of a . The following code example uses the property to display "no entry" in all cells containing values equal to . + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#073](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#073)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#073](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#073)] + +### To enable wordwrap in text-based cells + +- Set the property of a to one of the enumeration values. The following code example uses the property to set the wrap mode for the entire control. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#074](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#074)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#074](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#074)] + +### To specify the text alignment of DataGridView cells + +- Set the property of a to one of the enumeration values. The following code example sets the alignment for a specific column using the property of the column. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#072](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#072)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#072](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#072)] + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#070](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#070)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#070](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#070)] + +## Compiling the Code + These examples require: + +- A control named `dataGridView1` that contains a column named `UnitPrice`, a column named `ShipDate`, and a column named `CustomerName`. + +- References to the , , and assemblies. + +## Robust Programming + For maximum scalability, you should share objects across multiple rows, columns, or cells that use the same styles rather than setting the style properties for each element separately. For more information, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [Data Formatting in the Windows Forms DataGridView Control](data-formatting-in-the-windows-forms-datagridview-control.md) +- [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md) +- [Formatting Types](https://docs.microsoft.com/dotnet/standard/base-types/formatting-types) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-format-the-windows-forms-datagrid-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-format-the-windows-forms-datagrid-control-using-the-designer.md new file mode 100644 index 0000000000..9880f0ae36 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-format-the-windows-forms-datagrid-control-using-the-designer.md @@ -0,0 +1,98 @@ +--- +title: Format DataGrid Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "columns [Windows Forms], DataGrid controls" + - "colors [Windows Forms], applying to DataGrid controls" + - "DataGrid control [Windows Forms], formatting" + - "DataGrid control [Windows Forms], default styles" + - "tables [Windows Forms], formatting in DataGrid control" + - "formatting [Windows Forms]" +ms.assetid: 533b9814-6124-49dc-9fda-085f1502609f +--- +# How to: Format the Windows Forms DataGrid Control Using the Designer + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + +Applying different colors to various parts of a control can help to make the information in it easier to read and interpret. Color can be applied to rows and columns. Rows and columns can also be hidden or shown at your discretion. + +There are three basic aspects of formatting the control: + +- You can set properties to establish a default style in which data is displayed. + +- From that base, you can then customize the way certain tables are displayed at run time. + +- Finally, you can modify which columns are displayed in the data grid as well as the colors and other formatting that is shown. + +As an initial step in formatting a data grid, you can set the properties of the itself. These color and format choices form a base from which you can then make changes depending on the data tables and columns displayed. + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). In Visual Studio 2005, the control is not in the **Toolbox** by default. For more information, see [How to: Add Items to the Toolbox](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms165355(v=vs.100)). + +### To establish a default style for the DataGrid control + +1. Select the control. + +2. In the **Properties** window, set the following properties, as appropriate. + + |Property|Description| + |--------------|-----------------| + ||The `BackColor` property defines the color of the even-numbered rows of the grid. When you set the property to a different color, every other row is set to this new color (rows 1, 3, 5, and so on).| + ||The background color of the even-numbered rows of the grid (rows 0, 2, 4, 6, and so on).| + ||Whereas the and properties determines the color of rows in the grid, the property determines the color of the area outside the row area, which is only visible when the grid is scrolled to the bottom, or if only a few rows are contained in the grid.| + ||The grid's border style, one of the enumeration values.| + ||The background color of the grid's window caption which appears immediately above the grid.| + ||The font of the caption at the top of the grid.| + ||The background color of the grid's window caption.| + ||The font used to display the text in the grid.| + ||The color of the font displayed by the data in the rows of the data grid.| + ||The color of the grid lines of the data grid.| + ||The style of the lines separating the cells of the grid, one of the enumeration values.| + ||The background color of row and column headers.| + ||The font used for the column headers.| + ||The foreground color of the grid's column headers, including the column header text and the plus sign (+) and minus sign (-) glyphs that expand and collapse rows when multiple related tables are displayed.| + ||The color of text of all the links in the data grid, including links to child tables, the relation name, and so on.| + ||In a child table, this is the background color of the parent rows.| + ||In a child table, this is the foreground color of the parent rows.| + ||Determines whether the table and column names are displayed in the parent row, by means of the enumeration.| + ||The default width (in pixels) of columns in the grid. Set this property before resetting the and properties (either separately, or through the method), or the property will have no effect.

The property cannot be set to a value less than 0.| + ||The row height (in pixels) of rows in the grid. Set this property before resetting the and properties (either separately, or through the method), or the property will have no effect.

The property cannot be set to a value less than 0.| + ||The width of the row headers of the grid.| + ||When a row or cell is selected, this is the background color.| + ||When a row or cell is selected, this is the foreground color.| + + > [!NOTE] + > When you are customizing the colors of controls, it is possible to make the control inaccessible due to poor color choice (for example, red and green). Use the colors available on the **System Colors** palette to avoid this issue. + + The following procedure requires a control bound to a data table. For more information, see [How to: Bind the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md). + +### To set the table and column style of a data table at design time + +1. Select the control on your form. + +2. In the **Properties** window, select the property and click the **Ellipsis** (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button. + +3. In the **DataGridTableStyle Collection Editor** dialog box, click **Add** to add a table style to the collection. + + With the **DataGridTableStyle Collection Editor**, you can add and remove table styles, set display and layout properties, and set the mapping name for the table styles. + +4. Set the property to the mapping name for each table style. + + The mapping name is used to specify which table style should be used with which table. + +5. In the **DataGridTableStyle Collection Editor**, select the property and click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)). + +6. In the **DataGridColumnStyle Collection Editor** dialog box, add column styles to the table style you created. + + With the **DataGridColumnStyle Collection Editor**, you can add and remove column styles, set display and layout properties, and set the mapping name and formatting strings for the data columns. + + > [!NOTE] + > For more information about formatting strings, see [Formatting Types](https://docs.microsoft.com/dotnet/standard/base-types/formatting-types). + +## See also + +- +- +- +- [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) +- [DataGrid Control](datagrid-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-format-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-format-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..b0aa944c1c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-format-the-windows-forms-datagrid-control.md @@ -0,0 +1,156 @@ +--- +title: Format DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "columns [Windows Forms], DataGrid control" + - "colors [Windows Forms], applying to DataGrid controls" + - "DataGrid control [Windows Forms], formatting" + - "columns [Windows Forms], formatting in DataGrid control" + - "DataGrid control [Windows Forms], default styles" + - "tables [Windows Forms], formatting in DataGrid control" + - "formatting [Windows Forms]" +ms.assetid: a50fcc3b-8abf-47ec-9029-7f268af4ddb1 +--- +# How to: Format the Windows Forms DataGrid Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + Applying different colors to various parts of a control can help to make the information in it easier to read and interpret. Color can be applied to rows and columns. Rows and columns can also be hidden or shown at your discretion. + + There are three basic aspects of formatting the control. You can set properties to establish a default style in which data is displayed. From that base, you can then customize the way certain tables are displayed at run time. Finally, you can modify which columns are displayed in the data grid as well as the colors and other formatting that is shown. + + As an initial step in formatting a data grid, you can set the properties of the itself. These color and format choices form a base from which you can then make changes depending on the data tables and columns displayed. + +### To establish a default style for the DataGrid control + +1. Set the following properties as appropriate: + + |Property|Description| + |--------------|-----------------| + ||The property defines the color of the even-numbered rows of the grid. When you set the property to a different color, every other row is set to this new color (rows 1, 3, 5, and so on).| + ||The background color of the even-numbered rows of the grid (rows 0, 2, 4, 6, and so on).| + ||Whereas the and properties determines the color of rows in the grid, the property determines the color of the nonrow area, which is only visible when the grid is scrolled to the bottom, or if only a few rows are contained in the grid.| + ||The grid's border style, one of the enumeration values.| + ||The background color of the grid's window caption which appears immediately above the grid.| + ||The font of the caption at the top of the grid.| + ||The background color of the grid's window caption.| + ||The font used to display the text in the grid.| + ||The color of the font displayed by the data in the rows of the data grid.| + ||The color of the grid lines of the data grid.| + ||The style of the lines separating the cells of the grid, one of the enumeration values.| + ||The background color of row and column headers.| + ||The font used for the column headers.| + ||The foreground color of the grid's column headers, including the column header text and the plus/minus glyphs (to expand rows when multiple related tables are displayed).| + ||The color of text of all the links in the data grid, including links to child tables, the relation name, and so on.| + ||In a child table, this is the background color of the parent rows.| + ||In a child table, this is the foreground color of the parent rows.| + ||Determines whether the table and column names are displayed in the parent row, by means of the enumeration.| + ||The default width (in pixels) of columns in the grid. Set this property before resetting the and properties (either separately, or through the method), or the property will have no effect.

The property cannot be set to a value less than 0.| + ||The row height (in pixels) of rows in the grid. Set this property before resetting the and properties (either separately, or through the method), or the property will have no effect.

The property cannot be set to a value less than 0.| + ||The width of the row headers of the grid.| + ||When a row or cell is selected, this is the background color.| + ||When a row or cell is selected, this is the foreground color.| + + > [!NOTE] + > Keep in mind, when customizing the colors of controls, that it is possible to make the control inaccessible, due to poor color choice (for example, red and green). Use the colors available on the **System Colors** palette to avoid this issue. + + The following procedures assume your form has a control bound to a data table. For more information, see [Binding the Windows Forms DataGrid Control to a Data Source](how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md). + +### To set the table and column style of a data table programmatically + +1. Create a new table style and set its properties. + +2. Create a column style and set its properties. + +3. Add the column style to the table style's column styles collection. + +4. Add the table style to the data grid's table styles collection. + +5. In the example below, create an instance of a new and set its property. + +6. Create a new instance of a **GridColumnStyle** and set its **MappingName** (and some other layout and display properties). + +7. Repeat steps 2 through 6 for each column style you want to create. + + The following example illustrates how a is created, because a name is to be displayed in the column. Additionally, you add the column style to the of the table style, and you add the table style to the of the data grid. + + ```vb + Private Sub CreateAuthorFirstNameColumn() + ' Add a GridTableStyle and set the MappingName + ' to the name of the DataTable. + Dim TSAuthors As New DataGridTableStyle() + TSAuthors.MappingName = "Authors" + + ' Add a GridColumnStyle and set the MappingName + ' to the name of a DataColumn in the DataTable. + ' Set the HeaderText and Width properties. + Dim TCFirstName As New DataGridTextBoxColumn() + TCFirstName.MappingName = "AV_FName" + TCFirstName.HeaderText = "First Name" + TCFirstName.Width = 75 + TSAuthors.GridColumnStyles.Add(TCFirstName) + + ' Add the DataGridTableStyle instance to + ' the GridTableStylesCollection. + myDataGrid.TableStyles.Add(TSAuthors) + End Sub + ``` + + ```csharp + private void addCustomDataTableStyle() + { + // Add a GridTableStyle and set the MappingName + // to the name of the DataTable. + DataGridTableStyle TSAuthors = new DataGridTableStyle(); + TSAuthors.MappingName = "Authors"; + + // Add a GridColumnStyle and set the MappingName + // to the name of a DataColumn in the DataTable. + // Set the HeaderText and Width properties. + DataGridColumnStyle TCFirstName = new DataGridTextBoxColumn(); + TCFirstName.MappingName = " AV_FName"; + TCFirstName.HeaderText = "First Name"; + TCFirstName.Width = 75; + TSAuthors.GridColumnStyles.Add(TCFirstName); + + // Add the DataGridTableStyle instance to + // the GridTableStylesCollection. + dataGrid1.TableStyles.Add(TSAuthors); + } + ``` + + ```cpp + private: + void addCustomDataTableStyle() + { + // Add a GridTableStyle and set the MappingName + // to the name of the DataTable. + DataGridTableStyle^ TSAuthors = new DataGridTableStyle(); + TSAuthors->MappingName = "Authors"; + + // Add a GridColumnStyle and set the MappingName + // to the name of a DataColumn in the DataTable. + // Set the HeaderText and Width properties. + DataGridColumnStyle^ TCFirstName = gcnew DataGridTextBoxColumn(); + TCFirstName->MappingName = "AV_FName"; + TCFirstName->HeaderText = "First Name"; + TCFirstName->Width = 75; + TSAuthors->GridColumnStyles->Add(TCFirstName); + + // Add the DataGridTableStyle instance to + // the GridTableStylesCollection. + dataGrid1->TableStyles->Add(TSAuthors); + } + ``` + +## See also + +- +- +- +- [How to: Delete or Hide Columns in the Windows Forms DataGrid Control](how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md) +- [DataGrid Control](datagrid-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-freeze-columns-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-freeze-columns-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..062374b242 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-freeze-columns-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,44 @@ +--- +title: Freeze Columns in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "columns [Windows Forms], freezing" + - "DataGridView control [Windows Forms], freezing columns" + - "DataGridView control [Windows Forms], columns always in view" +ms.assetid: 2ef8b1de-782e-4867-af8d-58171ab5c106 +--- +# How to: Freeze Columns in the Windows Forms DataGridView Control +When users view data displayed in a Windows Forms control, they sometimes need to refer to a single column or set of columns frequently. For example, when displaying a table of customer information that contains many columns, it is useful to display the customer name at all times while enabling other columns to scroll outside the visible region. + + To achieve this behavior, you can freeze columns in the control. When you freeze a column, all the columns to its left (or to its right in right-to-left language scripts) are frozen as well. Frozen columns remain in place while all other columns can scroll. + +> [!NOTE] +> If column reordering is enabled, the frozen columns are treated as a group distinct from the unfrozen columns. Users can reposition columns in either group, but they cannot move a column from one group to the other. + + The property of a column determines whether the column is always visible within the grid. + + There is support for this task in Visual Studio. Also see [How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer](freeze-columns-in-the-datagrid-using-the-designer.md). + +### To freeze a column programmatically + +- Set the property to `true`. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#061](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#061)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#061](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#061)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1` that contains a column named `AddToCartButton`. + +- References to the and assemblies. + +## See also + +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) +- [How to: Enable Column Reordering in the Windows Forms DataGridView Control](how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-give-your-control-a-transparent-background.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-give-your-control-a-transparent-background.md new file mode 100644 index 0000000000..2a89ffbbf4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-give-your-control-a-transparent-background.md @@ -0,0 +1,28 @@ +--- +title: "How to: Give Your Control a Transparent Background" +ms.date: "03/30/2017" +helpviewer_keywords: + - "transparent backgrounds [Windows Forms], custom controls" + - "custom controls [Windows Forms], transparent background" + - "transparency [Windows Forms], Windows Forms custom controls" +ms.assetid: 32433e63-f4e9-4305-9857-6de3edeb944a +--- +# How to: Give Your Control a Transparent Background +In earlier versions of the .NET Framework, controls didn't support setting transparent backcolors without first setting the method in the forms's constructor. In the current framework version, the backcolor for most controls can be set to in the **Properties** window at design time, or in code in the form's constructor. + +> [!NOTE] +> Windows Forms controls do not support true transparency. The background of a transparent Windows Forms control is painted by its parent. + +> [!NOTE] +> The control doesn't support a transparent backcolor even when the property is set to . + +### To give your control a transparent backcolor + +- In the Properties window, choose the property and set it to + +## See also + +- +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [Using Managed Graphics Classes](../advanced/using-managed-graphics-classes.md) +- [How to: Draw Opaque and Semitransparent Lines](../advanced/how-to-draw-opaque-and-semitransparent-lines.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-group-controls-with-the-windows-forms-groupbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-controls-with-the-windows-forms-groupbox-control.md new file mode 100644 index 0000000000..0c64bcf20b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-controls-with-the-windows-forms-groupbox-control.md @@ -0,0 +1,33 @@ +--- +title: Group Controls with GroupBox Control +description: Learn how to group controls with the Windows Forms GroupBox control so that you can create a visual grouping of related elements. +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], grouping" + - "GroupBox control [Windows Forms], grouping controls" + - "Windows Forms controls, grouping" +ms.assetid: 0bda316d-bd2a-43aa-ac73-342453303169 +--- +# How to: Group Controls with the Windows Forms GroupBox Control +Windows Forms controls are used to group other controls. There are three reasons to group controls: + +- To create a visual grouping of related form elements for a clear user interface. + +- To create programmatic grouping (of radio buttons, for example). + +- For moving the controls as a unit at design time. + +### To create a group of controls + +1. Draw a control on a form. + +2. Add other controls to the group box, drawing each inside the group box. + + If you have existing controls that you want to enclose in a group box, you can select all the controls, cut them to the Clipboard, select the control, and then paste them into the group box. You can also drag them into the group box. + +3. Set the property of the group box to an appropriate caption. + +## See also + +- +- [GroupBox Control](groupbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer.md new file mode 100644 index 0000000000..295dd6aac6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer.md @@ -0,0 +1,45 @@ +--- +title: Group Items in ListView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "ListView control [Windows Forms], grouping items" + - "grouping" + - "groups [Windows Forms], in Windows Forms controls" +ms.assetid: 8b615000-69d9-4c64-acaf-b54fa09b69e3 +--- +# How to: Group Items in a Windows Forms ListView Control Using the Designer + +The grouping feature of the control enables you to display related sets of items in groups. These groups are separated on the screen by horizontal group headers that contain the group titles. You can use groups to make navigating large lists easier by grouping items alphabetically, by date, or by any other logical grouping. The following image shows some grouped items: + +![Numbers separated into odd and even groups.](./media/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer/odd-even-list-view-groups.gif) + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +To enable grouping, you must first create one or more objects either in the designer or programmatically. Once a group has been defined, you can assign items to it. + +## To add or remove groups in the designer + +1. In the **Properties** window, click the **Ellipsis** (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button next to the property. + + The **ListViewGroup Collection Editor** appears. + +2. To add a group, click the **Add** button. You can then set properties of the new group, such as the and properties. To remove a group, select it and click the **Remove** button. + +## To assign items to groups in the designer + +1. In the **Properties** window, click the **Ellipsis** (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button next to the property. + + The **ListViewItem Collection Editor** appears. + +2. To add a new item, click the **Add** button. You can then set properties of the new item, such as the and properties. + +3. Select the property and choose a group from the drop-down list. + +## See also + +- +- +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-group-items-in-a-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-items-in-a-windows-forms-listview-control.md new file mode 100644 index 0000000000..141743e545 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-items-in-a-windows-forms-listview-control.md @@ -0,0 +1,56 @@ +--- +title: Group Items in ListView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ListView control [Windows Forms], grouping items" + - "lists [Windows Forms], grouping items" + - "grouping" + - "list views [Windows Forms], grouping items" + - "groups" + - "groups [Windows Forms], in Windows Forms controls" +ms.assetid: 610416a1-8da4-436c-af19-5f19e654769b +--- +# How to: Group Items in a Windows Forms ListView Control +With the grouping feature of the control, you can display related sets of items in groups. These groups are separated on the screen by horizontal group headers that contain the group titles. You can use groups to make navigating large lists easier by grouping items alphabetically, by date, or by any other logical grouping. The following image shows some grouped items. + + ![Screenshot of odd and even ListView groups.](./media/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer/odd-even-list-view-groups.gif) + + To enable grouping, you must first create one or more groups either in the designer or programmatically. After a group has been defined, you can assign items to groups. You can also move items from one group to another programmatically. + +### To add groups + +1. Use the method of the collection. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#21](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#21)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#21](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#21)] + +### To remove groups + +1. Use the or method of the collection. + + The method removes a single group; the method removes all groups from the list. + + > [!NOTE] + > Removing a group does not remove the items within that group. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#22)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#22)] + +### To assign items to groups or move items between groups + +1. Set the property of individual items. + + [!code-csharp[System.Windows.Forms.ListViewLegacyTopics#23](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs#23)] + [!code-vb[System.Windows.Forms.ListViewLegacyTopics#23](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb#23)] + +## See also + +- +- +- +- [ListView Control](listview-control-windows-forms.md) +- [ListView Control Overview](listview-control-overview-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md new file mode 100644 index 0000000000..9d2c42e8f4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md @@ -0,0 +1,30 @@ +--- +title: Group RadioButton Controls to Function as a Set +description: Learn how to how to group Windows Forms RadioButton controls to function independently of other sets. +ms.date: "03/30/2017" +helpviewer_keywords: + - "radio buttons [Windows Forms], grouping" + - "controls [Windows Forms], grouping" + - "Windows Forms controls, grouping" + - "RadioButton control [Windows Forms], grouping" +ms.assetid: 58f8fe34-50b7-49d8-a2be-c271be3c6b32 +--- +# How to: Group Windows Forms RadioButton Controls to Function as a Set +Windows Forms controls are designed to give users a choice among two or more settings, of which only one can be assigned to a procedure or object. For example, a group of controls may display a choice of package carriers for an order, but only one of the carriers will be used. Therefore only one at a time can be selected, even if it is a part of a functional group. + + You group radio buttons by drawing them inside a container such as a control, a control, or a form. All radio buttons that are added directly to a form become one group. To add separate groups, you must place them inside panels or group boxes. For more information about panels or group boxes, see [Panel Control Overview](panel-control-overview-windows-forms.md) or [GroupBox Control Overview](groupbox-control-overview-windows-forms.md). + +### To group RadioButton controls as a set to function independently of other sets + +1. Drag a or control from the **Windows Forms** tab on the **Toolbox** onto the form. + +2. Draw controls on the or control. + +## See also + +- +- [RadioButton Control Overview](radiobutton-control-overview-windows-forms.md) +- [Panel Control Overview](panel-control-overview-windows-forms.md) +- [GroupBox Control Overview](groupbox-control-overview-windows-forms.md) +- [CheckBox Control Overview](checkbox-control-overview-windows-forms.md) +- [RadioButton Control](radiobutton-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-handle-errors-and-exceptions-that-occur-with-databinding.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-handle-errors-and-exceptions-that-occur-with-databinding.md new file mode 100644 index 0000000000..9b07c37f7d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-handle-errors-and-exceptions-that-occur-with-databinding.md @@ -0,0 +1,38 @@ +--- +title: "How to: Handle Errors and Exceptions that Occur with Databinding" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "error handling [Windows Forms], examples" + - "data binding [Windows Forms], examples" + - "examples [Windows Forms], error handling" + - "error handling [Windows Forms], data binding" + - "data binding [Windows Forms], error handling" + - "BindingSource component [Windows Forms], handling errors and exceptions" +ms.assetid: eddc5bad-9513-47df-ab28-f02d8dff7892 +--- +# How to: Handle Errors and Exceptions that Occur with Databinding +Oftentimes exceptions and errors occur on the underlying business objects when you bind them to controls. You can intercept these errors and exceptions and then either recover or pass the error information to the user by handling the event for a particular , , or component. + +## Example + This code example demonstrates how to handle errors and exceptions that occur during a data-binding operation. It demonstrates how to intercept errors by handling the event of the objects. In order to intercept errors and exceptions by handling this event, you must enable formatting for the binding. You can enable formatting when the binding is constructed or added to the binding collection, or by setting the property to `true`. + + [!code-cpp[System.Windows.Forms.DataConnectorBindingComplete#3](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CPP/form1.cpp#3)] + [!code-csharp[System.Windows.Forms.DataConnectorBindingComplete#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CS/form1.cs#3)] + [!code-vb[System.Windows.Forms.DataConnectorBindingComplete#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/VB/form1.vb#3)] + + When the code is running and an empty string is entered for the part name or a value less than 100 is entered for the part number, a message box appears. This is a result of handling the event for these textbox bindings. + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- [BindingSource Component](bindingsource-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-handle-the-contextmenustrip-opening-event.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-handle-the-contextmenustrip-opening-event.md new file mode 100644 index 0000000000..29557754d2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-handle-the-contextmenustrip-opening-event.md @@ -0,0 +1,31 @@ +--- +title: "How to: Handle the ContextMenuStrip Opening Event" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ContextMenuStrip control [Windows Forms]" + - "context menus [Windows Forms], event handling" + - "ToolStrip control [Windows Forms]" + - "event handling [Windows Forms], context menus" + - "shortcut menus [Windows Forms], event handling" +ms.assetid: b661b3dd-7815-4cc2-a1aa-a9a391ab3427 +--- +# How to: Handle the ContextMenuStrip Opening Event +You can customize the behavior of your control by handling the event. + +## Example + The following code example demonstrates how to handle the event. The event handler adds items dynamically to a control. For the complete code example, see [How to: Add ToolStrip Items Dynamically](how-to-add-toolstrip-items-dynamically.md). + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#42](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#42)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#42](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#42)] + + Set the property to `true` to prevent the menu from opening. + +## See also + +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-column-headers-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-column-headers-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..5ed5813aa8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-column-headers-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,34 @@ +--- +title: Hide Column Headers in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "columns [Windows Forms], hiding column headers" + - "column headers [Windows Forms], hiding" + - "DataGridView control [Windows Forms], column headers" +ms.assetid: e4ad5f68-50d2-4b9e-93ee-9d622423a8ab +--- +# How to: Hide Column Headers in the Windows Forms DataGridView Control +Sometimes you will want to display a without column headers. In the control, the property value determines whether the column headers are displayed. + +### To hide the column headers + +- Set the property to `false`. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#062](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#062)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#062](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#062)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-columns-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-columns-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..f3fd751f16 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-columns-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,41 @@ +--- +title: Hide Columns in DataGridView Control +description: Learn how to hide columns programmatically in the Windows Forms DataGridView control by setting the DataGridViewColumn.Visible property to false. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], hiding columns" + - "data grids [Windows Forms], hiding columns" + - "columns [Windows Forms], hiding" +ms.assetid: 3f94143a-2ef0-49a5-a22a-b2e6f9289642 +--- +# How to: Hide Columns in the Windows Forms DataGridView Control +Sometimes you will want to display only some of the columns that are available in a Windows Forms control. For example, you might want to show an employee salary column to users with management credentials while hiding it from other users. Alternately, you might want to bind the control to a data source that contains many columns, only some of which you want to display. In this case, you will typically remove the columns you are not interested in displaying rather than hide them. + + In the control, the property value of a column determines whether that column is displayed. + + There is support for this task in Visual Studio. Also see [How to: Hide Columns in the Windows Forms DataGridView Control Using the Designer](hide-columns-in-the-datagrid-using-the-designer.md). + +### To hide a column programmatically + +- Set the property to `false`. To hide a `CustomerID` column that is automatically generated during data binding, place the following code example in a event handler. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#063](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#063)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#063](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#063)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1` that contains a column named `CustomerID`. + +- References to the and assemblies. + +## See also + +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) +- [How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control](remove-autogenerated-columns-from-a-wf-datagridview-control.md) +- [How to: Change the Order of Columns in the Windows Forms DataGridView Control](how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-toolstripmenuitems-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-toolstripmenuitems-using-the-designer.md new file mode 100644 index 0000000000..3d5e84d3d0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-toolstripmenuitems-using-the-designer.md @@ -0,0 +1,36 @@ +--- +title: "How to: Hide ToolStripMenuItems Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStripMenuItems [Windows Forms], hiding menu items in designer" + - "MenuStrip control [Windows Forms], hiding menu items in designer" + - "menu items [Windows Forms], hiding" +ms.assetid: 8f1b057e-3d8a-4f11-88df-935f7b29a836 +--- +# How to: Hide ToolStripMenuItems Using the Designer +Hiding menu items is a way to control the user interface (UI) of your application and restrict user commands. Often, you will want to hide an entire menu when all of the menu items on it are unavailable. This presents fewer distractions for the user. Furthermore, you might want to both hide and disable the menu or menu item, as hiding alone does not prevent the user from accessing a menu command by using a shortcut key. For more information on disabling menu items, see [How to: Disable ToolStripMenuItems Using the Designer](how-to-disable-toolstripmenuitems-using-the-designer.md). + +## To hide a top-level menu and its submenu items + +1. Select the top-level menu item and set its or property to `false`. + + When you hide the top-level menu item, all menu items within that menu are also hidden. If you click somewhere other than on the after setting to `false`, the entire top-level menu item and its submenu items disappear from your form, thus showing you the run-time effect of your action. To display the hidden top-level menu item at design time, click on the in the **Component Tray**, in **Document Outline**, or at the top of the property grid. + +> [!NOTE] +> You will rarely hide an entire menu except for multiple document interface (MDI) child menus in a merging scenario. + +## To hide a submenu item + +1. Select the submenu item and set its property to `false`. + + When you hide a submenu item, it remains visible on your form at design time so that you can easily select it for further work. It will actually be hidden at run time. + +## See also + +- +- +- +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) +- [How to: Disable ToolStripMenuItems Using the Designer](how-to-disable-toolstripmenuitems-using-the-designer.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-toolstripmenuitems.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-toolstripmenuitems.md new file mode 100644 index 0000000000..7a5b7778da --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-hide-toolstripmenuitems.md @@ -0,0 +1,40 @@ +--- +title: "How to: Hide ToolStripMenuItems" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ToolStripMenuItems [Windows Forms], hiding" + - "MenuStrip control [Windows Forms], hiding menu items" + - "menus [Windows Forms], hiding menu items" + - "menu items [Windows Forms], hiding" + - "hiding menu items" +ms.assetid: 418a768f-808a-44cd-8cef-f4e161883621 +--- +# How to: Hide ToolStripMenuItems +Hiding menu items is a way to control the user interface of your application and restrict user commands. Often, you will want to hide an entire menu when all of the menu items on it are unavailable. This presents fewer distractions for the user. Furthermore, you might want to both hide and disable the menu or menu item, as hiding alone does not prevent the user from accessing a menu command by using a shortcut key. + +### To hide any menu item programmatically + +- Within the method where you set the properties of the menu item, add code to set the property to `false`. + + ```vb + MenuItem3.Visible = False + ``` + + ```csharp + menuItem3.Visible = false; + ``` + + ```cpp + menuItem3->Visible = false; + ``` + +## See also + +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) +- [How to: Disable ToolStripMenuItems](how-to-disable-toolstripmenuitems.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells.md new file mode 100644 index 0000000000..c6408fb198 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells.md @@ -0,0 +1,41 @@ +--- +title: Host Controls in DataGridView Cells +description: Learn how to host controls in Windows Forms DataGridView cells to enable your users to enter and edit values in a variety of ways. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], hosting in cells" + - "DataGridView control [Windows Forms], hosting controls in cells" + - "cells [Windows Forms], hosting controls" +ms.assetid: e79a9d4e-64ec-41f5-93ec-f5492633cbb2 +--- +# How to: Host Controls in Windows Forms DataGridView Cells +The control provides several column types, enabling your users to enter and edit values in a variety of ways. If these column types do not meet your data-entry needs, however, you can create your own column types with cells that host controls of your choosing. To do this, you must define classes that derive from and . You must also define a class that derives from and implements the interface. + + The following code example shows how to create a calendar column. The cells of this column display dates in ordinary text box cells, but when the user edits a cell, a control appears. In order to avoid having to implement text box display functionality again, the `CalendarCell` class derives from the class rather than inheriting the class directly. + +> [!NOTE] +> When you derive from or and add new properties to the derived class, be sure to override the `Clone` method to copy the new properties during cloning operations. You should also call the base class's `Clone` method so that the properties of the base class are copied to the new cell or column. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewCalendarColumn#000](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/CS/datagridviewcalendarcolumn.cs#000)] + [!code-vb[System.Windows.Forms.DataGridViewCalendarColumn#000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/VB/datagridviewcalendarcolumn.vb#000)] + +## Compiling the Code + The following example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- [Customizing the Windows Forms DataGridView Control](customizing-the-windows-forms-datagridview-control.md) +- [DataGridView Control Architecture](datagridview-control-architecture-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-custom-layout-engine.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-custom-layout-engine.md new file mode 100644 index 0000000000..bde63b96e8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-custom-layout-engine.md @@ -0,0 +1,26 @@ +--- +title: "How to: Implement a Custom Layout Engine" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "layout engines [Windows Forms], custom" + - "TableLayoutPanel control [Windows Forms], layout engine" + - "layout engines [Windows Forms], implementing" + - "FlowLayoutPanel control [Windows Forms], layout engine" +ms.assetid: f91aa91c-29f4-4089-95ca-5d48b774b00e +--- +# How to: Implement a Custom Layout Engine +The following code example demonstrates how to create a custom layout engine that performs a simple flow layout. It implements a panel control named `DemoFlowPanel`, which overrides the property to provide an instance of the `DemoFlowLayout` class. + +## Example + [!code-cpp[System.Windows.Forms.Layout.LayoutEngine#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/DemoFlowLayout.cpp#1)] + [!code-csharp[System.Windows.Forms.Layout.LayoutEngine#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/CS/DemoFlowLayout.cs#1)] + [!code-vb[System.Windows.Forms.Layout.LayoutEngine#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/VB/DemoFlowLayout.vb#1)] + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-custom-toolstriprenderer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-custom-toolstriprenderer.md new file mode 100644 index 0000000000..7f1ef3fc35 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-custom-toolstriprenderer.md @@ -0,0 +1,42 @@ +--- +title: "How to: Implement a Custom ToolStripRenderer" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStrip control [Windows Forms]" +ms.assetid: c66fd3f7-2377-4553-8f1b-006527f08f32 +--- +# How to: Implement a Custom ToolStripRenderer +You can customize the appearance of a control by implementing a class that derives from . This gives you the flexibility to create an appearance that differs from the appearance provided the and classes. + +## Example + The following code example demonstrates how to implement a custom class. In this example, the `GridStrip` control implements a sliding-tile puzzle, which allows the user to move tiles in a table layout to form an image. A custom control arranges its controls in a grid layout. The layout contains one empty cell, into which the user can slide an adjacent tile by using a drag-and-drop operation. Tiles that the user can move are highlighted. + + The `GridStripRenderer` class customizes three aspects of the `GridStrip` control's appearance: + +- `GridStrip` border + +- border + +- image + + [!code-csharp[System.Windows.Forms.ToolStrip.GridStrip#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/CS/GridStrip.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.GridStrip#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/VB/GridStrip.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-form-that-uses-a-background-operation.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-form-that-uses-a-background-operation.md new file mode 100644 index 0000000000..5e4ca264fb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-a-form-that-uses-a-background-operation.md @@ -0,0 +1,48 @@ +--- +title: "How to: Implement a Form That Uses a Background Operation" +description: Learn how to implement a Windows Form that uses a background operation so that one operation can continue to run while another operation proceeds. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "threading [Windows Forms], forms" + - "BackgroundWorker component" + - "background tasks" + - "forms [Windows Forms], multithreading" + - "components [Windows Forms], asynchronous" + - "forms [Windows Forms], background operations" + - "background threads" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: 9f483f93-1613-4be1-a021-b4934e9c78f3 +--- +# How to: Implement a Form That Uses a Background Operation +The following example program creates a form that calculates Fibonacci numbers. The calculation runs on a thread that is separate from the user interface thread, so the user interface continues to run without delays as the calculation proceeds. + + There is extensive support for this task in Visual Studio. + + Also see [Walkthrough: Implementing a Form That Uses a Background Operation](walkthrough-implementing-a-form-that-uses-a-background-operation.md). + +## Example + [!code-cpp[System.ComponentModel.BackgroundWorker#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#1)] + [!code-csharp[System.ComponentModel.BackgroundWorker#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#1)] + [!code-vb[System.ComponentModel.BackgroundWorker#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## Robust Programming + +> [!CAUTION] +> When using multithreading of any sort, you potentially expose yourself to very serious and complex bugs. Consult the [Managed Threading Best Practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) before implementing any solution that uses multithreading. + +## See also + +- +- +- [Event-based Asynchronous Pattern Overview](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview) +- [Managed Threading Best Practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..03aa7a7191 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,43 @@ +--- +title: Implement Virtual Mode in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data [Windows Forms], managing large data sets" + - "DataGridView control [Windows Forms], virtual mode" + - "virtual mode" + - "DataGridView control [Windows Forms], large data sets" +ms.assetid: 98236267-f08e-4918-bcf9-77acf050a3ca +--- +# How to: Implement Virtual Mode in the Windows Forms DataGridView Control +The following code example demonstrates how to manage large sets of data using a control with its property set to `true`. + + For a complete explanation of this code example, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +## Example + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#000](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#000)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#000](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#000)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#000)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- +- +- [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md) +- [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) +- [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-existing-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-existing-windows-forms-controls.md new file mode 100644 index 0000000000..36d41024bd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-existing-windows-forms-controls.md @@ -0,0 +1,89 @@ +--- +title: Inherit from Existing Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "inheritance [Windows Forms], Windows Forms custom controls" + - "custom controls [Windows Forms], inheritance" +ms.assetid: 1e1fc8ea-c615-4cf0-a356-16d6df7444ab +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Inherit from Existing Windows Forms Controls + +If you want to extend the functionality of an existing control, you can create a control derived from an existing control through inheritance. When inheriting from an existing control, you inherit all of the functionality and visual properties of that control. For example, if you were creating a control that inherited from , your new control would look and act exactly like a standard control. You could then extend or modify the functionality of your new control through the implementation of custom methods and properties. In some controls, you can also change the visual appearance of your inherited control by overriding its method. + +## To create an inherited control + +1. In Visual Studio, create a new **Windows Forms Application** project. + +1. From the **Project** menu, choose **Add New Item**. + + The **Add New Item** dialog box appears. + +1. In the **Add New Item** dialog box, double-click **Custom Control**. + + A new custom control is added to your project. + +1. If you're using: + + - Visual Basic, at the top of **Solution Explorer**, click **Show All Files**. Expand CustomControl1.vb and then open CustomControl1.Designer.vb in the Code Editor. + - C#, open CustomControl1.cs in the Code Editor. + +1. Locate the class declaration, which inherits from . + +1. Change the base class to the control that you want to inherit from. + + For example, if you want to inherit from , change the class declaration to the following: + + ```vb + Partial Class CustomControl1 + Inherits System.Windows.Forms.Button + ``` + + ```csharp + public partial class CustomControl1 : System.Windows.Forms.Button + ``` + +1. If you are using Visual Basic, save and close CustomControl1.Designer.vb. Open CustomControl1.vb in the Code Editor. + +1. Implement any custom methods or properties that your control will incorporate. + +1. If you want to modify the graphical appearance of your control, override the method. + + > [!NOTE] + > Overriding will not allow you to modify the appearance of all controls. Those controls that have all of their painting done by Windows (for example, ) never call their method, and thus will never use the custom code. Refer to the Help documentation for the particular control you want to modify to see if the method is available. For a list of all the Windows Form Controls, see [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md). If a control does not have listed as a member method, you cannot alter its appearance by overriding this method. For more information about custom painting, see [Custom Control Painting and Rendering](custom-control-painting-and-rendering.md). + + ```vb + Protected Overrides Sub OnPaint(ByVal e As _ + System.Windows.Forms.PaintEventArgs) + MyBase.OnPaint(e) + ' Insert code to do custom painting. + ' If you want to completely change the appearance of your control, + ' do not call MyBase.OnPaint(e). + End Sub + ``` + + ```csharp + protected override void OnPaint(PaintEventArgs pe) + { + base.OnPaint(pe); + // Insert code to do custom painting. + // If you want to completely change the appearance of your control, + // do not call base.OnPaint(pe). + } + ``` + +1. Save and test your control. + +## See also + +- [Varieties of Custom Controls](varieties-of-custom-controls.md) +- [How to: Inherit from the Control Class](how-to-inherit-from-the-control-class.md) +- [How to: Inherit from the UserControl Class](how-to-inherit-from-the-usercontrol-class.md) +- [How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md) +- [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers) +- [Walkthrough: Inheriting from a Windows Forms Control](walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-the-control-class.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-the-control-class.md new file mode 100644 index 0000000000..2cfcde796f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-the-control-class.md @@ -0,0 +1,48 @@ +--- +title: "How to: Inherit from the Control Class" +ms.date: "03/30/2017" +helpviewer_keywords: + - "inheritance [Windows Forms], Windows Forms custom controls" + - "Control class [Windows Forms], inheriting from" + - "custom controls [Windows Forms], inheritance" + - "OnPaint method [Windows Forms]" + - "custom controls [Windows Forms], creating" +ms.assetid: 46ba0df3-5cf7-443c-a3b4-a72660172476 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Inherit from the Control Class + +If you want to create a completely custom control to use on a Windows Form, you should inherit from the class. While inheriting from the class requires that you perform more planning and implementation, it also provides you with the largest range of options. When inheriting from , you inherit the very basic functionality that makes controls work. The functionality inherent in the class handles user input through the keyboard and mouse, defines the bounds and size of the control, provides a windows handle, and provides message handling and security. It does not incorporate any painting, which in this case is the actual rendering of the graphical interface of the control, nor does it incorporate any specific user interaction functionality. You must provide all of these aspects through custom code. + +## To create a custom control + +1. In Visual Studio, create a new **Windows Application** or **Windows Control Library** project. + +2. From the **Project** menu, choose **Add Class**. + +3. In the **Add New Item** dialog box, click **Custom Control**. + + A new custom control is added to your project. + +4. Press **F7** to open the **Code Editor** for your custom control. + +5. Locate the method, which will be empty except for a call to the method of the base class. + +6. Modify the code to incorporate any custom painting you want for your control. + + For information about writing code to render graphics for controls, see [Custom Control Painting and Rendering](custom-control-painting-and-rendering.md). + +7. Implement any custom methods, properties, or events that your control will incorporate. + +8. Save and test your control. + +## See also + +- [Varieties of Custom Controls](varieties-of-custom-controls.md) +- [How to: Inherit from the UserControl Class](how-to-inherit-from-the-usercontrol-class.md) +- [How to: Inherit from Existing Windows Forms Controls](how-to-inherit-from-existing-windows-forms-controls.md) +- [How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md) +- [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers) +- [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-the-usercontrol-class.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-the-usercontrol-class.md new file mode 100644 index 0000000000..ed77e3154d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-inherit-from-the-usercontrol-class.md @@ -0,0 +1,39 @@ +--- +title: "How to: Inherit from the UserControl Class" +ms.date: "03/30/2017" +helpviewer_keywords: + - "inheritance [Windows Forms], Windows Forms custom controls" + - "UserControl class [Windows Forms], inheriting from" + - "user controls [Windows Forms], creating" + - "composite controls [Windows Forms], creating" +ms.assetid: 67713625-e2e4-4f6a-bce7-0855ee5043d9 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Inherit from the UserControl Class + +To combine the functionality of one or more Windows Forms controls with custom code, you can create a *user control*. User controls combine rapid control development, standard Windows Forms control functionality, and the versatility of custom properties and methods. When you begin creating a user control, you are presented with a visible designer, upon which you can place standard Windows Forms controls. These controls retain all of their inherent functionality, as well as the appearance and behavior (look and feel) of standard controls. Once these controls are built into the user control, however, they are no longer available to you through code. The user control does its own painting and also handles all of the basic functionality associated with controls. + +## To create a user control + +1. Create a new **Windows Control Library** project in Visual Studio. + + A new project is created with a blank user control. + +2. Drag controls from the **Windows Forms** tab of the **Toolbox** onto your designer. + +3. These controls should be positioned and designed as you want them to appear in the final user control. If you want to allow developers to access the constituent controls, you must declare them as public, or selectively expose properties of the constituent control. For details, see [How to: Expose Properties of Constituent Controls](how-to-expose-properties-of-constituent-controls.md). + +4. Implement any custom methods or properties that your control will incorporate. + +5. Press **F5** to build the project and run your control in the **UserControl Test Container**. For more information, see [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md). + +## See also + +- [Varieties of Custom Controls](varieties-of-custom-controls.md) +- [How to: Inherit from the Control Class](how-to-inherit-from-the-control-class.md) +- [How to: Inherit from Existing Windows Forms Controls](how-to-inherit-from-existing-windows-forms-controls.md) +- [How to: Author Controls for Windows Forms](how-to-author-controls-for-windows-forms.md) +- [Troubleshoot Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers) +- [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-insert-a-menustrip-into-an-mdi-drop-down-menu-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-insert-a-menustrip-into-an-mdi-drop-down-menu-windows-forms.md new file mode 100644 index 0000000000..9ce67c0902 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-insert-a-menustrip-into-an-mdi-drop-down-menu-windows-forms.md @@ -0,0 +1,96 @@ +--- +title: "How to: Insert a MenuStrip into an MDI Drop-Down Menu" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "MenuStrip control [Windows Forms], inserting" + - "MenuStrip control [Windows Forms], merging" + - "MDI [Windows Forms], merging menu items" +ms.assetid: 0fad444e-26d9-49af-8860-044d9c10d608 +--- +# How to: Insert a MenuStrip into an MDI Drop-Down Menu (Windows Forms) +In some applications, the kind of a multiple-document interface (MDI) child window can be different from the MDI parent window. For example, the MDI parent might be a spreadsheet, and the MDI child might be a chart. In that case, you want to update the contents of the MDI parent's menu with the contents of the MDI child's menu as MDI child windows of different kinds are activated. + + The following procedure uses the , , , and properties to insert a group of menu items from the MDI child menu into the drop-down part of the MDI parent menu. Closing the MDI child window removes the inserted menu items from the MDI parent. + +### To insert a MenuStrip into an MDI drop-down menu + +1. Create a form and set its property to `true`. + +2. Add a to `Form1` and set the property of the to `true`. + +3. Add a top-level menu item to the `Form1` and set its property to `&File`. + +4. Add three submenu items to the `&File` menu item and set their properties to `&Open`, `&Import from`, and `E&xit`. + +5. Add two submenu items to the `&Import from` submenu item and set their properties to `&Word` and `&Excel`. + +6. Add a form to the project, add a to the form, and set the property of the `Form2` to `true`. + +7. Add a top-level menu item to the `Form2` and set its property to `&File`. + +8. Add submenu items to the `&File` menu of `Form2` in the following order: a , `&Save`, `Save and &Close`, and another . + +9. Set the and properties of the `Form2` menu items as shown in the following table. + + |Form2 menu item|MergeAction value|MergeIndex value| + |---------------------|-----------------------|----------------------| + |File|MatchOnly|-1| + |Separator|Insert|2| + |Save|Insert|3| + |Save and Close|Insert|4| + |Separator|Insert|5| + +10. Create an event handler for the event of the `&Open`. + +11. Within the event handler, insert code similar to the following code example to create and display new instances of `Form2` as MDI children of `Form1`. + + ```vb + Private Sub openToolStripMenuItem_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles openToolStripMenuItem.Click + Dim NewMDIChild As New Form2() + 'Set the parent form of the child window. + NewMDIChild.MdiParent = Me + 'Display the new form. + NewMDIChild.Show() + End Sub + ``` + + ```csharp + private void openToolStripMenuItem_Click(object sender, EventArgs e) + { + Form2 newMDIChild = new Form2(); + // Set the parent form of the child window. + newMDIChild.MdiParent = this; + // Display the new form. + newMDIChild.Show(); + } + ``` + +12. Place code similar to the following code example in the `&Open` to register the event handler. + + ```vb + Private Sub openToolStripMenuItem_Click(sender As Object, e As _ + EventArgs) Handles openToolStripMenuItem.Click + ``` + + ```csharp + this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); + ``` + +## Compiling the Code + This example requires: + +- Two controls named `Form1` and `Form2`. + +- A control on `Form1` named `menuStrip1`, and a control on `Form2` named `menuStrip2`. + +- References to the and assemblies. + +## See also + +- [How to: Create MDI Parent Forms](../advanced/how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](../advanced/how-to-create-mdi-child-forms.md) +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md new file mode 100644 index 0000000000..a9dafbae3e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md @@ -0,0 +1,123 @@ +--- +title: Iterate Through All Nodes of TreeView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], TreeView control" + - "TreeView control [Windows Forms], iterating through nodes" + - "tree nodes in TreeView control [Windows Forms], iterating through" +ms.assetid: 427f8928-ebcf-4beb-887f-695b905d5134 +--- +# How to: Iterate Through All Nodes of a Windows Forms TreeView Control +It is sometimes useful to examine every node in a Windows Forms control in order to perform some calculation on the node values. This operation can be done using a recursive procedure (recursive method in C# and C++) that iterates through each node in each collection of the tree. + + Each object in a tree view has properties that you can use to navigate the tree view: , , , , and . The value of the property is the parent node of the current node. The child nodes of the current node, if there are any, are listed in its property. The control itself has the property, which is the root node of the entire tree view. + +### To iterate through all nodes of the TreeView control + +1. Create a recursive procedure (recursive method in C# and C++) that tests each node. + +2. Call the procedure. + + The following example shows how to print each object's property: + + ```vb + Private Sub PrintRecursive(ByVal n As TreeNode) + System.Diagnostics.Debug.WriteLine(n.Text) + MessageBox.Show(n.Text) + Dim aNode As TreeNode + For Each aNode In n.Nodes + PrintRecursive(aNode) + Next + End Sub + + ' Call the procedure using the top nodes of the treeview. + Private Sub CallRecursive(ByVal aTreeView As TreeView) + Dim n As TreeNode + For Each n In aTreeView.Nodes + PrintRecursive(n) + Next + End Sub + ``` + + ```csharp + private void PrintRecursive(TreeNode treeNode) + { + // Print the node. + System.Diagnostics.Debug.WriteLine(treeNode.Text); + MessageBox.Show(treeNode.Text); + // Print each node recursively. + foreach (TreeNode tn in treeNode.Nodes) + { + PrintRecursive(tn); + } + } + + // Call the procedure using the TreeView. + private void CallRecursive(TreeView treeView) + { + // Print each node recursively. + TreeNodeCollection nodes = treeView.Nodes; + foreach (TreeNode n in nodes) + { + PrintRecursive(n); + } + } + ``` + + ```cpp + private: + void PrintRecursive( TreeNode^ treeNode ) + { + // Print the node. + System::Diagnostics::Debug::WriteLine( treeNode->Text ); + MessageBox::Show( treeNode->Text ); + + // Print each node recursively. + System::Collections::IEnumerator^ myNodes = (safe_cast(treeNode->Nodes))->GetEnumerator(); + try + { + while ( myNodes->MoveNext() ) + { + TreeNode^ tn = safe_cast(myNodes->Current); + PrintRecursive( tn ); + } + } + finally + { + IDisposable^ disposable = dynamic_cast(myNodes); + if ( disposable != nullptr ) + disposable->Dispose(); + } + } + + // Call the procedure using the TreeView. + void CallRecursive( TreeView^ treeView ) + { + // Print each node recursively. + TreeNodeCollection^ nodes = treeView->Nodes; + System::Collections::IEnumerator^ myNodes = (safe_cast(nodes))->GetEnumerator(); + try + { + while ( myNodes->MoveNext() ) + { + TreeNode^ n = safe_cast(myNodes->Current); + PrintRecursive( n ); + } + } + finally + { + IDisposable^ disposable = dynamic_cast(myNodes); + if ( disposable != nullptr ) + disposable->Dispose(); + } + } + ``` + +## See also + +- [TreeView Control](treeview-control-windows-forms.md) +- [Recursive Procedures](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/procedures/recursive-procedures) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-join-toolstrippanels.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-join-toolstrippanels.md new file mode 100644 index 0000000000..3a2ea11434 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-join-toolstrippanels.md @@ -0,0 +1,30 @@ +--- +title: "How to: Join ToolStripPanels" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms], joining together" + - "ToolStripPanel control [Windows Forms], joining together" +ms.assetid: 4eadda6d-e3b8-4151-aaf2-a8d564fbe6b3 +--- +# How to: Join ToolStripPanels +You can join controls to a at run time, which provides the flexibility of multiple-document interface (MDI) applications. + +## Example + The following code example demonstrates how to join controls to a . + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#11)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#11)] + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- [How to: Use ToolStripPanels for MDI](how-to-use-toolstrippanels-for-mdi.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-layer-objects-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-layer-objects-on-windows-forms.md new file mode 100644 index 0000000000..52f95b34a4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-layer-objects-on-windows-forms.md @@ -0,0 +1,56 @@ +--- +title: Layer Objects +description: Learn how to layer objects on Windows Forms controls and child forms to create more complex user interfaces. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms controls, layering" + - "controls [Windows Forms], layering" + - "z order" + - "controls [Windows Forms], positioning" + - "z-order" +ms.assetid: 1acc4281-2976-4715-86f4-bda68134baaf +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Layer objects on Windows Forms + +When you create a complex user interface, or work with a multiple document interface (MDI) form, you will often want to layer both controls and child forms to create more complex user interfaces (UI). To move and keep track of controls and windows within the context of a group, you manipulate their *z-order*. Z-order is the visual layering of controls on a form along the form's z-axis (depth). The window at the top of the z-order overlaps all other windows. All other windows overlap the window at the bottom of the z-order. + +## To layer controls at design time + +1. In Visual Studio, select a control that you want to layer. + +2. On the **Format** menu, select **Order**, and then select **Bring To Front** or **Send To Back**. + +## To layer controls programmatically + +Use the and methods to manipulate the z-order of the controls. + +For example, if a control, `txtFirstName`, is underneath another control and you want to have it on top, use the following code: + +```vb +txtFirstName.BringToFront() +``` + +```csharp +txtFirstName.BringToFront(); +``` + +```cpp +txtFirstName->BringToFront(); +``` + +> [!NOTE] +> Windows Forms supports *control containment*. Control containment involves placing a number of controls within a containing control, such as a number of controls within a control. You can then layer the controls within the containing control. Moving the group box moves the controls as well, because they are contained inside it. + +## See also + +- [Windows Forms Controls](index.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-load-a-picture-using-the-designer-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-load-a-picture-using-the-designer-windows-forms.md new file mode 100644 index 0000000000..7601e491f2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-load-a-picture-using-the-designer-windows-forms.md @@ -0,0 +1,45 @@ +--- +title: "How to: Load a Picture Using the Designer" +description: Learn how to use the Windows Forms PictureBox control to load and display a picture on a form at design time. +ms.date: "03/30/2017" +helpviewer_keywords: + - "picture formats" + - "images [Windows Forms], displaying on Windows Forms" + - "pictures [Windows Forms], displaying" + - "forms [Windows Forms], displaying images" + - "PictureBox control [Windows Forms], adding pictures" +ms.assetid: 4dc7b973-afb1-4276-8322-20825af96655 +--- +# How to: Load a Picture Using the Designer (Windows Forms) + +With the Windows Forms control, you can load and display a picture on a form at design time by setting the property to a valid picture. The following table shows the acceptable file types. + +|Type|File name extension| +|---|---| +|Bitmap|.bmp| +|Icon|.ico| +|GIF|.gif| +|Metafile|.wmf| +|JPEG|.jpg| + +## To display a picture at design time + +1. Draw a control on a form. + +2. In the **Properties** window, select the property, then select the ellipsis button to display the **Open** dialog box. + +3. If you're looking for a specific file type (for example, .gif files), select it in the **Files of type** box. + +4. Select the file you want to display. + +## To clear the picture at design time + +1. In the **Properties** window, select the property. Right-click the small thumbnail image that appears to the left of the name of the image object, and then choose **Reset**. + +## See also + +- +- [PictureBox Control Overview](picturebox-control-overview-windows-forms.md) +- [How to: Modify the Size or Placement of a Picture at Run Time](how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md) +- [How to: Set Pictures at Run Time](how-to-set-pictures-at-run-time-windows-forms.md) +- [PictureBox Control](picturebox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-load-a-sound-asynchronously-within-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-load-a-sound-asynchronously-within-a-windows-form.md new file mode 100644 index 0000000000..09d252ab9b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-load-a-sound-asynchronously-within-a-windows-form.md @@ -0,0 +1,52 @@ +--- +title: "How to: Load a Sound Asynchronously within a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "SoundPlayer class [Windows Forms], loading sounds asynchronously" + - "sounds [Windows Forms], loading on separate threads" + - "threading [Windows Forms], sounds" +ms.assetid: 3b6a9296-1d5e-4d52-a4ba-94366d6fe302 +--- +# How to: Load a Sound Asynchronously within a Windows Form +The following code example asynchronously loads a sound from an URL and then plays it on a new thread. + +## Example + [!code-csharp[System.Media.SoundPlayer.LoadAsync#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/CS/Form1.cs#1)] + [!code-vb[System.Media.SoundPlayer.LoadAsync#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +- That you replace the file name `"http://www.tailspintoys.com/sounds/stop.wav"` with a valid file name. + +## Robust Programming + File operations should be enclosed within appropriate exception-handling blocks. + + The following conditions may cause an exception: + +- The path name is malformed. For example, it contains characters that are not valid or is only white space ( class). + +- The path is read-only ( class). + +- The path name is `Nothing` ( class). + +- The path name is too long ( class). + +- The path is not valid ( class). + +- The path is only a colon ":" ( class). + +## .NET Framework Security + Do not make decisions about the contents of the file based on the name of the file. For example, the file `Form1.vb` may not be a Visual Basic source file. Verify all inputs before using the data in your application. + +## See also + +- +- +- +- [How to: Play a Sound from a Windows Form](how-to-play-a-sound-from-a-windows-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-load-files-into-the-windows-forms-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-load-files-into-the-windows-forms-richtextbox-control.md new file mode 100644 index 0000000000..f54c0ba241 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-load-files-into-the-windows-forms-richtextbox-control.md @@ -0,0 +1,83 @@ +--- +title: Load Files into RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "text boxes [Windows Forms], displaying files" + - "examples [Windows Forms], text boxes" + - ".rtf files [Windows Forms], opening in RichTextBox control" + - "RTF files [Windows Forms], opening in RichTextBox control" + - "text files [Windows Forms], displaying in RichTextBox control" + - ".rtf files [Windows Forms], displaying in RichTextBox control" + - "RichTextBox control [Windows Forms], opening files" + - "RTF files [Windows Forms], displaying in RichTextBox control" +ms.assetid: c03451be-f285-4428-a71a-c41e002cc919 +--- +# How to: Load Files into the Windows Forms RichTextBox Control + +The Windows Forms control can display a plain-text, Unicode plain-text, or Rich-Text-Format (RTF) file. To do so, call the method. You can also use the method to load data from a stream. For more information, see . + +### To load a file into the RichTextBox control + +1. Determine the path of the file to be opened using the component. For an overview, see [OpenFileDialog Component Overview](openfiledialog-component-overview-windows-forms.md). + +2. Call the method of the control, specifying the file to load and optionally a file type. In the example below, the file to load is taken from the component's property. If you call the method with a file name as its only argument, the file type will be assumed to be RTF. To specify another file type, call the method with a value of the enumeration as its second argument. + + In the example below, the component is shown when a button is clicked. The file selected is then opened and displayed in the control. This example assumes a form has a button,`btnOpenFile`. + + ```vb + Private Sub btnOpenFile_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles btnOpenFile.Click + If OpenFileDialog1.ShowDialog() = DialogResult.OK Then + RichTextBox1.LoadFile(OpenFileDialog1.FileName, _ + RichTextBoxStreamType.RichText) + End If + End Sub + ``` + + ```csharp + private void btnOpenFile_Click(object sender, System.EventArgs e) + { + if(openFileDialog1.ShowDialog() == DialogResult.OK) + { + richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText); + } + } + ``` + + ```cpp + private: + void btnOpenFile_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + if(openFileDialog1->ShowDialog() == DialogResult::OK) + { + richTextBox1->LoadFile(openFileDialog1->FileName, + RichTextBoxStreamType::RichText); + } + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.btnOpenFile.Click += new System.EventHandler(this. btnOpenFile_Click); + ``` + + ```cpp + this->btnOpenFile->Click += gcnew + System::EventHandler(this, &Form1::btnOpenFile_Click); + ``` + + > [!IMPORTANT] + > To run this process, your assembly may require a privilege level granted by the class. If you are running in a partial-trust context, the process might throw an exception because of insufficient privileges. For more information, see [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics). + +## See also + +- +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-lock-controls-to-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-lock-controls-to-windows-forms.md new file mode 100644 index 0000000000..06931fc202 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-lock-controls-to-windows-forms.md @@ -0,0 +1,49 @@ +--- +title: Lock Controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, locking" + - "controls [Windows Forms], locking" +ms.assetid: 94efe0d2-c14e-4d14-b903-63ea9b07e290 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Lock controls to Windows Forms + +When you design the user interface (UI) of your Windows application, you can lock the controls once they are positioned correctly, so that you do not inadvertently move or resize them when setting other properties. + +Additionally, you can lock and unlock all the controls on the form at once, which is helpful for forms with many controls, or you can unlock individual controls. Once you have placed all the controls where you want them on the form, lock them all in place to prevent erroneous movement. + +## To lock a control + +In the **Properties** window of Visual Studio, select the **Locked** property and then select **true**. (Double-clicking the name toggles the property setting.) + +Alternatively, right-click the control and choose **Lock Controls**. + +> [!NOTE] +> Locking controls prevents them from being dragged to a new size or location on the design surface. However, you can still change the size or location of controls by means of the **Properties** window or in code. + +## To lock all the controls on a form + +From the **Format** menu, choose **Lock Controls**. + +> [!NOTE] +> This command locks the form's size as well, because a form is a control. + +## To unlock all locked controls on a form + +From the **Format** menu, choose **Lock Controls**. + +All previously locked controls on the form are now unlocked. + +## To unlock locked controls individually + +In the **Properties** window, select the **Locked** property and then select **false**. (Double-clicking the name toggles the property setting.) + +## See also + +- [Windows Forms Controls](index.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-loop-a-sound-playing-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-loop-a-sound-playing-on-a-windows-form.md new file mode 100644 index 0000000000..fe77225a43 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-loop-a-sound-playing-on-a-windows-form.md @@ -0,0 +1,52 @@ +--- +title: "How to: Loop a Sound Playing on a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sound loops" + - "SoundPlayer class [Windows Forms], play looping" + - "sounds [Windows Forms], looping" + - "playing sounds [Windows Forms], looping" +ms.assetid: ea95dd46-10a3-46c0-8263-4b205f00df7f +--- +# How to: Loop a Sound Playing on a Windows Form +The following code example plays a sound repeatedly. When the code in the `stopPlayingButton_Click` event handler runs, any sound currently playing stops. If no sound is playing, nothing happens. + +## Example + [!code-csharp[System.Media.SoundPlayer.PlayLooping#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/CS/Form1.cs#1)] + [!code-vb[System.Media.SoundPlayer.PlayLooping#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +- That you replace the file name `"c:\Windows\Media\chimes.wav"` with a valid file name. + +## Robust Programming + File operations should be enclosed within appropriate exception-handling blocks. + + The following conditions may cause an exception: + +- The path name is malformed. For example, it contains characters that are not valid or it is only white space ( class). + +- The path is read-only ( class). + +- The path name is `Nothing` ( class). + +- The path name is too long ( class). + +- The path is invalid ( class). + +- The path is only a colon ":" ( class). + +## .NET Framework Security + Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file. Verify all inputs before using the data in your application. + +## See also + +- +- [How to: Play a Sound from a Windows Form](how-to-play-a-sound-from-a-windows-form.md) +- [SoundPlayer Class Overview](soundplayer-class-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..954528b0a8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,37 @@ +--- +title: Make Columns Read-Only in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], read-only columns" + - "DataGridView control [Windows Forms], read-only columns" +ms.assetid: 2bb73ebb-1a55-4362-9fda-e50574c087d5 +--- +# How to: Make Columns Read-Only in the Windows Forms DataGridView Control +Not all data is meant for editing. In the control, the column property value determines whether users can edit cells in that column. For information about how to make the control entirely read-only, see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md). + + There is support for this task in Visual Studio. Also see [How to: Make Columns Read-Only in the Windows Forms DataGridView Control Using the Designer](make-columns-read-only-in-the-datagrid-using-the-designer.md). + +### To make a column read-only programmatically + +- Set the property to `true`. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#064](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#064)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#064](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#064)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1` with a column named `CompanyName`. + +- References to the and assemblies. + +## See also + +- +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) +- [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls.md new file mode 100644 index 0000000000..a978135bc3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls.md @@ -0,0 +1,93 @@ +--- +title: Make thread-safe calls to controls +ms.date: "02/19/2019" +description: Learn how to implement multithreading in your app by calling cross-thread controls in a thread-safe way. +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "EHInvalidOperation.WinForms.IllegalCrossThreadCall" +helpviewer_keywords: + - "thread safety [Windows Forms], calling controls [Windows Forms]" + - "calling controls [Windows Forms], thread safety [Windows Forms]" + - "CheckForIllegalCrossThreadCalls property [Windows Forms]" + - "Windows Forms controls [Windows Forms], multithreading" + - "BackgroundWorker class [Windows Forms], examples" + - "threading [Windows Forms], cross-thread calls" + - "controls [Windows Forms], multithreading" +ms.assetid: 138f38b6-1099-4fd5-910c-390b41cbad35 +--- +# How to: Make thread-safe calls to Windows Forms controls + +Multithreading can improve the performance of Windows Forms apps, but access to Windows Forms controls isn't inherently thread-safe. Multithreading can expose your code to very serious and complex bugs. Two or more threads manipulating a control can force the control into an inconsistent state and lead to race conditions, deadlocks, and freezes or hangs. If you implement multithreading in your app, be sure to call cross-thread controls in a thread-safe way. For more information, see [Managed threading best practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices). + +There are two ways to safely call a Windows Forms control from a thread that didn't create that control. You can use the method to call a delegate created in the main thread, which in turn calls the control. Or, you can implement a , which uses an event-driven model to separate work done in the background thread from reporting on the results. + +## Unsafe cross-thread calls + +It's unsafe to call a control directly from a thread that didn't create it. The following code snippet illustrates an unsafe call to the control. The `Button1_Click` event handler creates a new `WriteTextUnsafe` thread, which sets the main thread's property directly. + +```csharp +private void Button1_Click(object sender, EventArgs e) +{ + thread2 = new Thread(new ThreadStart(WriteTextUnsafe)); + thread2.Start(); +} +private void WriteTextUnsafe() +{ + textBox1.Text = "This text was set unsafely."; +} +``` + +```vb +Private Sub Button1_Click(ByVal sender As Object, e As EventArgs) Handles Button1.Click + Thread2 = New Thread(New ThreadStart(AddressOf WriteTextUnsafe)) + Thread2.Start() +End Sub + +Private Sub WriteTextUnsafe() + TextBox1.Text = "This text was set unsafely." +End Sub +``` + +The Visual Studio debugger detects these unsafe thread calls by raising an with the message, **Cross-thread operation not valid. Control "" accessed from a thread other than the thread it was created on.** The always occurs for unsafe cross-thread calls during Visual Studio debugging, and may occur at app runtime. You should fix the issue, but you can disable the exception by setting the property to `false`. + +## Safe cross-thread calls + +The following code examples demonstrate two ways to safely call a Windows Forms control from a thread that didn't create it: + +1. The method, which calls a delegate from the main thread to call the control. +2. A component, which offers an event-driven model. + +In both examples, the background thread sleeps for one second to simulate work being done in that thread. + +You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. For more information, see [Command-line building with csc.exe](https://docs.microsoft.com/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe) or [Build from the command line (Visual Basic)](https://docs.microsoft.com/dotnet/visual-basic/reference/command-line-compiler/building-from-the-command-line). + +Starting with .NET Core 3.0, you can also build and run the examples as Windows .NET Core apps from a folder that has a .NET Core Windows Forms *\.csproj* project file. + +## Example: Use the Invoke method with a delegate + +The following example demonstrates a pattern for ensuring thread-safe calls to a Windows Forms control. It queries the property, which compares the control's creating thread ID to the calling thread ID. If the thread IDs are the same, it calls the control directly. If the thread IDs are different, it calls the method with a delegate from the main thread, which makes the actual call to the control. + +The `SafeCallDelegate` enables setting the control's property. The `WriteTextSafe` method queries . If returns `true`, `WriteTextSafe` passes the `SafeCallDelegate` to the method to make the actual call to the control. If returns `false`, `WriteTextSafe` sets the directly. The `Button1_Click` event handler creates the new thread and runs the `WriteTextSafe` method. + + [!code-csharp[ThreadSafeCalls#1](~/samples/snippets/winforms/thread-safe/example1/cs/Form1.cs)] + [!code-vb[ThreadSafeCalls#1](~/samples/snippets/winforms/thread-safe/example1/vb/Form1.vb)] + +## Example: Use a BackgroundWorker event handler + +An easy way to implement multithreading is with the component, which uses an event-driven model. The background thread runs the event, which doesn't interact with the main thread. The main thread runs the and event handlers, which can call the main thread's controls. + +To make a thread-safe call by using , create a method in the background thread to do the work, and bind it to the event. Create another method in the main thread to report the results of the background work, and bind it to the or event. To start the background thread, call . + +The example uses the event handler to set the control's property. For an example using the event, see . + + [!code-csharp[ThreadSafeCalls#2](~/samples/snippets/winforms/thread-safe/example2/cs/Form1.cs)] + [!code-vb[ThreadSafeCalls#2](~/samples/snippets/winforms/thread-safe/example2/vb/Form1.vb)] + +## See also + +- +- [How to: Run an operation in the background](how-to-run-an-operation-in-the-background.md) +- [How to: Implement a form that uses a background operation](how-to-implement-a-form-that-uses-a-background-operation.md) +- [Develop custom Windows Forms controls with the .NET Framework](developing-custom-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-make-your-control-invisible-at-run-time.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-make-your-control-invisible-at-run-time.md new file mode 100644 index 0000000000..aafd498492 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-make-your-control-invisible-at-run-time.md @@ -0,0 +1,40 @@ +--- +title: "How to: Make Your Control Invisible at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], making invisible at run time" + - "invisible controls" + - "user controls [Windows Forms], invisible" + - "custom controls [Windows Forms], invisible" + - "run time [Windows Forms], making controls invisible" +ms.assetid: 69eb2e72-32f5-4f79-a157-c2c5f60c1628 +--- +# How to: Make Your Control Invisible at Run Time +There are times when you might want to create a user control that is invisible at run time. For example, a control that is an alarm clock might be invisible except when the alarm was sounding. This is easily accomplished by setting the property. If the property is `true`, your control will appear as normal. If `false`, your control will be hidden. Although code in your control may still run while invisible, you will not be able to interact with the control through the user interface. If you want to create an invisible control that still responds to user input (for example, mouse clicks), you should create a transparent control. For more information, see [Giving Your Control a Transparent Background](how-to-give-your-control-a-transparent-background.md). + +### To make your control invisible at run time + +1. Set the property to `false`. + + ```vb + ' To set the Visible property from within your object's own code. + Me.Visible = False + ' To set the Visible property from another object. + myControl1.Visible = False + ``` + + ```csharp + // To set the Visible property from within your object's own code. + this.Visible = false; + // To set the Visible property from another object. + myControl1.Visible = false; + ``` + +## See also + +- +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [How to: Give Your Control a Transparent Background](how-to-give-your-control-a-transparent-background.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-manage-toolstrip-overflow-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-manage-toolstrip-overflow-in-windows-forms.md new file mode 100644 index 0000000000..cbf5911376 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-manage-toolstrip-overflow-in-windows-forms.md @@ -0,0 +1,49 @@ +--- +title: "How to: Manage ToolStrip Overflow" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], managing overflow" + - "toolbars [Windows Forms], managing overflow" + - "examples [Windows Forms], toolbars" + - "CanOverflow property" +ms.assetid: fa10e0ad-4cbf-4c0d-9082-359c2f855d4e +--- + +# How to: Manage ToolStrip Overflow in Windows Forms + +When all the items on a control do not fit in the allotted space, you can enable overflow functionality on the and determine the overflow behavior of specific s. + +When you add s that require more space than is allotted to the given the form's current size, a automatically appears on the . The appears, and overflow-enabled items are moved into the drop-down overflow menu. This allows you to customize and prioritize how your items properly adjust to different form sizes. You can also change the appearance of your items when they fall into the overflow by using the and properties and the event. If you enlarge the form at either design time or run time, more s can be displayed on the main and the might even disappear until you decrease the size of the form. + +## To enable overflow on a ToolStrip control + +- Ensure that the property is not set to `false` for the . The default is `True`. + + When is `True` (the default), a is sent to the drop-down overflow menu when the content of the exceeds the width of a horizontal or the height of a vertical . + +## To specify overflow behavior of a specific ToolStripItem + +- Set the property of the to the desired value. The possibilities are `Always`, `Never`, and `AsNeeded`. The default is `AsNeeded`. + + ```vb + toolStripTextBox1.Overflow = _ + System.Windows.Forms.ToolStripItemOverflow.Never + ``` + + ```csharp + toolStripTextBox1.Overflow = _ + System.Windows.Forms.ToolStripItemOverflow.Never; + ``` + +## See also + +- +- +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-bands-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-bands-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..02f0f3c1bd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-bands-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,33 @@ +--- +title: Manipulate Bands in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data grids [Windows Forms], manipulating bands" + - "bands [Windows Forms], manipulating in Windows Forms" + - "DataGridView control [Windows Forms], manipulating bands" +ms.assetid: 1ea3470e-480f-4edc-bcbd-51373eca3856 +--- +# How to: Manipulate Bands in the Windows Forms DataGridView Control +The following code example shows various ways to manipulate rows and columns using properties of the class from which the and classes derive. + +## Example + [!code-cpp[System.Windows.Forms.DataGridView.ButtonDemos#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewBandDemo.cpp#0)] + [!code-csharp[System.Windows.Forms.DataGridView.ButtonDemos#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewBandDemo.cs#0)] + [!code-vb[System.Windows.Forms.DataGridView.ButtonDemos#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewbanddemo.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-columns-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-columns-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..98d01f8f66 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-columns-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,37 @@ +--- +title: Manipulate Columns in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "DataGridView control [Windows Forms], manipulating columns" + - "columns [Windows Forms], manipulating" + - "data grids [Windows Forms], manipulating columns" +ms.assetid: d8cfe6b3-bbab-4182-bec2-0517d9f1eaf6 +--- + +# How to: Manipulate Columns in the Windows Forms DataGridView Control + +The following code example shows the various ways to manipulate columns using properties of the class. + +## Example + +[!code-cpp[System.Windows.Forms.DataGridView.ButtonDemos#100](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewColumnDemo.cpp#100)] +[!code-csharp[System.Windows.Forms.DataGridView.ButtonDemos#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewColumnDemo.cs#100)] +[!code-vb[System.Windows.Forms.DataGridView.ButtonDemos#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewcolumndemo.vb#100)] + +## Compiling the Code + +This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-rows-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-rows-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..ba92fb8ecd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-manipulate-rows-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,33 @@ +--- +title: Manipulate Rows in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "DataGridView control [Windows Forms], manipulating rows" + - "data grids [Windows Forms], manipulating rows" + - "rows [Windows Forms], manipulating on Windows Forms" +ms.assetid: 522d8944-e073-4488-9673-923f0a8d7214 +--- +# How to: Manipulate Rows in the Windows Forms DataGridView Control +The following code example shows the various ways to manipulate rows using properties of the class. + +## Example + [!code-cpp[System.Windows.Forms.DataGridView.ButtonDemos#200](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewRowDemo.cpp#200)] + [!code-csharp[System.Windows.Forms.DataGridView.ButtonDemos#200](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewRowDemo.cs#200)] + [!code-vb[System.Windows.Forms.DataGridView.ButtonDemos#200](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewrowdemo.vb#200)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md new file mode 100644 index 0000000000..e8ce5f5833 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md @@ -0,0 +1,85 @@ +--- +title: "How to: Modify the Size or Placement of a Picture at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "images [Windows Forms], controlling placement in PictureBox control [Windows Forms]" + - "examples [Windows Forms], PictureBox control" + - "PictureBox control [Windows Forms], picture size and alignment" + - "pictures [Windows Forms], controlling placement in PictureBox control [Windows Forms]" +ms.assetid: d0b332a3-fae2-4891-957c-dc3e17743326 +--- +# How to: Modify the Size or Placement of a Picture at Run Time (Windows Forms) +If you use the Windows Forms control on a form, you can set the property on it to: + +- Align the picture's upper left corner with the control's upper left corner + +- Center the picture within the control + +- Adjust the size of the control to fit the picture it displays + +- Stretch any picture it displays to fit the control + + Stretching a picture (especially one in bitmap format) can produce a loss in image quality. Metafiles, which are lists of graphics instructions for drawing images at run time, are better suited for stretching than bitmaps are. + +### To set the SizeMode property at run time + +1. Set to (the default), , , or . means that the image is placed in the control's upper-left corner; if the image is larger than the control, its lower and right edges are clipped. means that the image is centered within the control; if the image is larger than the control, the picture's outside edges are clipped. means that the size of the control is adjusted to the size of the image. is the reverse, and means that the size of the image is adjusted to the size of the control. + + In the example below, the path set for the location of the image is the My Documents folder. This is done, because you can assume that most computers running the Windows operating system will include this directory. This also allows users with minimal system access levels to safely run the application. The example below assumes a form with a control already added. + + ```vb + Private Sub StretchPic() + ' Stretch the picture to fit the control. + PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage + ' Load the picture into the control. + ' You should replace the bold image + ' in the sample below with an icon of your own choosing. + PictureBox1.Image = Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Image.gif") + End Sub + ``` + + ```csharp + private void StretchPic(){ + // Stretch the picture to fit the control. + PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; + // Load the picture into the control. + // You should replace the bold image + // in the sample below with an icon of your own choosing. + // Note the escape character used (@) when specifying the path. + PictureBox1.Image = Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + + @"\Image.gif") + } + ``` + + ```cpp + private: + void StretchPic() + { + // Stretch the picture to fit the control. + pictureBox1->SizeMode = PictureBoxSizeMode::StretchImage; + // Load the picture into the control. + // You should replace the bold image + // in the sample below with an icon of your own choosing. + pictureBox1->Image = Image::FromFile(String::Concat( + System::Environment::GetFolderPath( + System::Environment::SpecialFolder::Personal), + "\\Image.gif")); + } + ``` + +## See also + +- +- [How to: Load a Picture Using the Designer](how-to-load-a-picture-using-the-designer-windows-forms.md) +- [PictureBox Control Overview](picturebox-control-overview-windows-forms.md) +- [How to: Set Pictures at Run Time](how-to-set-pictures-at-run-time-windows-forms.md) +- [PictureBox Control](picturebox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md new file mode 100644 index 0000000000..0415392339 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md @@ -0,0 +1,28 @@ +--- +title: "How to: Move a ToolStrip Out of a ToolStripContainer onto a Form" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], parenting to forms" + - "Windows Forms, parenting ToolStrip controls" +ms.assetid: a1c94a7f-6fc5-4e4c-84cf-ff11dc573d33 +--- +# How to: Move a ToolStrip Out of a ToolStripContainer onto a Form +Use the following procedure to move a out of a onto a form. + +## To move a ToolStrip out of a ToolStripContainer onto a form + +1. Select the . + +2. Cut the by pressing CTRL+X, or right-click the and choose **Cut** from the context menu. + +3. Select the form. + +4. Paste the by pressing CTRL+V, or choose **Paste** from the **Edit** menu. + +5. Set the property of the to **Top**. + +## See also + +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-move-toolstripmenuitems.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-move-toolstripmenuitems.md new file mode 100644 index 0000000000..4d80a592c1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-move-toolstripmenuitems.md @@ -0,0 +1,68 @@ +--- +title: "How to: Move ToolStripMenuItems" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStripMenuItems [Windows Forms], moving" + - "menus [Windows Forms], arranging items" + - "ToolStripMenuItems [Windows Forms], dragging and dropping" + - "menu items [Windows Forms], moving" + - "menu items [Windows Forms], cutting and pasting" + - "menu items [Windows Forms], dragging and dropping" + - "MenuStrip control [Windows Forms], arranging items" + - "ToolStripMenuItems [Windows Forms], cutting and pasting" +ms.assetid: cab9e03e-4edd-4c25-b3e3-bd1edc602bd9 +--- +# How to: Move ToolStripMenuItems +At design time, you can move entire top-level menus and their menu items to a different place on the . You can also move individual menu items between top-level menus or change the position of menu items within a menu. + +## To move a top-level menu and its menu items to another top-level location + +1. Click and hold down the left mouse button on the menu that you want to move. + +2. Drag the insertion point to the top-level menu that is before the intended new location and release the left mouse button. + + The selected menu moves to the right of the insertion point. + +## To move a top-level menu and its menu items to a drop-down location + +1. Left-click the menu that you want to move and press CTRL+X, or right-click the menu and select **Cut** from the shortcut menu. + +2. In the destination top-level menu, left-click the menu item above the intended new location and press CTRL+V, or right-click the menu item above the intended new location and select **Paste** from the shortcut menu. + + The menu that you cut is inserted after the selected menu item. + +## To move a menu item within a menu using the Items Collection Editor + +1. Right-click the menu that contains the menu item you want to move. + +2. From the shortcut menu, choose **Edit DropDownItems**. + +3. In the **Items Collection Editor**, left-click the menu item you want to move. + +4. Click the UP and DOWN ARROW keys to move the menu item within the menu. + +5. Click **OK**. + +## To move a menu item within a menu using the keyboard + +1. Press and hold down the ALT key. + +2. Click and hold the left mouse button on the menu item that you want to move. + +3. Drag the menu item to the new location and release the left mouse button. + +## To move a menu item to another menu + +1. Left-click the menu item that you want to move and press CTRL+X, or right-click the menu item and choose **Cut** from the shortcut menu. + +2. Left-click the menu that will contain the menu item that you cut. + +3. Left-click the menu item that is before the intended new location and press CTRL+V, or right-click the menu item that is before the intended new location and select **Paste** from the shortcut menu. + + The menu item that you cut is inserted after the selected menu item. + +## See also + +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-navigate-data-with-the-windows-forms-bindingnavigator-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-navigate-data-with-the-windows-forms-bindingnavigator-control.md new file mode 100644 index 0000000000..3a831486be --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-navigate-data-with-the-windows-forms-bindingnavigator-control.md @@ -0,0 +1,52 @@ +--- +title: Navigate Data with BindingNavigator Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "BindingNavigator control [Windows Forms], navigating data" + - "data [Windows Forms], navigating" + - "data navigation" + - "examples [Windows Forms], BindingNavigator control" +ms.assetid: 0e5d4f34-bc9b-47cf-9b8d-93acbb1f1dbb +--- +# How to: Navigate Data with the Windows Forms BindingNavigator Control +The advent of the control in Windows Forms enables developers to provide end users with a simple data navigation and manipulation user interface on the forms they create. + + The control is a control with buttons preconfigured for navigation to the first, last, next, and previous record in a data set, as well as buttons to add and delete records. Adding buttons to the control is easy, because it is a control. For examples, see [How to: Add Load, Save, and Cancel Buttons to the Windows Forms BindingNavigator Control](load-save-and-cancel-bindingnavigator.md). + + For each button on the control, there is a corresponding member of the component that programmatically allows the same functionality. For example, the button corresponds to the method of the component, the button corresponds to the method, and so on. As a result, enabling the control to navigate data records is a simple as setting its property to the appropriate component on the form. + +### To set up the BindingNavigator control + +1. Add a component named `bindingSource1` and two controls named `textBox1` and `textBox2`. + +2. Bind `bindingSource1` to data, and the textbox controls to `bindingSource1`. To do this, paste the following code into your form and call `LoadData` from the form's constructor or event-handling method. + + [!code-csharp[System.Windows.Forms.BindingNavigatorNavigate#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.BindingNavigatorNavigate#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/VB/Form1.vb#2)] + +3. Add a control named `bindingNavigator1` to your form. + +4. Set the property for `bindingNavigator1` to `bindingSource1`. You can do this with the designer or in code. + + [!code-csharp[System.Windows.Forms.BindingNavigatorNavigate#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.BindingNavigatorNavigate#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/VB/Form1.vb#3)] + +## Example + The following code example is the complete example for the steps listed previously. + + [!code-csharp[System.Windows.Forms.BindingNavigatorNavigate#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.BindingNavigatorNavigate#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing, System.Windows.Forms and System.Xml assemblies. + +## See also + +- +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-navigate-to-a-url-with-the-webbrowser-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-navigate-to-a-url-with-the-webbrowser-control.md new file mode 100644 index 0000000000..9bdcda918f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-navigate-to-a-url-with-the-webbrowser-control.md @@ -0,0 +1,46 @@ +--- +title: "How to: Navigate to a URL with the WebBrowser Control" +description: Learn how to use the Windows Forms WebBrowser.Navigate control to navigate to a specific URL. Also learn how to determine when the new document is loaded. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "WebBrowser.Navigate" +helpviewer_keywords: + - "WebBrowser control [Windows Forms], examples" + - "URLs [Windows Forms], navigating to" + - "WebBrowser control [Windows Forms], navigating to URLs" + - "examples [Windows Forms], WebBrowser control" +ms.assetid: b3ec38cb-f509-4d0b-bd79-9f3611259c62 +--- +# How to: Navigate to a URL with the WebBrowser Control +The following code example demonstrates how to navigate the control to a specific URL. + + To determine when the new document is fully loaded, handle the event. For a demonstration of this event, see [How to: Print with a WebBrowser Control](how-to-print-with-a-webbrowser-control.md). + +## Example + +```vb +Me.webBrowser1.Navigate("https://www.microsoft.com") +``` + +```csharp +this.webBrowser1.Navigate("https://www.microsoft.com"); +``` + +## Compiling the Code + This example requires: + +- A control named `webBrowser1`. + +- References to the `System` and `System.Windows.Forms` assemblies. + +## See also + +- +- +- +- +- [WebBrowser Control](webbrowser-control-windows-forms.md) +- [How to: Print with a WebBrowser Control](how-to-print-with-a-webbrowser-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-open-files-using-the-openfiledialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-open-files-using-the-openfiledialog-component.md new file mode 100644 index 0000000000..6659dea9a6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-open-files-using-the-openfiledialog-component.md @@ -0,0 +1,41 @@ +--- +title: "How to: Open files with the OpenFileDialog component" +ms.date: "02/11/2019" +description: Learn how to use the OpenFileDialog component to open the Windows dialog box for browsing and selecting files. +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "OpenFileDialog component [Windows Forms], opening files" + - "OpenFile method [Windows Forms], OpenFileDialog component" + - "files [Windows Forms], opening with OpenFileDialog component" +ms.assetid: 9d88367a-cc21-4ffd-be74-89fd63767d35 +--- +# How to: Open files with the OpenFileDialog + +The component opens the Windows dialog box for browsing and selecting files. To open and read the selected files, you can use the method, or create an instance of the class. The following examples show both approaches. + +In .NET Framework, to get or set the property requires a privilege level granted by the class. The examples run a permission check, and can throw an exception due to insufficient privileges if run in a partial-trust context. For more information, see [Code access security basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics). + +You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. For more information, see [Command-line building with csc.exe](https://docs.microsoft.com/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe) or [Build from the command line](https://docs.microsoft.com/dotnet/visual-basic/reference/command-line-compiler/building-from-the-command-line). + +Starting with .NET Core 3.0, you can also build and run the examples as Windows .NET Core apps from a folder that has a .NET Core Windows Forms *\.csproj* project file. + +## Example: Read a file as a stream with StreamReader + +The following example uses the Windows Forms control's event handler to open the with the method. After the user chooses a file and selects **OK**, an instance of the class reads the file and displays its contents in the form's text box. For more information about reading from file streams, see and . + + [!code-csharp[OpenFileDialog#1](~/samples/snippets/winforms/open-files/example1/cs/Form1.cs)] + [!code-vb[OpenFileDialog#1](~/samples/snippets/winforms/open-files/example1/vb/Form1.vb)] + +## Example: Open a file from a filtered selection with OpenFile + +The following example uses the control's event handler to open the with a filter that shows only text files. After the user chooses a text file and selects **OK**, the method is used to open the file in Notepad. + + [!code-csharp[OpenFileDialog#2](~/samples/snippets/winforms/open-files/example2/cs/Form1.cs)] + [!code-vb[OpenFileDialog#2](~/samples/snippets/winforms/open-files/example2/vb/Form1.vb)] + +## See also + +- +- [OpenFileDialog component](openfiledialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-opt-out-of-file-dialog-box-automatic-upgrade.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-opt-out-of-file-dialog-box-automatic-upgrade.md new file mode 100644 index 0000000000..2b4ce69524 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-opt-out-of-file-dialog-box-automatic-upgrade.md @@ -0,0 +1,21 @@ +--- +title: "How To: Opt Out of File Dialog Box Automatic Upgrade" +ms.date: "03/30/2017" +helpviewer_keywords: + - "OpenFileDialog [Windows Forms], opt out of automatic upgrade" + - "file dialog box [Windows Forms], opt out of automatic upgrade" + - "Windows Vista file dialog box [Windows Forms], opt out of automatic upgrade" + - "SaveFileDialog [Windows Forms], opt out of automatic upgrade" + - "AutoUpgradeEnabled property" +ms.assetid: 522e482e-cc01-48b1-8d59-9617dc2c4ac1 +--- +# How To: Opt Out of File Dialog Box Automatic Upgrade +When the and classes are used in an application, their appearance and behavior depend on the version of Windows the application is running on. When an application that was created on the .NET Framework 2.0 or earlier is displayed on Windows Vista, and are automatically displayed with the Windows Vista appearance and behavior. Starting in the .NET Framework 3.0, you can opt out of the automatic upgrade to display the and with a Windows XP-style appearance and behavior. + +### To opt out of file dialog box automatic upgrade + +1. Set the property of or to `false` before you display the dialog box. + +## See also + +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-beep-from-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-beep-from-a-windows-form.md new file mode 100644 index 0000000000..414a2d278f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-beep-from-a-windows-form.md @@ -0,0 +1,44 @@ +--- +title: "How to: Play a Beep from a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sounds [Windows Forms], beep" + - "Windows Forms, sounds" + - "sounds [Windows Forms], playing" + - "forms [Windows Forms], sounds" + - "examples [Windows Forms], sounds" +ms.assetid: 7ea5cded-4888-4f35-8f28-5cab1a55c973 +--- +# How to: Play a Beep from a Windows Form +This example plays a beep at run time. + +## Example + +```vb +Public Sub OnePing() + Beep() +End Sub +``` + +```csharp +public void onePing() +{ + SystemSounds.Beep.Play(); +} +``` + +> [!NOTE] +> The sound played in the C# code sample is determined by the system sound setting. For more information, see . + +## Compiling the Code + For C#, this example requires a reference to the namespace. + +## See also + +- +- +- [How to: Play a System Sound from a Windows Form](how-to-play-a-system-sound-from-a-windows-form.md) +- [How to: Play a Sound from a Windows Form](how-to-play-a-sound-from-a-windows-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-sound-embedded-in-a-resource-from-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-sound-embedded-in-a-resource-from-a-windows-form.md new file mode 100644 index 0000000000..0ab33f5597 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-sound-embedded-in-a-resource-from-a-windows-form.md @@ -0,0 +1,34 @@ +--- +title: "How to: Play a Sound Embedded in a Resource from a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sounds [Windows Forms], playing from resources" + - "resources [Windows Forms], playing sounds" + - "playing sounds [Windows Forms], from resources" + - "SoundPlayer class [Windows Forms], playing sounds from resources" +ms.assetid: 7d148bb6-8a1e-47d7-a08d-35828d2e688f +--- +# How to: Play a Sound Embedded in a Resource from a Windows Form +You can use the class to play a sound from an embedded resource. + +## Example + [!code-csharp[System.Windows.Forms.Sound#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Sound/CS/soundtestform.cs#10)] + [!code-vb[System.Windows.Forms.Sound#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Sound/VB/soundtestform.vb#10)] + +## Compiling the Code + This example requires: + + Importing the namespace. + + Including the sound file as an embedded resource in your project. + + Replacing "\" with the name of the assembly in which the sound file is embedded. Do not include the ".dll" suffix. + +## See also + +- +- [How to: Play a Sound from a Windows Form](how-to-play-a-sound-from-a-windows-form.md) +- [How to: Loop a Sound Playing on a Windows Form](how-to-loop-a-sound-playing-on-a-windows-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-sound-from-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-sound-from-a-windows-form.md new file mode 100644 index 0000000000..bb7c0caba2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-sound-from-a-windows-form.md @@ -0,0 +1,65 @@ +--- +title: "How to: Play a Sound from a Windows Form" +description: Learn how to play a sound from a Windows Form at a given path at runtime. Also, learn about compiling the code and the .NET Security Framework. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "playing sounds [Windows Forms], Windows Forms" + - "sounds [Windows Forms], playing" + - "sounds" + - "My.Computer.Audio object [Windows Forms], playing sounds" + - "examples [Windows Forms], sounds" +ms.assetid: 3d3350b7-1ebd-4e05-a738-48ca1160a19d +--- +# How to: Play a Sound from a Windows Form +This example plays a sound at a given path at run time. + +## Example + +```vb +Sub PlaySimpleSound() + My.Computer.Audio.Play("c:\Windows\Media\chimes.wav") +End Sub +``` + +```csharp +private void playSimpleSound() +{ + SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\chimes.wav"); + simpleSound.Play(); +} +``` + +## Compiling the Code + This example requires: + +- That you replace the file name `"c:\Windows\Media\chimes.wav"` with a valid file name. + +- (C#) A reference to the namespace. + +## Robust Programming + File operations should be enclosed within appropriate structured exception handling blocks. + + The following conditions may cause an exception: + +- The path name is malformed. For example, it contains illegal characters or is only white space ( class). + +- The path is read-only ( class). + +- The path name is `null` ( class). + +- The path name is too long ( class). + +- The path is invalid ( class). + +- The path is only a colon, ":" ( class). + +## .NET Framework Security + Do not make decisions about the contents of the file based on the name of the file. For example, the file `Form1.vb` may not be a Visual Basic source file. Verify all inputs before using the data in your application. + +## See also + +- +- [How to: Load a Sound Asynchronously within a Windows Form](how-to-load-a-sound-asynchronously-within-a-windows-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-system-sound-from-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-system-sound-from-a-windows-form.md new file mode 100644 index 0000000000..9028a8888e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-play-a-system-sound-from-a-windows-form.md @@ -0,0 +1,45 @@ +--- +title: "How to: Play a System Sound from a Windows Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sounds [Windows Forms], playing for system events" + - "playing sounds [Windows Forms], Windows Forms" + - "system sounds [Windows Forms], playing from Windows Forms" + - "playing sounds [Windows Forms], system" + - "SoundPlayer class [Windows Forms], system sounds" + - "sounds [Windows Forms], playing" + - "examples [Windows Forms], sounds" +ms.assetid: afb206ff-4824-4804-a8d4-185bf5ad8e7c +--- +# How to: Play a System Sound from a Windows Form +The following code example plays the `Exclamation` system sound at run time. For more information about system sounds, see . + +## Example + +```vb +Public Sub PlayExclamation() + SystemSounds.Exclamation.Play() +End Sub +``` + +```csharp +public void playExclamation() +{ + SystemSounds.Exclamation.Play(); +} +``` + +## Compiling the Code + This example requires: + +- A reference to the namespace. + +## See also + +- +- +- [How to: Play a Beep from a Windows Form](how-to-play-a-beep-from-a-windows-form.md) +- [How to: Play a Sound from a Windows Form](how-to-play-a-sound-from-a-windows-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-position-a-toolstripitem-on-a-toolstrip.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-position-a-toolstripitem-on-a-toolstrip.md new file mode 100644 index 0000000000..02c71e23dd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-position-a-toolstripitem-on-a-toolstrip.md @@ -0,0 +1,26 @@ +--- +title: "How to: Position a ToolStripItem on a ToolStrip" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], aligning items" + - "toolbars [Windows Forms], positioning items" +ms.assetid: 11fd7c5b-ee5c-4993-9a11-89127ff0aa7a +--- +# How to: Position a ToolStripItem on a ToolStrip +You can move or add a to the left or right side of a . + +### To move or add a ToolStripItem to the left side of a ToolStrip + +1. Set the property of the to . + +### To move or add a ToolStripItem to the right side of a ToolStrip + +1. Set the property of the to . + +## See also + +- +- +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-position-controls-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-position-controls-on-windows-forms.md new file mode 100644 index 0000000000..a24853374e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-position-controls-on-windows-forms.md @@ -0,0 +1,103 @@ +--- +title: Position Controls +description: Learn how to use the Windows Forms Designer in Visual Studio or the Location property to position your controls. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "Location" + - "Location.Y" + - "Location.X" +helpviewer_keywords: + - "controls [Windows Forms]" + - "controls [Windows Forms], moving" + - "snaplines" + - "controls [Windows Forms], positioning" +ms.assetid: 4693977e-34a4-4f19-8221-68c3120c2b2b +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Position controls on Windows Forms + +To position controls, use the Windows Forms Designer in Visual Studio or specify the property. + +## Position a control on the design surface of the Windows Forms Designer + +In Visual Studio, drag the control to the appropriate location with the mouse. + +> [!NOTE] +> Select the control and move it with the ARROW keys to position it more precisely. Also, *snaplines* assist you in placing controls precisely on your form. For more information, see [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md). + +## Position a control using the Properties window + +1. In Visual Studio, select the control you want to position. + +2. In the **Properties** window, enter values for the property, separated by a comma, to position the control within its container. + + The first number (X) is the distance from the left border of the container; the second number (Y) is the distance from the upper border of the container area, measured in pixels. + + > [!NOTE] + > You can expand the property to type the **X** and **Y** values individually. + +## Position a control programmatically + +1. Set the property of the control to a . + + ```vb + Button1.Location = New Point(100, 100) + ``` + + ```csharp + button1.Location = new Point(100, 100); + ``` + + ```cpp + button1->Location = Point(100, 100); + ``` + +2. Change the X coordinate of the control's location using the subproperty. + + ```vb + Button1.Left = 300 + ``` + + ```csharp + button1.Left = 300; + ``` + + ```cpp + button1->Left = 300; + ``` + +## Increment a control's location programmatically + +Set the subproperty to increment the X coordinate of the control. + +```vb +Button1.Left += 200 +``` + +```csharp +button1.Left += 200; +``` + +```cpp +button1->Left += 200; +``` + +> [!NOTE] +> Use the property to set a control's X and Y positions simultaneously. To set a position individually, use the control's (**X**) or (**Y**) subproperty. Do not try to implicitly set the X and Y coordinates of the structure that represents the button's location, because this structure contains a copy of the button's coordinates. + +## See also + +- [Windows Forms Controls](index.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) +- [How to: Set the Screen Location of Windows Forms](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/52aha046(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-print-with-a-webbrowser-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-print-with-a-webbrowser-control.md new file mode 100644 index 0000000000..7f13fb1d5d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-print-with-a-webbrowser-control.md @@ -0,0 +1,38 @@ +--- +title: "How to: Print with a WebBrowser Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "WebBrowser.Print" +helpviewer_keywords: + - "printing [Windows Forms], Web pages" + - "WebBrowser control [Windows Forms], examples" + - "WebBrowser control [Windows Forms], printing from" + - "Web pages [Windows Forms], printing" + - "examples [Windows Forms], WebBrowser control" +ms.assetid: 3fb2a305-64ce-4b6c-9258-5330d3f21b6c +--- +# How to: Print with a WebBrowser Control +The following code example demonstrates how use the control to print a Web page without displaying it. + +## Example + [!code-csharp[WebBrowserMisc#10](~/samples/snippets/csharp/VS_Snippets_Winforms/WebBrowserMisc/CS/WebBrowserMisc.cs#10)] + [!code-vb[WebBrowserMisc#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WebBrowserMisc/vb/WebBrowserMisc.vb#10)] + +## Compiling the Code + This example requires: + +- References to the `System` and `System.Windows.Forms` assemblies. + +## See also + +- +- +- +- [How to: Navigate to a URL with the WebBrowser Control](how-to-navigate-to-a-url-with-the-webbrowser-control.md) +- [How to: Add Web Browser Capabilities to a Windows Forms Application](how-to-add-web-browser-capabilities-to-a-windows-forms-application.md) +- [How to: Create an HTML Document Viewer in a Windows Forms Application](how-to-create-an-html-document-viewer-in-a-windows-forms-application.md) +- [WebBrowser Control Overview](webbrowser-control-overview.md) +- [WebBrowser Security](webbrowser-security.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-provide-a-toolbox-bitmap-for-a-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-provide-a-toolbox-bitmap-for-a-control.md new file mode 100644 index 0000000000..6bb945b246 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-provide-a-toolbox-bitmap-for-a-control.md @@ -0,0 +1,70 @@ +--- +title: "How to: Provide a Toolbox Bitmap for a Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Toolbox [Windows Forms], adding bitmaps for custom controls" + - "custom controls [Windows Forms], Toolbox bitmaps" + - "bitmaps [Windows Forms], custom controls" +ms.assetid: 0ed0840a-616d-41ba-a27d-3573241932ad +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Provide a Toolbox Bitmap for a Control + +If you want to have a special icon for your control appear in the **Toolbox** of Visual Studio, you can specify a particular image by using the . This class is an *attribute*, a special kind of class you can attach to other classes. For more information about attributes, see [Attributes overview (Visual Basic)](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/concepts/attributes/index) for Visual Basic or [Attributes (C#)](https://docs.microsoft.com/dotnet/csharp/programming-guide/concepts/attributes/index) for C#. + +Using the , you can specify a string that indicates the path and file name for a 16 by 16 pixel bitmap. This bitmap then appears next to your control when added to the **Toolbox**. You can also specify a , in which case the bitmap associated with that type is loaded. If you specify both a and a string, the control searches for an image resource with the name specified by the string parameter in the assembly containing the type specified by the parameter. + +## To specify a Toolbox bitmap for your control + +1. Add the to the class declaration of your control before the `Class` keyword for visual Basic, and above the class declaration for Visual C#. + + ```vb + ' Specifies the bitmap associated with the Button type. + Class MyControl1 + ' Specifies a bitmap file. + End Class + _ + Class MyControl2 + End Class + ' Specifies a type that indicates the assembly to search, and the name + ' of an image resource to look for. + Class MyControl + End Class + ``` + + ```csharp + // Specifies the bitmap associated with the Button type. + [ToolboxBitmap(typeof(Button))] + class MyControl1 : UserControl + { + } + // Specifies a bitmap file. + [ToolboxBitmap(@"C:\Documents and Settings\Joe\MyPics\myImage.bmp")] + class MyControl2 : UserControl + { + } + // Specifies a type that indicates the assembly to search, and the name + // of an image resource to look for. + [ToolboxBitmap(typeof(MyControl), "MyControlBitmap")] + class MyControl : UserControl + { + } + ``` + +2. Rebuild the project. + + > [!NOTE] + > The bitmap does not appear in the Toolbox for autogenerated controls and components. To see the bitmap, reload the control by using the **Choose Toolbox Items** dialog box. For more information, see [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md). + +## See also + +- +- [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md) +- [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md) +- [Attributes overview (Visual Basic)](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/concepts/attributes/index) +- [Attributes (C#)](https://docs.microsoft.com/dotnet/csharp/programming-guide/concepts/attributes/index) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-provide-standard-menu-items-to-a-form.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-provide-standard-menu-items-to-a-form.md new file mode 100644 index 0000000000..e6dd1b6525 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-provide-standard-menu-items-to-a-form.md @@ -0,0 +1,36 @@ +--- +title: "How to: Provide Standard Menu Items to a Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "menu items [Windows Forms], standard" + - "ToolStrip control [Windows Forms]" +ms.assetid: 75db9126-e70c-4e81-921d-b83c0a4a9f50 +--- +# How to: Provide Standard Menu Items to a Form +You can provide a standard menu for your forms with the control. + + There is extensive support for this feature in Visual Studio. + + Also see [Walkthrough: Providing Standard Menu Items to a Form](walkthrough-providing-standard-menu-items-to-a-form.md). + +## Example + The following code example demonstrates how to use a control to create a form with a standard menu. Menu item selections are displayed in a control. + + [!code-csharp[System.Windows.Forms.ToolStrip.StandardMenu#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.StandardMenu#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [MenuStrip Control](menustrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-put-quotation-marks-in-a-string-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-put-quotation-marks-in-a-string-windows-forms.md new file mode 100644 index 0000000000..2b386bacb5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-put-quotation-marks-in-a-string-windows-forms.md @@ -0,0 +1,96 @@ +--- +title: "How to: Put Quotation Marks in a String" +description: Learn how to place quotation marks in a string of text. Also, learn to use the Quote field as a constant. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "quotation marks" + - "TextBox control [Windows Forms], displaying quotation marks" + - "quotation marks [Windows Forms], adding to strings in text boxes" +ms.assetid: 68bdc3f3-4177-4eab-99cd-cac17a82b515 +--- +# How to: Put Quotation Marks in a String (Windows Forms) +Sometimes you might want to place quotation marks (" ") in a string of text. For example: + + She said, "You deserve a treat!" + + As an alternative, you can also use the field as a constant. + +### To place quotation marks in a string in your code + +1. In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \\" as an embedded quotation mark. For example, to create the preceding string, use the following code. + + ```vb + Private Sub InsertQuote() + TextBox1.Text = "She said, ""You deserve a treat!"" " + End Sub + ``` + + ```csharp + private void InsertQuote(){ + textBox1.Text = "She said, \"You deserve a treat!\" "; + } + ``` + + ```cpp + private: + void InsertQuote() + { + textBox1->Text = "She said, \"You deserve a treat!\" "; + } + ``` + + -or- + +2. Insert the ASCII or Unicode character for a quotation mark. In Visual Basic, use the ASCII character (34). In Visual C#, use the Unicode character (\u0022). + + ```vb + Private Sub InsertAscii() + TextBox1.Text = "She said, " & Chr(34) & "You deserve a treat!" & Chr(34) + End Sub + ``` + + ```csharp + private void InsertAscii(){ + textBox1.Text = "She said, " + '\u0022' + "You deserve a treat!" + '\u0022'; + } + ``` + + > [!NOTE] + > In this example, you cannot use \u0022 because you cannot use a universal character name that designates a character in the basic character set. Otherwise, you produce C3851. For more information, see [Compiler Error C3851](/cpp/error-messages/compiler-errors-2/compiler-error-c3851). + + -or- + +3. You can also define a constant for the character, and use it where needed. + + ```vb + Const quote As String = """" + TextBox1.Text = "She said, " & quote & "You deserve a treat!" & quote + ``` + + ```csharp + const string quote = "\""; + textBox1.Text = "She said, " + quote + "You deserve a treat!"+ quote ; + ``` + + ```cpp + const String^ quote = "\""; + textBox1->Text = String::Concat("She said, ", + const_cast(quote), "You deserve a treat!", + const_cast(quote)); + ``` + +## See also + +- +- +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) +- [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) +- [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) +- [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) +- [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) +- [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-raise-change-notifications-using-the-bindingsource-resetitem-method.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-raise-change-notifications-using-the-bindingsource-resetitem-method.md new file mode 100644 index 0000000000..2d504fe552 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-raise-change-notifications-using-the-bindingsource-resetitem-method.md @@ -0,0 +1,37 @@ +--- +title: "How to: Raise Change Notifications Using the BindingSource ResetItem Method" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "change notifications [Windows Forms], raising" + - "data binding [Windows Forms], change notifications" + - "BindingSource component [Windows Forms], raising change notifications with" + - "data sources [Windows Forms], detecting changes" + - "change notifications" +ms.assetid: ab8b4096-37ff-4e30-aabc-de79a2f2e972 +--- +# How to: Raise Change Notifications Using the BindingSource ResetItem Method +Some data sources for your controls do not raise change notifications when items are changed, added, or deleted. With the component, you can bind to such data sources and raise a change notification from your code. + +## Example + This form demonstrates using a component to bind a list to a control. The list does not raise change notifications, so the method on the is called when an item in the list is changed. . + + [!code-cpp[System.Windows.Forms.DataConnector.ResetItem#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CPP/form1.cpp#1)] + [!code-csharp[System.Windows.Forms.DataConnector.ResetItem#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnector.ResetItem#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-reassign-existing-controls-to-a-different-parent.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-reassign-existing-controls-to-a-different-parent.md new file mode 100644 index 0000000000..4e8bbef6e1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-reassign-existing-controls-to-a-different-parent.md @@ -0,0 +1,40 @@ +--- +title: "How to: Reassign Existing Controls to a Different Parent" +ms.date: "03/30/2017" +helpviewer_keywords: + - "container controls [Windows Forms], Windows Forms" + - "layout [Windows Forms], resizing" + - "layout [Windows Forms], child controls" +ms.assetid: 5a5723ff-34e0-4b6f-a57b-be4ebe35cb34 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Reassign existing controls to a different parent + +You can assign controls that exist on your form to a new container control. + +1. In Visual Studio, drag three controls from the **Toolbox** onto the form. Position them near to each other, but leave them unaligned. + +2. In the **Toolbox**, click the control icon. (Do not drag the icon onto the form.) + +3. Move the mouse pointer close to the three controls. + + The pointer changes to a crosshair with the control icon attached. + +4. Click and hold the mouse button. + +5. Drag the mouse pointer to draw the outline of the control. + +6. Draw the outline around the three controls. + +7. Release the mouse button. + + The three controls are now inserted into the control. + +## See also + +- +- +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-remove-a-toolstripmenuitem-from-an-mdi-drop-down-menu-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-remove-a-toolstripmenuitem-from-an-mdi-drop-down-menu-windows-forms.md new file mode 100644 index 0000000000..aeaf7f950f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-remove-a-toolstripmenuitem-from-an-mdi-drop-down-menu-windows-forms.md @@ -0,0 +1,95 @@ +--- +title: "How to: Remove a ToolStripMenuItem from an MDI Drop-Down Menu" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "menu items [Windows Forms], removing from MDI drop-down menus" + - "MenuStrip control [Windows Forms], merging" + - "MenuStrip control [Windows Forms], removing" + - "MDI [Windows Forms], merging menu items" +ms.assetid: bdafe60d-82ee-45bc-97fe-eeefca6e54c1 +--- +# How to: Remove a ToolStripMenuItem from an MDI Drop-Down Menu (Windows Forms) +In some applications, the kind of a multiple-document interface (MDI) child window can be different from the MDI parent window. For example, the MDI parent might be a spreadsheet, and the MDI child might be a chart. In that case, you want to update the contents of the MDI parent's menu with the contents of the MDI child's menu as MDI child windows of different kinds are activated. + + The following procedure uses the , , , and properties to remove a menu item from the drop-down part of the MDI parent menu. Closing the MDI child window restores the removed menu items to the MDI parent menu. + +### To remove a MenuStrip from an MDI drop-down menu + +1. Create a form and set its property to `true`. + +2. Add a to `Form1` and set the property of the to `true`. + +3. Add a top-level menu item to the `Form1` and set its property to `&File`. + +4. Add three submenu items to the `&File` menu item and set their properties to `&Open`, `&Import from`, and `E&xit`. + +5. Add two submenu items to the `&Import from` submenu item and set their properties to `&Word` and `&Excel`. + +6. Add a form to the project, add a to the form, and set the property of the `Form2` to `true`. + +7. Add a top-level menu item to the `Form2` and set its property to `&File`. + +8. Add an `&Import from` submenu item to the `&File` menu of `Form2`, and add an `&Word` submenu item to the `&File` menu. + +9. Set the and properties of the `Form2` menu items as shown in the following table. + + |Form2 menu item|MergeAction value|MergeIndex value| + |---------------------|-----------------------|----------------------| + |File|MatchOnly|-1| + |Import from|MatchOnly|-1| + |Word|Remove|-1| + +10. In `Form1`, create an event handler for the event of the `&Open`. + +11. Within the event handler, insert code similar to the following code example to create and display new instances of `Form2` as MDI children of `Form1`: + + ```vb + Private Sub openToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles openToolStripMenuItem.Click + Dim NewMDIChild As New Form2() + 'Set the parent form of the child window. + NewMDIChild.MdiParent = Me + 'Display the new form. + NewMDIChild.Show() + End Sub + ``` + + ```csharp + private void openToolStripMenuItem_Click(object sender, EventArgs e) + { + Form2 newMDIChild = new Form2(); + // Set the parent form of the child window. + newMDIChild.MdiParent = this; + // Display the new form. + newMDIChild.Show(); + } + ``` + +12. Place code similar to the following code example in the `&Open` to register the event handler. + + ```vb + Private Sub openToolStripMenuItem_Click(sender As Object, e As _ + EventArgs) Handles openToolStripMenuItem.Click + ``` + + ```csharp + this.openToolStripMenuItem.Click += new _ + System.EventHandler(this.openToolStripMenuItem_Click); + ``` + +## Compiling the Code + This example requires: + +- Two controls named `Form1` and `Form2`. + +- A control on `Form1` named `menuStrip1`, and a control on `Form2` named `menuStrip2`. + +- References to the and assemblies. + +## See also + +- [How to: Create MDI Parent Forms](../advanced/how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](../advanced/how-to-create-mdi-child-forms.md) +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-remove-items-from-windows-forms-domainupdown-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-remove-items-from-windows-forms-domainupdown-controls.md new file mode 100644 index 0000000000..2248adaca7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-remove-items-from-windows-forms-domainupdown-controls.md @@ -0,0 +1,57 @@ +--- +title: Remove Items from DomainUpDown Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "DomainUpDown control [Windows Forms], removing items from" + - "spin button control [Windows Forms], removing items" +ms.assetid: e70f5cbc-b497-41a9-975a-344c00e56ed2 +--- +# How to: Remove Items from Windows Forms DomainUpDown Controls +You can remove items from the Windows Forms control by calling the or method of the class. The method removes a specific item, while the method removes an item by its position. + +### To remove an item + +- Use the method of the class to remove an item by name. + + ```vb + DomainUpDown1.Items.Remove("noodles") + ``` + + ```csharp + domainUpDown1.Items.Remove("noodles"); + ``` + + ```cpp + domainUpDown1->Items->Remove("noodles"); + ``` + + -or- + +- Use the method to remove an item by its position. + + ```vb + ' Removes the first item in the list. + DomainUpDown1.Items.RemoveAt(0) + ``` + + ```csharp + // Removes the first item in the list. + domainUpDown1.Items.RemoveAt(0); + ``` + + ```cpp + // Removes the first item in the list. + domainUpDown1->Items->RemoveAt(0); + ``` + +## See also + +- +- +- +- [DomainUpDown Control](domainupdown-control-windows-forms.md) +- [DomainUpDown Control Overview](domainupdown-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-render-a-visual-style-element.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-render-a-visual-style-element.md new file mode 100644 index 0000000000..a7cc9e612e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-render-a-visual-style-element.md @@ -0,0 +1,42 @@ +--- +title: "How to: Render a Visual Style Element" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "visual themes [Windows Forms], applying to elements of Windows Forms applications" + - "professional appearance [Windows Forms], applying to elements of Windows Forms applications" + - "visual styles [Windows Forms], rendering Windows Forms controls" +ms.assetid: a207781b-1baa-4ce9-b788-1e951bd4b5df +--- +# How to: Render a Visual Style Element +The namespace exposes objects that represent the Windows user interface (UI) elements supported by visual styles. This topic demonstrates how to use the class to render the that represents the **Log Off** and **Shut Down** buttons of the Start menu. + +### To render a visual style element + +1. Create a and set it to the element you want to draw. Note the use of the property and the method; the constructor will throw an exception if visual styles are disabled or an element is undefined. + + [!code-cpp[System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple#4](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/form1.cpp#4)] + [!code-csharp[System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/CS/form1.cs#4)] + [!code-vb[System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/VB/form1.vb#4)] + +2. Call the method to render the element that the currently represents. + + [!code-cpp[System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple#6](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/form1.cpp#6)] + [!code-csharp[System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple#6](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/CS/form1.cs#6)] + [!code-vb[System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple#6](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/VB/form1.vb#6)] + +## Compiling the Code + This example requires: + +- A custom control derived from the class. + +- A that hosts the custom control. + +- References to the , , , and namespaces. + +## See also + +- [Rendering Controls with Visual Styles](rendering-controls-with-visual-styles.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-resize-controls-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-resize-controls-on-windows-forms.md new file mode 100644 index 0000000000..0ad6e03de9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-resize-controls-on-windows-forms.md @@ -0,0 +1,39 @@ +--- +title: Resize Controls +ms.date: "03/30/2017" +f1_keywords: + - "Size.Height" + - "Size.Width" +helpviewer_keywords: + - "controls [Windows Forms], resizing" + - "size [Windows Forms], controls" + - "Windows Forms controls, size" +ms.assetid: d2dba441-a8c0-4705-b8e8-2e5d86d6e7ec +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Resize controls on Windows Forms + +You can resize individual controls, and you can resize multiple controls of the same or different kind, such as and controls. + +## To resize a control + +In Visual Studio, select the control to be resized and drag one of the eight sizing handles. + +> [!NOTE] +> Select the control and press the **arrow** keys while holding down the **Shift** key to resize the control one pixel at a time. Press the **down arrow** or **right arrow** keys while holding down the **Shift** and **Ctrl** keys to resize the control in large increments. + +## To resize multiple controls on a form + +1. In Visual Studio, hold down the **Ctrl** or **Shift** key and select the controls you want to resize. The size of the first control you select is used for the other controls. + +2. On the **Format** menu, choose **Make Same Size**, and select one of the four options. The first three commands change the dimensions of the controls to match the first-selected control. + +## See also + +- [Windows Forms Controls](index.md) +- [Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) +- [How to: Resize Windows Forms Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/37k2zkwx(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-clicks-in-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-clicks-in-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..4305bc74a3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-clicks-in-the-windows-forms-datagrid-control.md @@ -0,0 +1,140 @@ +--- +title: Respond to Clicks in DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Click event [Windows Forms], monitoring in DataGrid controls" + - "DataGrid control [Windows Forms], examples" + - "DataGrid control [Windows Forms], returning clicked cell value" + - "cells [Windows Forms], location in DataGrid" + - "examples [Windows Forms], DataGrid control" + - "DataGrid control [Windows Forms], click events" +ms.assetid: a0aa204b-8351-4d82-9933-ee21a5c9e409 +--- +# How to: Respond to Clicks in the Windows Forms DataGrid Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + After the Windows Forms is connected to a database, you can monitor which cell the user clicked. + +### To detect when the user of the DataGrid selects a different cell + +- In the event handler, write code to respond appropriately. + + ```vb + Private Sub myDataGrid_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myDataGrid.CurrentCellChanged + MessageBox.Show("Col is " & myDataGrid.CurrentCell.ColumnNumber _ + & ", Row is " & myDataGrid.CurrentCell.RowNumber _ + & ", Value is " & myDataGrid.Item(myDataGrid.CurrentCell)) + End Sub + ``` + + ```csharp + private void myDataGrid_CurrentCellChanged(object sender, + System.EventArgs e) + { + MessageBox.Show ("Col is " + myDataGrid.CurrentCell.ColumnNumber + + ", Row is " + myDataGrid.CurrentCell.RowNumber + + ", Value is " + myDataGrid[myDataGrid.CurrentCell] ); + } + ``` + + (Visual C#) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.myDataGrid.CurrentCellChanged += new + System.EventHandler(this.myDataGrid_CurrentCellChanged); + ``` + +### To determine which part of the DataGrid the user clicked + +- Call the method in an appropriate event handler, such as for the or event. + + The method returns a object that contains the row and column of a clicked area. + + ```vb + Private Sub myDataGrid_MouseDown(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles myDataGrid.MouseDown + Dim myGrid As DataGrid = CType(sender, DataGrid) + Dim hti As System.Windows.Forms.DataGrid.HitTestInfo + hti = myGrid.HitTest(e.X, e.Y) + Dim message As String = "You clicked " + + Select Case hti.Type + Case System.Windows.Forms.DataGrid.HitTestType.None + message &= "the background." + Case System.Windows.Forms.DataGrid.HitTestType.Cell + message &= "cell at row " & hti.Row & ", col " & hti.Column + Case System.Windows.Forms.DataGrid.HitTestType.ColumnHeader + message &= "the column header for column " & hti.Column + Case System.Windows.Forms.DataGrid.HitTestType.RowHeader + message &= "the row header for row " & hti.Row + Case System.Windows.Forms.DataGrid.HitTestType.ColumnResize + message &= "the column resizer for column " & hti.Column + Case System.Windows.Forms.DataGrid.HitTestType.RowResize + message &= "the row resizer for row " & hti.Row + Case System.Windows.Forms.DataGrid.HitTestType.Caption + message &= "the caption" + Case System.Windows.Forms.DataGrid.HitTestType.ParentRows + message &= "the parent row" + End Select + + Console.WriteLine(message) + End Sub + ``` + + ```csharp + private void myDataGrid_MouseDown(object sender, + System.Windows.Forms.MouseEventArgs e) + { + DataGrid myGrid = (DataGrid) sender; + System.Windows.Forms.DataGrid.HitTestInfo hti; + hti = myGrid.HitTest(e.X, e.Y); + string message = "You clicked "; + + switch (hti.Type) + { + case System.Windows.Forms.DataGrid.HitTestType.None : + message += "the background."; + break; + case System.Windows.Forms.DataGrid.HitTestType.Cell : + message += "cell at row " + hti.Row + ", col " + hti.Column; + break; + case System.Windows.Forms.DataGrid.HitTestType.ColumnHeader : + message += "the column header for column " + hti.Column; + break; + case System.Windows.Forms.DataGrid.HitTestType.RowHeader : + message += "the row header for row " + hti.Row; + break; + case System.Windows.Forms.DataGrid.HitTestType.ColumnResize : + message += "the column resizer for column " + hti.Column; + break; + case System.Windows.Forms.DataGrid.HitTestType.RowResize : + message += "the row resizer for row " + hti.Row; + break; + case System.Windows.Forms.DataGrid.HitTestType.Caption : + message += "the caption"; + break; + case System.Windows.Forms.DataGrid.HitTestType.ParentRows : + message += "the parent row"; + break; + } + + Console.WriteLine(message); + } + ``` + + (Visual C#) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.myDataGrid.MouseDown += new + System.Windows.Forms.MouseEventHandler + (this.myDataGrid_MouseDown); + ``` + +## See also + +- [DataGrid Control](datagrid-control-windows-forms.md) +- [How to: Change Displayed Data at Run Time in the Windows Forms DataGrid Control](change-displayed-data-at-run-time-wf-datagrid-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-windows-forms-button-clicks.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-windows-forms-button-clicks.md new file mode 100644 index 0000000000..1ffbdb7e77 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-windows-forms-button-clicks.md @@ -0,0 +1,57 @@ +--- +title: Respond to Button Clicks +description: Learn how to respond to Windows Forms button clicks. The most basic use of a Windows Forms Button control is to run some code when the button is clicked. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "buttons [Windows Forms], responding to Click events" + - "events [Windows Forms], Click events" + - "Click event [Windows Forms], Button control" + - "MouseDown event" + - "Button control [Windows Forms], click response" + - "double-clicks" + - "examples [Windows Forms], controls" + - "Click event [Windows Forms], responding to" +ms.assetid: 7a4951bd-369c-4662-b246-28ad83eda484 +--- +# How to: Respond to Windows Forms Button Clicks +The most basic use of a Windows Forms control is to run some code when the button is clicked. + + Clicking a control also generates a number of other events, such as the , , and events. If you intend to attach event handlers for these related events, be sure that their actions do not conflict. For example, if clicking the button clears information that the user has typed in a text box, pausing the mouse pointer over the button should not display a tool tip with that now-nonexistent information. + + If the user attempts to double-click the control, each click will be processed separately; that is, the control does not support the double-click event. + +### To respond to a button click + +- In the button's `Click` write the code to run. `Button1_Click` must be bound to the control. For more information, see [How to: Create Event Handlers at Run Time for Windows Forms](../how-to-create-event-handlers-at-run-time-for-windows-forms.md). + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + MessageBox.Show("Button1 was clicked") + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + MessageBox.Show("button1 was clicked"); + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + MessageBox::Show("button1 was clicked"); + } + ``` + +## See also + +- [Button Control Overview](button-control-overview-windows-forms.md) +- [Ways to Select a Windows Forms Button Control](ways-to-select-a-windows-forms-button-control.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-windows-forms-checkbox-clicks.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-windows-forms-checkbox-clicks.md new file mode 100644 index 0000000000..9bc06c23d2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-respond-to-windows-forms-checkbox-clicks.md @@ -0,0 +1,138 @@ +--- +title: Respond to CheckBox Clicks +description: Learn how to program your Windows Forms application to perform some action depending upon the state of the check box. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Click event [Windows Forms], CheckBox control" + - "CheckBox control [Windows Forms], Click events" + - "events [Windows Forms], Click events" + - "double-clicks" + - "check boxes [Windows Forms], responding to events" +ms.assetid: c39f901e-8899-43b6-aa31-939cbf7089fb +--- +# How to: Respond to Windows Forms CheckBox Clicks +Whenever a user clicks a Windows Forms control, the event occurs. You can program your application to perform some action depending upon the state of the check box. + +### To respond to CheckBox clicks + +1. In the event handler, use the property to determine the control's state, and perform any necessary action. + + ```vb + Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click + ' The CheckBox control's Text property is changed each time the + ' control is clicked, indicating a checked or unchecked state. + If CheckBox1.Checked = True Then + CheckBox1.Text = "Checked" + Else + CheckBox1.Text = "Unchecked" + End If + End Sub + ``` + + ```csharp + private void checkBox1_Click(object sender, System.EventArgs e) + { + // The CheckBox control's Text property is changed each time the + // control is clicked, indicating a checked or unchecked state. + if (checkBox1.Checked) + { + checkBox1.Text = "Checked"; + } + else + { + checkBox1.Text = "Unchecked"; + } + } + ``` + + ```cpp + private: + void checkBox1_CheckedChanged(System::Object ^ sender, + System::EventArgs ^ e) + { + if (checkBox1->Checked) + { + checkBox1->Text = "Checked"; + } + else + { + checkBox1->Text = "Unchecked"; + } + } + ``` + + > [!NOTE] + > If the user attempts to double-click the control, each click will be processed separately; that is, the control does not support the double-click event. + + > [!NOTE] + > When the property is `true` (the default), the is automatically selected or cleared when it is clicked. Otherwise, you must manually set the property when the event occurs. + + You can also use the control to determine a course of action. + +### To determine a course of action when a check box is clicked + +1. Use a case statement to query the value of the property to determine a course of action. When the property is set to `true`, the property may return three possible values, which represent the box being checked, the box being unchecked, or a third indeterminate state in which the box is displayed with a dimmed appearance to indicate the option is unavailable. + + ```vb + Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click + Select Case CheckBox1.CheckState + Case CheckState.Checked + ' Code for checked state. + Case CheckState.Unchecked + ' Code for unchecked state. + Case CheckState.Indeterminate + ' Code for indeterminate state. + End Select + End Sub + ``` + + ```csharp + private void checkBox1_Click(object sender, System.EventArgs e) + { + switch(checkBox1.CheckState) + { + case CheckState.Checked: + // Code for checked state. + break; + case CheckState.Unchecked: + // Code for unchecked state. + break; + case CheckState.Indeterminate: + // Code for indeterminate state. + break; + } + } + ``` + + ```cpp + private: + void checkBox1_CheckedChanged(System::Object ^ sender, + System::EventArgs ^ e) + { + switch(checkBox1->CheckState) { + case CheckState::Checked: + // Code for checked state. + break; + case CheckState::Unchecked: + // Code for unchecked state. + break; + case CheckState::Indeterminate: + // Code for indeterminate state. + break; + } + } + ``` + + > [!NOTE] + > When the property is set to `true`, the property returns `true` for both and . + +## See also + +- +- [CheckBox Control Overview](checkbox-control-overview-windows-forms.md) +- [How to: Set Options with Windows Forms CheckBox Controls](how-to-set-options-with-windows-forms-checkbox-controls.md) +- [CheckBox Control](checkbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-run-an-operation-in-the-background.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-run-an-operation-in-the-background.md new file mode 100644 index 0000000000..23b63f98e4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-run-an-operation-in-the-background.md @@ -0,0 +1,41 @@ +--- +title: "How to: Run an Operation in the Background" +description: Learn how to use the BackgroundWorker class to run a time-consuming Windows Forms operation in the background. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "background tasks" + - "forms [Windows Forms], multithreading" + - "forms [Windows Forms], background operations" + - "background threads" + - "BackgroundWorker class [Windows Forms], examples" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: 5b56e2aa-dc05-444f-930c-2d7b23f9ad5b +--- +# How to: Run an Operation in the Background +If you have an operation that will take a long time to complete, and you do not want to cause delays in your user interface, you can use the class to run the operation on another thread. + + The following code example shows how to run a time-consuming operation in the background. The form has **Start** and **Cancel** buttons. Click the **Start** button to run an asynchronous operation. Click the **Cancel** button to stop a running asynchronous operation. The outcome of each operation is displayed in a . + + There is extensive support for this task in Visual Studio. + + Also see [Walkthrough: Running an Operation in the Background](walkthrough-running-an-operation-in-the-background.md). + +## Example + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#1)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md) +- [BackgroundWorker Component](backgroundworker-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-save-files-using-the-savefiledialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-save-files-using-the-savefiledialog-component.md new file mode 100644 index 0000000000..ce3fe8fdd5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-save-files-using-the-savefiledialog-component.md @@ -0,0 +1,179 @@ +--- +title: "How to: Save Files Using the SaveFileDialog Component" +description: Learn how to use the SaveFileDialog component to browse the file system and select files to be saved. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "saving files" + - "SaveFileDialog component [Windows Forms], saving files" + - "files [Windows Forms], saving" + - "OpenFile method [Windows Forms], saving files with SaveFileDialog component" +ms.assetid: 02e8f409-b83f-4707-babb-e71f6b223d90 +--- +# How to: Save Files Using the SaveFileDialog Component + +The component allows users to browse the file system and select files to be saved. The dialog box returns the path and name of the file the user has selected in the dialog box. However, you must write the code to actually write the files to disk. + +### To save a file using the SaveFileDialog component + +- Display the **Save File** dialog box and call a method to save the file selected by the user. + + Use the component's method to save the file. This method gives you a object you can write to. + + The example below uses the property to get the name of the file, and the method to save the file. The method gives you a stream to write the file to. + + In the example below, there is a control with an image assigned to it. When you click the button, a component is instantiated with a filter that allows files of type .gif, .jpeg, and .bmp. If a file of this type is selected in the Save File dialog box, the button's image is saved. + + > [!IMPORTANT] + > To get or set the property, your assembly requires a privilege level granted by the class. If you are running in a partial-trust context, the process might throw an exception due to insufficient privileges. For more information, see [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics). + + The example assumes your form has a control with its property set to a file of type .gif, .jpeg, or .bmp. + + > [!NOTE] + > The class's property (which, due to inheritance, is part of the class) uses a one-based index. This is important if you are writing code to save data in a specific format (for example, saving a file in plain text versus binary format). This property is featured in the example below. + + ```vb + Private Sub Button2_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Button2.Click + ' Displays a SaveFileDialog so the user can save the Image + ' assigned to Button2. + Dim saveFileDialog1 As New SaveFileDialog() + saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif" + saveFileDialog1.Title = "Save an Image File" + saveFileDialog1.ShowDialog() + + ' If the file name is not an empty string open it for saving. + If saveFileDialog1.FileName <> "" Then + ' Saves the Image via a FileStream created by the OpenFile method. + Dim fs As System.IO.FileStream = Ctype _ + (saveFileDialog1.OpenFile(), System.IO.FileStream) + ' Saves the Image in the appropriate ImageFormat based upon the + ' file type selected in the dialog box. + ' NOTE that the FilterIndex property is one-based. + Select Case saveFileDialog1.FilterIndex + Case 1 + Me.button2.Image.Save(fs, _ + System.Drawing.Imaging.ImageFormat.Jpeg) + + Case 2 + Me.button2.Image.Save(fs, _ + System.Drawing.Imaging.ImageFormat.Bmp) + + Case 3 + Me.button2.Image.Save(fs, _ + System.Drawing.Imaging.ImageFormat.Gif) + End Select + + fs.Close() + End If + End Sub + ``` + + ```csharp + private void button2_Click(object sender, System.EventArgs e) + { + // Displays a SaveFileDialog so the user can save the Image + // assigned to Button2. + SaveFileDialog saveFileDialog1 = new SaveFileDialog(); + saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"; + saveFileDialog1.Title = "Save an Image File"; + saveFileDialog1.ShowDialog(); + + // If the file name is not an empty string open it for saving. + if(saveFileDialog1.FileName != "") + { + // Saves the Image via a FileStream created by the OpenFile method. + System.IO.FileStream fs = + (System.IO.FileStream)saveFileDialog1.OpenFile(); + // Saves the Image in the appropriate ImageFormat based upon the + // File type selected in the dialog box. + // NOTE that the FilterIndex property is one-based. + switch(saveFileDialog1.FilterIndex) + { + case 1 : + this.button2.Image.Save(fs, + System.Drawing.Imaging.ImageFormat.Jpeg); + break; + + case 2 : + this.button2.Image.Save(fs, + System.Drawing.Imaging.ImageFormat.Bmp); + break; + + case 3 : + this.button2.Image.Save(fs, + System.Drawing.Imaging.ImageFormat.Gif); + break; + } + + fs.Close(); + } + } + ``` + + ```cpp + private: + System::Void button2_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + // Displays a SaveFileDialog so the user can save the Image + // assigned to Button2. + SaveFileDialog ^ saveFileDialog1 = new SaveFileDialog(); + saveFileDialog1->Filter = + "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"; + saveFileDialog1->Title = "Save an Image File"; + saveFileDialog1->ShowDialog(); + // If the file name is not an empty string, open it for saving. + if(saveFileDialog1->FileName != "") + { + // Saves the Image through a FileStream created by + // the OpenFile method. + System::IO::FileStream ^ fs = + safe_cast\( + saveFileDialog1->OpenFile()); + // Saves the Image in the appropriate ImageFormat based on + // the file type selected in the dialog box. + // Note that the FilterIndex property is one based. + switch(saveFileDialog1->FilterIndex) + { + case 1 : + this->button2->Image->Save(fs, + System::Drawing::Imaging::ImageFormat::Jpeg); + break; + case 2 : + this->button2->Image->Save(fs, + System::Drawing::Imaging::ImageFormat::Bmp); + break; + case 3 : + this->button2->Image->Save(fs, + System::Drawing::Imaging::ImageFormat::Gif); + break; + } + fs->Close(); + } + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.button2.Click += new System.EventHandler(this.button2_Click); + ``` + + ```cpp + this->button2->Click += gcnew + System::EventHandler(this, &Form1::button2_Click); + ``` + + For more information about writing file streams, see and . + + > [!NOTE] + > Certain controls, such as the control, have the ability to save files. + +## See also + +- +- [SaveFileDialog Component](savefiledialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-save-files-with-the-windows-forms-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-save-files-with-the-windows-forms-richtextbox-control.md new file mode 100644 index 0000000000..87f4d326e2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-save-files-with-the-windows-forms-richtextbox-control.md @@ -0,0 +1,90 @@ +--- +title: Save Files with RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "saving files" + - "RTF files [Windows Forms], saving in RichTextBox control" + - "examples [Windows Forms], text boxes" + - "saving files [Windows Forms], RichTextBox control" + - "files [Windows Forms], saving with RichTextBox control" + - "RichTextBox control [Windows Forms], saving files" + - ".rtf files [Windows Forms], saving in RichTextBox control" + - "text files [Windows Forms], saving from RichTextBox control" +ms.assetid: 4a58ec19-84d1-4383-9110-298c06adcfca +--- +# How to: Save Files with the Windows Forms RichTextBox Control + +The Windows Forms control can write the information it displays in one of several formats: + +- Plain text + +- Unicode plain text + +- Rich-Text Format (RTF) + +- RTF with spaces in place of OLE objects + +- Plain text with a textual representation of OLE objects + +To save a file, call the method. You can also use the **SaveFile** method to save data to a stream. For more information, see . + +### To save the contents of the control to a file + +1. Determine the path of the file to be saved. + + To do this in a real-world application, you would typically use the component. For an overview, see [SaveFileDialog Component Overview](savefiledialog-component-overview-windows-forms.md). + +2. Call the method of the control, specifying the file to save and optionally a file type. If you call the method with a file name as its only argument, the file will be saved as RTF. To specify another file type, call the method with a value of the enumeration as its second argument. + + In the example below, the path set for the location of the rich-text file is the **My Documents** folder. This location is used because you can assume that most computers running the Windows operating system will include this folder. Choosing this location also allows users with minimal system access levels to safely run the application. The example below assumes a form with a control already added. + + ```vb + Public Sub SaveFile() + ' You should replace the bold file name in the + ' sample below with a file name of your own choosing. + RichTextBox1.SaveFile(System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Testdoc.rtf", _ + RichTextBoxStreamType.RichNoOleObjs) + End Sub + ``` + + ```csharp + public void SaveFile() + { + // You should replace the bold file name in the + // sample below with a file name of your own choosing. + // Note the escape character used (@) when specifying the path. + richTextBox1.SaveFile(System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Testdoc.rtf", + RichTextBoxStreamType.RichNoOleObjs); + } + ``` + + ```cpp + public: + void SaveFile() + { + // You should replace the bold file name in the + // sample below with a file name of your own choosing. + richTextBox1->SaveFile(String::Concat + (System::Environment::GetFolderPath + (System::Environment::SpecialFolder::Personal), + "\\Testdoc.rtf"), RichTextBoxStreamType::RichNoOleObjs); + } + ``` + + > [!IMPORTANT] + > This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create access for the folder. Permissions are set using access control lists. If the file already exists, the application needs only Write access, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create access for a folder. Also, it is more secure to write data to user folders than to the root folder or the Program Files folder. + +## See also + +- +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md new file mode 100644 index 0000000000..22a684f1a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md @@ -0,0 +1,76 @@ +--- +title: Select a Range of Dates in MonthCalendar Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "dates [Windows Forms], selecting range in calendar controls" + - "examples [Windows Forms], calendar controls" + - "calendars [Windows Forms], selecting date range" + - "MonthCalendar control [Windows Forms], selecting date range" +ms.assetid: 95d9ab95-b0f8-4c19-9f63-b5cd4593a5d0 +--- +# How to: Select a Range of Dates in the Windows Forms MonthCalendar Control +An important feature of the Windows Forms control is that the user can select a range of dates. This feature is an improvement over the date-selection feature of the control, which only enables the user to select a single date/time value. You can set a range of dates or get a selection range set by the user by using properties of the control. The following code example demonstrates how to set a selection range. + +### To select a range of dates + +1. Create objects that represent the first and last dates in a range. + + ```vb + Dim projectStart As Date = New DateTime(2001, 2, 13) + Dim projectEnd As Date = New DateTime(2001, 2, 28) + ``` + + ```csharp + DateTime projectStart = new DateTime(2001, 2, 13); + DateTime projectEnd = new DateTime(2001, 2, 28); + ``` + + ```cpp + DateTime projectStart = DateTime(2001, 2, 13); + DateTime projectEnd = DateTime(2001, 2, 28); + ``` + +2. Set the property. + + ```vb + MonthCalendar1.SelectionRange = New SelectionRange(projectStart, projectEnd) + ``` + + ```csharp + monthCalendar1.SelectionRange = new SelectionRange(projectStart, projectEnd); + ``` + + ```cpp + monthCalendar1->SelectionRange = gcnew + SelectionRange(projectStart, projectEnd); + ``` + + –or– + + Set the and properties. + + ```vb + MonthCalendar1.SelectionStart = projectStart + MonthCalendar1.SelectionEnd = projectEnd + ``` + + ```csharp + monthCalendar1.SelectionStart = projectStart; + monthCalendar1.SelectionEnd = projectEnd; + ``` + + ```cpp + monthCalendar1->SelectionStart = projectStart; + monthCalendar1->SelectionEnd = projectEnd; + ``` + +## See also + +- [MonthCalendar Control](monthcalendar-control-windows-forms.md) +- [How to: Change the Windows Forms MonthCalendar Control's Appearance](how-to-change-monthcalendar-control-appearance.md) +- [How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control](display-specific-days-in-bold-with-wf-monthcalendar-control.md) +- [How to: Display More than One Month in the Windows Forms MonthCalendar Control](display-more-than-one-month-wf-monthcalendar-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-select-an-item-in-the-windows-forms-listview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-select-an-item-in-the-windows-forms-listview-control.md new file mode 100644 index 0000000000..05335e0baa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-select-an-item-in-the-windows-forms-listview-control.md @@ -0,0 +1,31 @@ +--- +title: Select an Item in ListView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "lists [Windows Forms], selecting items" + - "ListView control [Windows Forms], selecting items" + - "selection [Windows Forms], in list views" + - "list views [Windows Forms], selecting items" +ms.assetid: ddea918e-1ddf-47f4-bd09-1e9b4c9d0c39 +--- +# How to: Select an Item in the Windows Forms ListView Control +This example demonstrates how to programmatically select an item in a Windows Forms control. Selecting an item programmatically does not automatically change the focus to the control. For this reason, you will typically also want to set the item as focused when selecting an item. + +## Example + [!code-csharp[System.Windows.Forms.ListView.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.ListView.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- A control named `listView1` that contains at least one item. + +- References to the and namespaces. + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-select-text-in-the-windows-forms-textbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-select-text-in-the-windows-forms-textbox-control.md new file mode 100644 index 0000000000..098bdf22ca --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-select-text-in-the-windows-forms-textbox-control.md @@ -0,0 +1,74 @@ +--- +title: Select Text in TextBox Control +description: Learn how to select text programmatically in the Windows Forms TextBox control. Also learn how to visually alert the reader of the found string's position. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "TextBox control [Windows Forms], selecting text programmatically" + - "text boxes [Windows Forms], selecting text programmatically" + - "text [Windows Forms], selecting in text boxes programmatically" +ms.assetid: 8c591546-6a01-45c7-8e03-f78431f903b1 +--- +# How to: Select Text in the Windows Forms TextBox Control +You can select text programmatically in the Windows Forms control. For example, if you create a function that searches text for a particular string, you can select the text to visually alert the reader of the found string's position. + +### To select text programmatically + +1. Set the property to the beginning of the text you want to select. + + The property is a number that indicates the insertion point within the string of text, with 0 being the left-most position. If the property is set to a value equal to or greater than the number of characters in the text box, the insertion point is placed after the last character. + +2. Set the property to the length of the text you want to select. + + The property is a numeric value that sets the width of the insertion point. Setting the to a number greater than 0 causes that number of characters to be selected, starting from the current insertion point. + +3. (Optional) Access the selected text through the property. + + The code below selects the contents of a text box when the control's event occurs. This example checks if the text box has a value for the property that is not `null` or an empty string. When the text box receives the focus, the current text in the text box is selected. The `TextBox1_Enter` event handler must be bound to the control; for more information, see [How to: Create Event Handlers at Run Time for Windows Forms](../how-to-create-event-handlers-at-run-time-for-windows-forms.md). + + To test this example, press the Tab key until the text box has the focus. If you click in the text box, the text is unselected. + + ```vb + Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Enter + If (Not String.IsNullOrEmpty(TextBox1.Text)) Then + TextBox1.SelectionStart = 0 + TextBox1.SelectionLength = TextBox1.Text.Length + End If + End Sub + ``` + + ```csharp + private void textBox1_Enter(object sender, System.EventArgs e){ + if (!String.IsNullOrEmpty(textBox1.Text)) + { + textBox1.SelectionStart = 0; + textBox1.SelectionLength = textBox1.Text.Length; + } + } + ``` + + ```cpp + private: + void textBox1_Enter(System::Object ^ sender, + System::EventArgs ^ e) { + if (!System::String::IsNullOrEmpty(textBox1->Text)) + { + textBox1->SelectionStart = 0; + textBox1->SelectionLength = textBox1->Text->Length; + } + } + ``` + +## See also + +- +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) +- [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) +- [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) +- [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) +- [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) +- [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..3459a55e60 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md @@ -0,0 +1,49 @@ +--- +title: Set Alternating Row Styles for DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], row styles" + - "data grids [Windows Forms], row styles" + - "rows [Windows Forms], data grids" +ms.assetid: 699ef759-458c-426d-ac87-7c7e71b018ae +--- +# How to: Set Alternating Row Styles for the Windows Forms DataGridView Control +Tabular data is often presented to users in a ledger-like format where alternating rows have different background colors. This format makes it easier for users to tell which cells are in each row, especially with wide tables that have many columns. + + With the control, you can specify complete style information for alternating rows. This enables you use style characteristics like foreground color and font, in addition to background color, to differentiate alternating rows. + + There is support for this task in Visual Studio. Also see [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer](set-alternating-row-styles-for-the-datagrid-using-the-designer.md). + +### To set alternating row styles programmatically + +- Set the properties of the objects returned by the and properties of the . + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#068](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#068)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#068](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#068)] + + > [!NOTE] + > The styles specified using the and properties override the styles specified on the column and level, but are overridden by the styles set on the individual row and cell level. For more information, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the , , and assemblies. + +## Robust Programming + For maximum scalability, you should share objects across multiple rows, columns, or cells that use the same styles, rather than setting the style properties for each element separately. For more information, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) +- [How to: Set Font and Color Styles in the Windows Forms DataGridView Control](how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md new file mode 100644 index 0000000000..f46e916bb6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md @@ -0,0 +1,72 @@ +--- +title: Set and Return Dates with DateTimePicker Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "dates [Windows Forms], setting in DateTimePicker" + - "DateTimePicker control [Windows Forms], setting and returning dates" + - "examples [Windows Forms], DateTimePicker control" +ms.assetid: a8a48d68-e4b5-426e-9764-51230fc9acd2 +--- +# How to: Set and Return Dates with the Windows Forms DateTimePicker Control +The currently selected date or time in the Windows Forms control is determined by the property. You can set the property before the control is displayed (for example, at design time or in the form's event) to determine which date will be initially selected in the control. By default, the control's is set to the current date. If you change the control's in code, the control is automatically updated on the form to reflect the new setting. + + The property returns a structure as its value. There are several properties of the structure that return specific information about the displayed date. These properties can only be used to return a value; do not use them to set a value. + +- For date values, the , , and properties return integer values for those time units of the selected date. The property returns a value indicating the selected day of the week (possible values are listed in the enumeration). + +- For time values, the , , , and properties return integer values for those time units. To configure the control to display times, see [How to: Display Time with the DateTimePicker Control](how-to-display-time-with-the-datetimepicker-control.md). + +### To set the date and time value of the control + +- Set the property to a date or time value. + + ```vb + DateTimePicker1.Value = New DateTime(2001, 10, 20) + ``` + + ```csharp + dateTimePicker1.Value = new DateTime(2001, 10, 20); + ``` + + ```cpp + dateTimePicker1->Value = DateTime(2001, 10, 20); + ``` + +### To return the date and time value + +- Call the property to return the entire value as formatted in the control, or call the appropriate method of the property to return a part of the value. Use to convert the information into a string that can be displayed to the user. + + ```vb + MessageBox.Show("The selected value is ", DateTimePicker1.Text) + MessageBox.Show("The day of the week is ", + DateTimePicker1.Value.DayOfWeek.ToString) + MessageBox.Show("Millisecond is: ", + DateTimePicker1.Value.Millisecond.ToString) + ``` + + ```csharp + MessageBox.Show ("The selected value is " + + dateTimePicker1.Text); + MessageBox.Show ("The day of the week is " + + dateTimePicker1.Value.DayOfWeek.ToString()); + MessageBox.Show("Millisecond is: " + + dateTimePicker1.Value.Millisecond.ToString()); + ``` + + ```cpp + MessageBox::Show (String::Concat("The selected value is ", + dateTimePicker1->Text)); + MessageBox::Show (String::Concat("The day of the week is ", + dateTimePicker1->Value.DayOfWeek.ToString())); + MessageBox::Show(String::Concat("Millisecond is: ", + dateTimePicker1->Value.Millisecond.ToString())); + ``` + +## See also + +- [DateTimePicker Control](datetimepicker-control-windows-forms.md) +- [How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control](display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..c5204d516a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md @@ -0,0 +1,58 @@ +--- +title: Set Default Cell Styles for DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], cell styles" + - "cells [Windows Forms], styles" + - "data grids [Windows Forms], cell styles" +ms.assetid: 1aaaca43-5340-447e-99c0-9177d9776aa1 +--- +# How to: Set Default Cell Styles for the Windows Forms DataGridView Control +With the control, you can specify default cell styles for the entire control and for specific columns and rows. These defaults filter down from the control level to the column level, then to the row level, then to the cell level. If a particular property is not set at the cell level, the default property setting at the row level is used. If the property is also not set at the row level, the default column setting is used. Finally, if the property is also not set at the column level, the default setting is used. With this setting, you can avoid having to duplicate the property settings at multiple levels. At each level, simply specify the styles that differ from the levels above it. For more information, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + + There is extensive support for this task in Visual Studio. Also see [How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer](default-cell-styles-datagridview.md). + +### To set the default cell styles programmatically + +1. Set the properties of the retrieved through the property. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#141](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#141)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#141](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#141)] + +2. Create and initialize new objects for use by multiple rows and columns. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#142](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#142)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#142](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#142)] + +3. Set the `DefaultCellStyle` property of specific rows and columns. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#143](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#143)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#143](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#143)] + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#140](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#140)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#140](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#140)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the , , and assemblies. + +## Robust Programming + To achieve maximum scalability when you work with very large data sets, you should share objects across multiple rows, columns, or cells that use the same styles, rather than set the style properties for individual elements separately. Additionally, you should create shared rows and access them by using the property. For more information, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) +- [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control](how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..4a19e0d811 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,61 @@ +--- +title: Set Font and Color Styles in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], cell customization" + - "data grids [Windows Forms], customizing cells" + - "data grids [Windows Forms], font styles" + - "data grids [Windows Forms], color styles" +ms.assetid: 588f2c57-d963-41b1-9c1d-d02d71818113 +--- +# How to: Set Font and Color Styles in the Windows Forms DataGridView Control +You can specify the visual appearance of cells within a control by setting properties of the class. You can retrieve instances of this class from various properties of the class and its companion classes, or you can instantiate objects for assignment to these properties. + + The following procedures demonstrate basic customization of cell appearance using the property. Every cell in the control inherits the styles specified through this property unless they are overridden at the column, row, or cell level. For an example of style inheritance, see [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md). For information about additional uses of the class, see the topics listed in the See Also section. + + There is extensive support for this task in Visual Studio. Also see [How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer](default-cell-styles-datagridview.md). + +### To specify the font used by DataGridView cells + +- Set the property of a . The following code example uses the property to set the font for the entire control. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#101](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#101)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#101](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#101)] + +### To specify the foreground and background colors of DataGridView cells + +- Set the and properties of a . The following code example uses the property to set these styles for the entire control. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#102](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#102)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#102](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#102)] + +### To specify the foreground and background colors of selected DataGridView cells + +- Set the and properties of a . The following code example uses the property to set these styles for the entire control. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#103](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#103)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#103](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#103)] + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#100)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#100)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the , , and assemblies. + +## Robust Programming + For maximum scalability, you should share objects across multiple rows, columns, or cells that use the same styles, rather than setting the style properties for each element separately. For more information, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-font-attributes-for-the-windows-forms-richtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-font-attributes-for-the-windows-forms-richtextbox-control.md new file mode 100644 index 0000000000..ebebd45bc6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-font-attributes-for-the-windows-forms-richtextbox-control.md @@ -0,0 +1,54 @@ +--- +title: Set Font Attributes for RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - ".rtf files [Windows Forms], formatting in RichTextBox control" + - "fonts [Windows Forms], changing attributes in RichTextBox control" + - "RTF files [Windows Forms], formatting in RichTextBox control" + - "RichTextBox control [Windows Forms], setting font attributes" + - "text [Windows Forms]" + - "text boxes [Windows Forms], formatting text" + - "formatting [Windows Forms]" +ms.assetid: 2bc23ddb-0529-4489-a1a2-ad253cb43f9a +--- +# How to: Set Font Attributes for the Windows Forms RichTextBox Control +The Windows Forms control has numerous options for formatting the text it displays. You can make the selected characters bold, underlined, or italic, using the property. You can also use this property to change the size and typeface of the selected characters. The property enables you to change the selected characters' color. + +### To change the appearance of characters + +1. Set the property to an appropriate font. + + To enable users to set the font family, size, and typeface in an application, you would typically use the component. For an overview, see [FontDialog Component Overview](fontdialog-component-overview-windows-forms.md). + +2. Set the property to an appropriate color. + + To enable users to set the color in an application, you would typically use the component. For an overview, see [ColorDialog Component Overview](colordialog-component-overview-windows-forms.md). + + ```vb + RichTextBox1.SelectionFont = New Font("Tahoma", 12, FontStyle.Bold) + RichTextBox1.SelectionColor = System.Drawing.Color.Red + ``` + + ```csharp + richTextBox1.SelectionFont = new Font("Tahoma", 12, FontStyle.Bold); + richTextBox1.SelectionColor = System.Drawing.Color.Red; + ``` + + ```cpp + richTextBox1->SelectionFont = + gcnew System::Drawing::Font("Tahoma", 12, FontStyle::Bold); + richTextBox1->SelectionColor = System::Drawing::Color::Red; + ``` + + > [!NOTE] + > These properties only affect selected text, or, if no text is selected, the text that is typed at the current location of the insertion point. For information on selecting text programmatically, see . + +## See also + +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-grid-options-for-all-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-grid-options-for-all-windows-forms.md new file mode 100644 index 0000000000..da15863958 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-grid-options-for-all-windows-forms.md @@ -0,0 +1,29 @@ +--- +title: Set Grid Options +ms.date: "03/30/2017" +helpviewer_keywords: + - "snap to grid [Windows Forms], Windows Forms Designer" + - "grids [Windows Forms], options in Windows Forms" + - "snaplines [Windows Forms], Windows Forms Designer" + - "Windows Forms, grid options in designer" + - "Windows Forms Designer" +ms.assetid: 36967466-1dfd-4fae-a7f1-7bf2cbc94048 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Set grid options for all Windows Forms + +As you become used to working in the Visual Studio development environment, you can set preferences for all the forms and projects you work with in the Windows Forms Designer. + +## Set global Windows Forms options + +1. In Visual Studio, from the **Tools** menu, select **Options**. + +2. In the left pane of the **Options** dialog box, click **Windows Forms Designer**. + + In the right pane, under the **Layout Settings** heading, you can set the default grid settings for all the new forms you create. These settings include the grid size, whether controls snap to it, and whether it is on by default. In addition, you can select between **SnapToGrid** and **SnapLines** layout modes. For more information on snaplines, see [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md). + +## See also + +- [Options: Windows Forms Designer](/visualstudio/ide/reference/options-windows-forms-designer) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-icons-for-the-windows-forms-treeview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-icons-for-the-windows-forms-treeview-control.md new file mode 100644 index 0000000000..861e96ea75 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-icons-for-the-windows-forms-treeview-control.md @@ -0,0 +1,71 @@ +--- +title: Set Icons for TreeView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], TreeView control" + - "TreeView control [Windows Forms], node icons" + - "ImageList component [Windows Forms], adding images" + - "icons [Windows Forms], setting for TreeView control" + - "tree nodes in TreeView control [Windows Forms], icons" +ms.assetid: c14ddcc0-e5a6-4c21-a2d5-6799fd491781 +--- +# How to: Set Icons for the Windows Forms TreeView Control +The Windows Forms control can display icons next to each node. The icons are positioned to the immediate left of the node text. To display these icons, you must associate the tree view with an control. For more information about image lists, see [ImageList Component](imagelist-component-windows-forms.md) and [How to: Add or Remove Images with the Windows Forms ImageList Component](how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md). + +> [!NOTE] +> A bug in Microsoft .NET Framework version 1.1 prevents images from appearing on nodes when your application calls . To work around this bug, call in your `Main` method immediately after calling . This bug is fixed in .NET Framework 2.0. + +### To display images in a tree view + +1. Set the control's property to the existing control you wish to use. + + These properties can be set in the designer with the Properties window, or in code. + + ```vb + TreeView1.ImageList = ImageList1 + ``` + + ```csharp + treeView1.ImageList = imageList1; + ``` + + ```cpp + treeView1->ImageList = imageList1; + ``` + +2. Set the node's and properties. The property determines the image displayed for the node's normal and expanded states, and the property determines the image displayed for the node's selected state. + + These properties can be set in code, or within the TreeNode Editor. To open the TreeNode Editor, click the ellipsis button ( ![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property on the Properties window. + + ```vb + ' (Assumes that ImageList1 contains at least two images and + ' the TreeView control contains a selected image.) + TreeView1.SelectedNode.ImageIndex = 0 + TreeView1.SelectedNode.SelectedImageIndex = 1 + ``` + + ```csharp + // (Assumes that imageList1 contains at least two images and + // the TreeView control contains a selected image.) + treeView1.SelectedNode.ImageIndex = 0; + treeView1.SelectedNode.SelectedImageIndex = 1; + ``` + + ```cpp + // (Assumes that imageList1 contains at least two images and + // the TreeView control contains a selected image.) + treeView1->SelectedNode->ImageIndex = 0; + treeView1->SelectedNode->SelectedImageIndex = 1; + ``` + +## See also + +- [TreeView Control Overview](treeview-control-overview-windows-forms.md) +- [How to: Add and Remove Nodes with the Windows Forms TreeView Control](how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md) +- [How to: Iterate Through All Nodes of a Windows Forms TreeView Control](how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md) +- [How to: Determine Which TreeView Node Was Clicked](how-to-determine-which-treeview-node-was-clicked-windows-forms.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-options-with-windows-forms-checkbox-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-options-with-windows-forms-checkbox-controls.md new file mode 100644 index 0000000000..b7e626fc29 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-options-with-windows-forms-checkbox-controls.md @@ -0,0 +1,67 @@ +--- +title: Set Options with CheckBox Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "checked" +helpviewer_keywords: + - "CheckBox control [Windows Forms], checked state" + - "check boxes [Windows Forms], using to set options" + - "CheckBox control [Windows Forms], using to set options" +ms.assetid: 2ac70498-7e3e-4e07-8901-ccabaeb5fd3e +--- +# How to: Set Options with Windows Forms CheckBox Controls +A Windows Forms control is used to give users True/False or Yes/No options. The control displays a check mark when it is selected. + +### To set options with CheckBox controls + +1. Examine the value of the property to determine its state, and use that value to set an option. + + In the code sample below, when the control's event is raised, the form's property is set to `false` if the check box is checked. This is useful for situations where you want to restrict user interaction. + + ```vb + Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged + ' Determine the CheckState of the check box. + If CheckBox1.CheckState = CheckState.Checked Then + ' If checked, do not allow items to be dragged onto the form. + Me.AllowDrop = False + End If + End Sub + ``` + + ```csharp + private void checkBox1_CheckedChanged(object sender, System.EventArgs e) + { + // Determine the CheckState of the check box. + if (checkBox1.CheckState == CheckState.Checked) + { + // If checked, do not allow items to be dragged onto the form. + this.AllowDrop = false; + } + } + ``` + + ```cpp + private: + void checkBox1_CheckedChanged(System::Object ^ sender, + System::EventArgs ^ e) + { + // Determine the CheckState of the check box. + if (checkBox1->CheckState == CheckState::Checked) + { + // If checked, do not allow items to be dragged onto the form. + this->AllowDrop = false; + } + } + ``` + +## See also + +- +- [CheckBox Control Overview](checkbox-control-overview-windows-forms.md) +- [How to: Respond to Windows Forms CheckBox Clicks](how-to-respond-to-windows-forms-checkbox-clicks.md) +- [CheckBox Control](checkbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-pictures-at-run-time-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-pictures-at-run-time-windows-forms.md new file mode 100644 index 0000000000..02f050a9ca --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-pictures-at-run-time-windows-forms.md @@ -0,0 +1,101 @@ +--- +title: "How to: Set Pictures at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "pictures [Windows Forms], setting display" + - "examples [Windows Forms], PictureBox control" + - "bitmaps [Windows Forms], displaying in PictureBox control [Windows Forms]" + - "PictureBox control [Windows Forms], adding images" + - "images [Windows Forms], adding with PictureBox control [Windows Forms]" + - "PictureBox control [Windows Forms], adding pictures" +ms.assetid: 18ca41d0-68a5-4660-985e-a6c1fbc01d76 +--- +# How to: Set Pictures at Run Time (Windows Forms) +You can programmatically set the image displayed by a Windows Forms control. + +### To set a picture programmatically + +- Set the property using the method of the class. + + In the example below, the path set for the location of the image is the My Documents folder. This is done, because you can assume that most computers running the Windows operating system will include this directory. This also allows users with minimal system access levels to safely run the application. The example below assumes a form with a control already added. + + ```vb + Private Sub LoadNewPict() + ' You should replace the bold image + ' in the sample below with an icon of your own choosing. + PictureBox1.Image = Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Image.gif") + End Sub + ``` + + ```csharp + private void LoadNewPict(){ + // You should replace the bold image + // in the sample below with an icon of your own choosing. + // Note the escape character used (@) when specifying the path. + pictureBox1.Image = Image.FromFile + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Image.gif"); + } + ``` + + ```cpp + private: + void LoadNewPict() + { + // You should replace the bold image + // in the sample below with an icon of your own choosing. + pictureBox1->Image = Image::FromFile(String::Concat( + System::Environment::GetFolderPath( + System::Environment::SpecialFolder::Personal), + "\\Image.gif")); + } + ``` + +### To clear a graphic + +- First, release the memory being used by the image, and then clear the graphic. Garbage collection will free up the memory later if memory management becomes a problem. + + ```vb + If Not (PictureBox1.Image Is Nothing) Then + PictureBox1.Image.Dispose() + PictureBox1.Image = Nothing + End If + ``` + + ```csharp + if (pictureBox1.Image != null) + { + pictureBox1.Image.Dispose(); + pictureBox1.Image = null; + } + ``` + + ```cpp + if (pictureBox1->Image != nullptr) + { + pictureBox1->Image->Dispose(); + pictureBox1->Image = nullptr; + } + ``` + + > [!NOTE] + > For more information on why you should use the method in this way, see [Cleaning Up Unmanaged Resources](https://docs.microsoft.com/dotnet/standard/garbage-collection/unmanage). + + This code will clear the image even if a graphic was loaded into the control at design time. + +## See also + +- +- +- [PictureBox Control Overview](picturebox-control-overview-windows-forms.md) +- [How to: Load a Picture Using the Designer](how-to-load-a-picture-using-the-designer-windows-forms.md) +- [How to: Modify the Size or Placement of a Picture at Run Time](how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md) +- [PictureBox Control](picturebox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-background-of-a-windows-forms-panel-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-background-of-a-windows-forms-panel-using-the-designer.md new file mode 100644 index 0000000000..79a6131cdc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-background-of-a-windows-forms-panel-using-the-designer.md @@ -0,0 +1,37 @@ +--- +title: Set the Background of a Panel Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "background colors [Windows Forms], Windows Forms Panel controls" + - "background images [Windows Forms], Windows Forms Panel controls" + - "Panel control [Windows Forms], background" + - "colors [Windows Forms], Windows Forms Panel controls" +ms.assetid: db83cf54-3c69-4b08-ac6c-25b9b5abb1b0 +--- +# How to: Set the background of a Windows Forms panel using the Designer + +A Windows Forms control can display both a background color and a background image. The property sets the background color for controls that are contained in the panel, such as labels and radio buttons. If the property is not set, the selection will fill all of the panel. If the property is set, the image will be displayed behind the controls that are contained in the panel. + +The following procedure requires a **Windows Application** project with a form that contains a control. For information about how to set up such a project in Visual Studio, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## Set the background in the Windows Forms Designer + +1. Open the project in Visual Studio and select the control. + +2. In the **Properties** window, click the arrow button next to the property to display a window with three tabs. + +3. Select the **Custom** tab to display a palette of colors. + +4. Select the **Web** or **System** tab to display a list of predefined names for colors, and then select a color. + +5. In the **Properties** window, click the arrow button next to the property. + +6. In the **Open** dialog box, select the file that you want to display. + +## See also + +- +- +- [Panel Control](panel-control-windows-forms.md) +- [Panel Control Overview](panel-control-overview-windows-forms.md) +- [How to: Group Controls with the Windows Forms Panel Control Using the Designer](group-controls-with-wf-panel-control-using-the-designer.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-background-of-a-windows-forms-panel.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-background-of-a-windows-forms-panel.md new file mode 100644 index 0000000000..9365dcd69a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-background-of-a-windows-forms-panel.md @@ -0,0 +1,70 @@ +--- +title: Set the Background of a Panel +description: Learn how to set the background color and background image of a Windows Forms panel using the Designer. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "background colors [Windows Forms], Windows Forms Panel controls" + - "background images [Windows Forms], Windows Forms Panel controls" + - "Panel control [Windows Forms], background" + - "colors [Windows Forms], Windows Forms Panel controls" +ms.assetid: 096cbd8d-45cc-47b8-b1ef-a27f60ea8be0 +--- +# How to: Set the Background of a Windows Forms Panel +A Windows Forms control can display both a background color and a background image. The property sets the background color for the contained controls, such as labels and radio buttons. If the property is not set, the selection will fill the entire panel. If the property is set, the image will be displayed behind the contained controls. + +### To set the background programmatically + +1. Set the panel's property to a value of type . + + ```vb + Panel1.BackColor = Color.AliceBlue + ``` + + ```csharp + panel1.BackColor = Color.AliceBlue; + ``` + + ```cpp + panel1->BackColor = Color::AliceBlue; + ``` + +2. Set the panel's property using the method of the class. + + ```vb + ' You should replace the bolded image + ' in the sample below with an image of your own choosing. + Panel1.BackgroundImage = Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.Personal) _ + & "\Image.gif") + ``` + + ```csharp + // You should replace the bolded image + // in the sample below with an image of your own choosing. + // Note the escape character used (@) when specifying the path. + panel1.BackgroundImage = Image.FromFile + (System.Environment.GetFolderPath + (System.Environment.SpecialFolder.Personal) + + @"\Image.gif"); + ``` + + ```cpp + // You should replace the bolded image + // in the sample below with an image of your own choosing. + panel1->BackgroundImage = Image::FromFile(String::Concat( + System::Environment::GetFolderPath + (System::Environment::SpecialFolder::Personal), + "\\Image.gif")); + ``` + +## See also + +- +- +- [Panel Control](panel-control-windows-forms.md) +- [Panel Control Overview](panel-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-format-for-the-windows-forms-numericupdown-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-format-for-the-windows-forms-numericupdown-control.md new file mode 100644 index 0000000000..80d35702a9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-format-for-the-windows-forms-numericupdown-control.md @@ -0,0 +1,58 @@ +--- +title: Set the Format for NumericUpDown Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "NumericUpDown control [Windows Forms], formatting values" + - "up-down controls [Windows Forms], formatting numeric values" +ms.assetid: fa7c5557-6bfb-45b2-975d-8887b23b0ba0 +--- +# How to: Set the Format for the Windows Forms NumericUpDown Control +You can configure how values are displayed in the Windows Forms control. The property determines how many numbers appear after the decimal point; the default is 0. The property determines whether a separator will be inserted between every three decimal digits; the default is `false`. The control can display values in hexadecimal instead of decimal format, if the property is set to `true`; the default is `false`. + +### To format the numeric value + +- Display a decimal value by setting the property to an integer and setting the property to `true` or `false`. + + ```vb + NumericUpDown1.DecimalPlaces = 2 + NumericUpDown1.ThousandsSeparator = True + ``` + + ```csharp + numericUpDown1.DecimalPlaces = 2; + numericUpDown1.ThousandsSeparator = true; + ``` + + ```cpp + numericUpDown1->DecimalPlaces = 2; + numericUpDown1->ThousandsSeparator = true; + ``` + + -or- + +- Display a hexadecimal value by setting the property to `true`. + + ```vb + NumericUpDown1.Hexadecimal = True + ``` + + ```csharp + numericUpDown1.Hexadecimal = true; + ``` + + ```cpp + numericUpDown1->Hexadecimal = true; + ``` + + > [!NOTE] + > Even if the value is displayed on the form as hexadecimal, any tests you perform on the property will be testing its decimal value. + +## See also + +- +- [NumericUpDown Control](numericupdown-control-windows-forms.md) +- [NumericUpDown Control Overview](numericupdown-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-image-displayed-by-a-windows-forms-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-image-displayed-by-a-windows-forms-control.md new file mode 100644 index 0000000000..9cb45b7869 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-image-displayed-by-a-windows-forms-control.md @@ -0,0 +1,61 @@ +--- +title: Set the Image Displayed by a Control +ms.date: 08/20/2019 +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Button control [Windows Forms], images" + - "Windows Forms controls, images" + - "controls [Windows Forms], images" + - "images [Windows Forms], Windows Forms controls" + - "examples [Windows Forms], controls" +ms.assetid: 9445af8f-4f62-48b0-a3f6-068058964b9f +--- +# How to: Set the image displayed by a Windows Forms control + +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. + +## 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. + +```vb +' Replace the image named below with your own icon. +PictureBox1.Image = Image.FromFile _ + (System.Environment.GetFolderPath _ + (System.Environment.SpecialFolder.MyPictures) _ + & "\Image.gif") +``` + +```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"); +``` + +```cpp +// Replace the image named below with your own icon. +pictureBox1->Image = Image::FromFile(String::Concat + (System::Environment::GetFolderPath + (System::Environment::SpecialFolder::MyPictures), + "\\Image.gif")); +``` + +## Designer + +1. 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. + +2. Select the image you want to display. + +## See also + +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-input-mask.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-input-mask.md new file mode 100644 index 0000000000..32e1591444 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-input-mask.md @@ -0,0 +1,62 @@ +--- +title: "How to: Set the Input Mask" +ms.date: "03/30/2017" +f1_keywords: + - "net.ComponentModel.MaskPropertyEditor" +helpviewer_keywords: + - "MaskedTextBox control [Windows Forms]" +ms.assetid: 779b3a12-cd74-4e58-b46e-04983bda5b2c +--- +# How to: Set the Input Mask +The masked text box control is an enhanced text box control that supports a declarative syntax for accepting or rejecting user input. By setting the Mask property, you can specify the allowable user input without writing any custom validation logic in your application. For more information, see the Remarks section of the class. + +## Setting the Mask Property Manually + If you are familiar with the characters that the Mask property supports, you can enter it manually. For a summary of the characters that the Mask property supports, see the Remarks section of the property. + +### To set the Mask property manually + +1. In **Design** view, select a . + +2. In the **Properties** window, locate the property. + +3. Type the mask that you want. For example, type `###`. + +## Using the Input Mask Dialog Box + The Input Mask dialog box provides some predefined input masks. You can also change the predefined masks or enter your own mask manually. + +### To open the Input Mask dialog box + +1. In **Design** view, select a . + + 1. Click the smart tag to open the **MaskedTextBox Tasks** panel. + + 2. Click **Set Mask**. + + \- or - + + 1. In the **Properties** window, select the property. + + 2. Click the ellipsis button in the property value column. + + The **Input Mask** dialog box appears. + +### To use the Input Mask dialog box + +1. (Optional) Click one of the predefined masks in the list. + +2. (Optional) Edit the predefined mask in the **Mask** box. + +3. (Optional) Type a new mask in the **Mask** box. That is, you do not have to use one of the predefined masks. + + > [!NOTE] + > The Preview box displays the characters that the user sees in the . These characters are a guide to help the user enter the data correctly. + +4. Select or clear the **Use ValidatingType** check box. The **Use ValidatingType** check box specifies whether a data type is used to verify the data input by the user. For more information, see the property. + +5. Click **OK**. + + The mask is entered in the **Mask** property in the **Properties** window. + +## See also + +- [Walkthrough: Working with the MaskedTextBox Control](walkthrough-working-with-the-maskedtextbox-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..23919fced1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md @@ -0,0 +1,34 @@ +--- +title: Set the Selection Mode of DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "selection [Windows Forms], modes in DataGridView control" + - "DataGridView control [Windows Forms], selection mode" + - "data grids [Windows Forms], selection mode" +ms.assetid: 2f241643-7f82-4583-8757-03494f63b465 +--- +# How to: Set the Selection Mode of the Windows Forms DataGridView Control +The following code example demonstrates how to configure a control so that clicking anywhere within a row automatically selects the entire row, and so that only one row at a time can be selected. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#065](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#065)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#065](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#065)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- +- +- +- [Selection and Clipboard Use with the Windows Forms DataGridView Control](selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md) +- [Selection Modes in the Windows Forms DataGridView Control](selection-modes-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-size-of-status-bar-panels.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-size-of-status-bar-panels.md new file mode 100644 index 0000000000..2246c4dba2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-size-of-status-bar-panels.md @@ -0,0 +1,68 @@ +--- +title: "How to: Set the Size of Status-Bar Panels" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "StatusBar control [Windows Forms], panel size" + - "status bars [Windows Forms], setting panel size" + - "panels [Windows Forms], setting size in status bars" +ms.assetid: a01bee43-d9eb-4954-84e6-45a93532d08d +--- +# How to: Set the Size of Status-Bar Panels +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + Each instance of the class within a [StatusBar Control](statusbar-control-windows-forms.md) control has a number of dynamic properties that determine its width and resize behavior at run time. + +### To set the size of a panel + +1. In a procedure, set the , , and properties (or any subset therein) for the status-bar panels using their index passed through the property of the collection. + + ```vb + Public Sub SetStatusBarPanelSize() + ' Create panel and set text property. + StatusBar1.Panels.Add("One") + ' Set properties of panels. + StatusBar1.Panels(0).AutoSize = StatusBarPanelAutoSize.Spring + StatusBar1.Panels(0).Width = 200 + ' Enable the StatusBar control to display panels. + StatusBar1.ShowPanels = True + End Sub + ``` + + ```csharp + public void SetStatusBarPanelSize() + { + // Create panel and set text property. + statusBar1.Panels.Add("One"); + // Set properties of panels. + statusBar1.Panels[0].AutoSize = StatusBarPanelAutoSize.Spring; + statusBar1.Panels[0].Width = 200; + statusBar1.ShowPanels = true; + } + ``` + + ```cpp + public: + void SetStatusBarPanelSize() + { + // Create panel and set text property. + statusBar1->Panels->Add("One"); + // Set properties of panels. + statusBar1->Panels[0]->AutoSize = + StatusBarPanelAutoSize::Spring; + statusBar1->Panels[0]->Width = 200; + statusBar1->ShowPanels = true; + } + ``` + +## See also + +- +- +- [Walkthrough: Updating Status Bar Information at Run Time](walkthrough-updating-status-bar-information-at-run-time.md) +- [How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked](determine-which-panel-wf-statusbar-control-was-clicked.md) +- [StatusBar Control Overview](statusbar-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..f67965c5fc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md @@ -0,0 +1,62 @@ +--- +title: Set the Sizing Modes of DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], setting sizing modes" + - "DataGridView control [Windows Forms], sizing modes" +ms.assetid: e9ad15e6-b4bb-44aa-a767-3738e9db1651 +--- +# How to: Set the Sizing Modes of the Windows Forms DataGridView Control +The following procedures demonstrate some common scenarios that customize or combine the sizing options available for the control and for specific columns in a control. + +### To create a fixed-width column + +- Set the property to , the property to , the property to `true`, and the property to an appropriate value. + + [!code-csharp[System.Windows.Forms.DataGridViewSizingScenarios#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewSizingScenarios#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb#10)] + +### To create a column that adjusts its size to fit its content + +- Set the property to a content-based sizing mode. + + [!code-csharp[System.Windows.Forms.DataGridViewSizingScenarios#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs#20)] + [!code-vb[System.Windows.Forms.DataGridViewSizingScenarios#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb#20)] + +### To create fill-mode columns for values of varying size and importance + +- Set the property to to set the sizing mode for all columns that do not override this value. Set the properties of the columns to values that are proportional to their average content widths. Set the properties of important columns to ensure partial content display. + + [!code-csharp[System.Windows.Forms.DataGridViewSizingScenarios#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs#30)] + [!code-vb[System.Windows.Forms.DataGridViewSizingScenarios#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb#30)] + +## Example + The following complete code example provides a demonstration application that can help you understand the sizing options described in this topic. + + [!code-csharp[System.Windows.Forms.DataGridViewSizingScenarios#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewSizingScenarios#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb#00)] + + To use this demonstration application: + +- Change the size of the form. Observe how the fill-mode columns change their widths while retaining the proportions indicated by the property values. Observe how a column's prevents it from changing when the form is too small. + +- Change the column sizes by dragging the column dividers with the mouse. Observe how some columns cannot be resized, and how resizable columns cannot be made narrower than their minimum widths. + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-tab-order-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-tab-order-on-windows-forms.md new file mode 100644 index 0000000000..393ed661a1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-tab-order-on-windows-forms.md @@ -0,0 +1,57 @@ +--- +title: Set tab order of controls +description: Learn how to set the tab order of controls on your Windows Forms. Set the tab order with Visual Studio or using the TabIndex property in the Properties window. +ms.date: "03/30/2017" +f1_keywords: + - "TabStop" + - "TabIndex" +helpviewer_keywords: + - "tab order [Windows Forms], controls on Windows forms" + - "Windows Forms controls, setting tab order" + - "controls [Windows Forms], setting tab order" + - "Windows Forms, setting tab order" +ms.assetid: 71fa8e76-0472-414b-ad3c-0f90166e0ad7 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Set the tab order on Windows Forms + +The tab order is the order in which a user moves focus from one control to another by pressing the Tab key. Each form has its own tab order. By default, the tab order is the same as the order in which you created the controls. Tab-order numbering begins with zero. + +## To set the tab order of a control + +1. In Visual Studio, on the **View** menu, select **Tab Order**. + + This activates the tab-order selection mode on the form. A number (representing the property) appears in the upper-left corner of each control. + +2. Click the controls sequentially to establish the tab order you want. + + > [!NOTE] + > A control's place within the tab order can be set to any value greater than or equal to 0. When duplicates occur, the z-order of the two controls is evaluated and the control on top is tabbed to first. (The z-order is the visual layering of controls on a form along the form's z-axis [depth]. The z-order determines which controls are in front of other controls.) For more information on z-order, see [Layering Objects on Windows Forms](how-to-layer-objects-on-windows-forms.md). + +3. When you have finished, select **Tab Order** on the **View** menu again to leave tab order mode. + + > [!NOTE] + > Controls that cannot get the focus, as well as disabled and invisible controls, do not have a property and are not included in the tab order. As a user presses the Tab key, these controls are skipped. + +Alternatively, tab order can be set in the Properties window using the property. The property of a control determines where it is positioned in the tab order. By default, the first control drawn has a value of 0, the second has a of 1, and so on. + +Additionally, by default, a control has its own value, which is a whole number. A control itself cannot have focus at run time. Thus, each control within a has its own decimal value, beginning with .0. Naturally, as the of a control is incremented, the controls within it will be incremented accordingly. If you changed a value from 5 to 6, the value of the first control in its group automatically changes to 6.0, and so on. + +Finally, any control of the many on your form can be skipped in the tab order. Usually, pressing Tab successively at run time selects each control in the tab order. By turning off the property, you can make a control be passed over in the tab order of the form. + +## To remove a control from the tab order + +Set the control's property to **false** in the **Properties** window. + +A control whose property has been set to `false` still maintains its position in the tab order, even though the control is skipped when you cycle through the controls with the Tab key. + +> [!NOTE] +> A radio button group has a single tab stop at run time. The selected button (that is, the button with its property set to `true`) has its property automatically set to `true`, while the other buttons have their property set to `false`. For more information about grouping controls, see [Grouping Windows Forms RadioButton Controls to Function as a Set](how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md). + +## See also + +- [Windows Forms Controls](index.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Windows Forms Controls by Function](windows-forms-controls-by-function.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-text-displayed-by-a-windows-forms-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-text-displayed-by-a-windows-forms-control.md new file mode 100644 index 0000000000..da2a0037ea --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-text-displayed-by-a-windows-forms-control.md @@ -0,0 +1,84 @@ +--- +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: 08/20/2019 +dev_langs: + - "csharp" + - "vb" + - "cpp" +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" +ms.assetid: 36b95bff-8780-479d-b86a-f1a0673653aa +--- +# How to: Set the text displayed by a Windows Forms control + +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). + +## Programmatic + +1. Set the property to a string. + + To create an underlined access key, includes an ampersand (&) before the letter that will be the access key. + +2. 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); + ``` + + ```cpp + button1->Text = "Click here to save changes"; + button1->Font = new System::Drawing::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"; + ``` + + ```cpp + mpMenuItem->Text = "&& Now For Something Completely Different"; + ``` + +## Designer + +1. In the **Properties** window in Visual Studio, set the **Text** property of the control to an appropriate string. + + To create an underlined shortcut key, includes an ampersand (&) before the letter that will be the shortcut key. + +2. 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. + + In the standard font dialog box, select the font, font style, size, effects (such as strikeout or underline), and script that you want. + +## See also + +- +- [How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md) +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-toolstrip-renderer-at-run-time.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-toolstrip-renderer-at-run-time.md new file mode 100644 index 0000000000..842a9a2c72 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-toolstrip-renderer-at-run-time.md @@ -0,0 +1,52 @@ +--- +title: "How to: Set the ToolStrip Renderer at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStripManager class [Windows Forms]" + - "ToolStripProfessionalRenderer class [Windows Forms]" + - "ToolStrip control [Windows Forms]" + - "MenuStrip control [Windows Forms]" +ms.assetid: 525e2347-0804-49aa-b9a3-9b2cabbf1c35 +--- +# How to: Set the ToolStrip Renderer at Run Time +You can customize the appearance of your control by creating a custom `ProfessionalColorTable` class. + +## Example + The following code example demonstrates how to create a custom `ProfessionalColorTable` class. This class defines gradients for a and a control. + + To use this code example, compile and run the application, and then click **Change Colors** to apply the gradients defined in the custom `ProfessionalColorTable` class. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#20)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#20)] + +## Defining a Custom ProfessionalColorTable class + The custom gradients are defined in the `CustomProfessionalColors` class. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#30)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#30)] + +## Assigning a Custom Renderer + Create a new `ToolStripProfessionalRenderer` with a `CustomProfessionalColors` class, and assign it to the property. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#22](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#22)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#22](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#22)] + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-toolstrip-renderer-for-an-application.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-toolstrip-renderer-for-an-application.md new file mode 100644 index 0000000000..5eb0e69382 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-toolstrip-renderer-for-an-application.md @@ -0,0 +1,45 @@ +--- +title: "How to: Set the ToolStrip Renderer for an Application" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Renderer property [Windows Forms]" + - "ToolStripProfessionalRenderer class [Windows Forms]" + - "ToolStrip control [Windows Forms]" + - "MenuStrip control [Windows Forms]" + - "toolbars [Windows Forms], customizing" +ms.assetid: 46acef3e-9844-4ae8-9a2e-3006fe99cadf +--- +# How to: Set the ToolStrip Renderer for an Application +You can customize the appearance of your controls individually or for all the controls in your application. + +## Example + The following code example demonstrates how to selectively apply a custom renderer to a control and a control. + + To use this code example, compile and run the application, and then select the scope of the custom rending from the control. Click **Apply** to set the renderer. + + To see custom menu item rendering, select the option from the control, click **Apply**, and then open the **File** menu item. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#70](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#70)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#70](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#70)] + + Set the property to apply a custom renderer to all the controls in your application. + + Set the property to apply a custom renderer to an individual control. + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-value-displayed-by-the-windows-forms-progressbar-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-value-displayed-by-the-windows-forms-progressbar-control.md new file mode 100644 index 0000000000..31f6a4f2d5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-the-value-displayed-by-the-windows-forms-progressbar-control.md @@ -0,0 +1,227 @@ +--- +title: Set the Value Displayed by ProgressBar Control +description: Learn how to set the value displayed by the Windows Forms ProgressBar control. There are multiple approaches you can choose to use. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ProgressBar control [Windows Forms], setting value displayed" + - "progress controls [Windows Forms], setting value displayed" +ms.assetid: 0e5010ad-1e9a-4271-895e-5a3d24d37a26 +--- +# How to: Set the Value Displayed by the Windows Forms ProgressBar Control +> [!IMPORTANT] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + The .NET Framework gives you several different ways to display a given value within the control. Which approach you choose will depend on the task at hand or the problem you are solving. The following table shows the approaches you can choose. + +|Approach|Description| +|--------------|-----------------| +|Set the value of the control directly.|This approach is useful for tasks where you know the total of the item measured that will be involved, such as reading records from a data source. Additionally, if you only need to set the value once or twice, this is an easy way to do it. Finally, use this process if you need to decrease the value displayed by the progress bar.| +|Increase the display by a fixed value.|This approach is useful when you are displaying a simple count between the minimum and maximum, such as elapsed time or the number of files that have been processed out of a known total.| +|Increase the display by a value that varies.|This approach is useful when you need to change the displayed value a number of times in different amounts. An example would be showing the amount of hard-disk space being consumed while writing a series of files to the disk.| + + The most direct way to set the value displayed by a progress bar is by setting the property. This can be done either at design time or at run time. + +### To set the ProgressBar value directly + +1. Set the control's and values. + +2. In code, set the control's property to an integer value between the minimum and maximum values you have established. + + > [!NOTE] + > If you set the property outside the boundaries established by the and properties, the control throws an exception. + + The following code example illustrates how to set the value directly. The code reads records from a data source and updates the progress bar and label every time a data record is read. This example requires that your form has a control, a control, and a data table with a row called `CustomerRow` with `FirstName` and `LastName` fields. + + ```vb + Public Sub CreateNewRecords() + ' Sets the progress bar's Maximum property to + ' the total number of records to be created. + ProgressBar1.Maximum = 20 + + ' Creates a new record in the dataset. + ' NOTE: The code below will not compile, it merely + ' illustrates how the progress bar would be used. + Dim anyRow As CustomerRow = DatasetName.ExistingTable.NewRow + anyRow.FirstName = "Stephen" + anyRow.LastName = "James" + ExistingTable.Rows.Add(anyRow) + + ' Increases the value displayed by the progress bar. + ProgressBar1.Value += 1 + ' Updates the label to show that a record was read. + Label1.Text = "Records Read = " & ProgressBar1.Value.ToString() + End Sub + ``` + + ```csharp + public void createNewRecords() + { + // Sets the progress bar's Maximum property to + // the total number of records to be created. + progressBar1.Maximum = 20; + + // Creates a new record in the dataset. + // NOTE: The code below will not compile, it merely + // illustrates how the progress bar would be used. + CustomerRow anyRow = DatasetName.ExistingTable.NewRow(); + anyRow.FirstName = "Stephen"; + anyRow.LastName = "James"; + ExistingTable.Rows.Add(anyRow); + + // Increases the value displayed by the progress bar. + progressBar1.Value += 1; + // Updates the label to show that a record was read. + label1.Text = "Records Read = " + progressBar1.Value.ToString(); + } + ``` + + If you are displaying progress that proceeds by a fixed interval, you can set the value and then call a method that increases the control's value by that interval. This is useful for timers and other scenarios where you are not measuring progress as a percentage of the whole. + +### To increase the progress bar by a fixed value + +1. Set the control's and values. + +2. Set the control's property to an integer representing the amount to increase the progress bar's displayed value. + +3. Call the method to change the value displayed by the amount set in the property. + + The following code example illustrates how a progress bar can maintain a count of the files in a copy operation. + + In the following example, as each file is read into memory, the progress bar and label are updated to reflect the total files read. This example requires that your form has a control and a control. + + ```vb + Public Sub LoadFiles() + ' Sets the progress bar's minimum value to a number representing + ' no operations complete -- in this case, no files read. + ProgressBar1.Minimum = 0 + ' Sets the progress bar's maximum value to a number representing + ' all operations complete -- in this case, all five files read. + ProgressBar1.Maximum = 5 + ' Sets the Step property to amount to increase with each iteration. + ' In this case, it will increase by one with every file read. + ProgressBar1.Step = 1 + + ' Dimensions a counter variable. + Dim i As Integer + ' Uses a For...Next loop to iterate through the operations to be + ' completed. In this case, five files are to be copied into memory, + ' so the loop will execute 5 times. + For i = 0 To 4 + ' Insert code to copy a file + ProgressBar1.PerformStep() + ' Update the label to show that a file was read. + Label1.Text = "# of Files Read = " & ProgressBar1.Value.ToString + Next i + End Sub + ``` + + ```csharp + public void loadFiles() + { + // Sets the progress bar's minimum value to a number representing + // no operations complete -- in this case, no files read. + progressBar1.Minimum = 0; + // Sets the progress bar's maximum value to a number representing + // all operations complete -- in this case, all five files read. + progressBar1.Maximum = 5; + // Sets the Step property to amount to increase with each iteration. + // In this case, it will increase by one with every file read. + progressBar1.Step = 1; + + // Uses a for loop to iterate through the operations to be + // completed. In this case, five files are to be copied into memory, + // so the loop will execute 5 times. + for (int i = 0; i <= 4; i++) + { + // Inserts code to copy a file + progressBar1.PerformStep(); + // Updates the label to show that a file was read. + label1.Text = "# of Files Read = " + progressBar1.Value.ToString(); + } + } + ``` + + Finally, you can increase the value displayed by a progress bar so that each increase is a unique amount. This is useful when you are keeping track of a series of unique operations, such as writing files of different sizes to a hard disk, or measuring progress as a percentage of the whole. + +### To increase the progress bar by a dynamic value + +1. Set the control's and values. + +2. Call the method to change the value displayed by an integer you specify. + + The following code example illustrates how a progress bar can calculate how much disk space has been used during a copy operation. + + In the following example, as each file is written to the hard disk, the progress bar and label are updated to reflect the amount of hard-disk space available. This example requires that your form has a control and a control. + + ```vb + Public Sub ReadFiles() + ' Sets the progress bar's minimum value to a number + ' representing the hard disk space before the files are read in. + ' You will most likely have to set this using a system call. + ' NOTE: The code below is meant to be an example and + ' will not compile. + ProgressBar1.Minimum = AvailableDiskSpace() + ' Sets the progress bar's maximum value to a number + ' representing the total hard disk space. + ' You will most likely have to set this using a system call. + ' NOTE: The code below is meant to be an example + ' and will not compile. + ProgressBar1.Maximum = TotalDiskSpace() + + ' Dimension a counter variable. + Dim i As Integer + ' Uses a For...Next loop to iterate through the operations to be + ' completed. In this case, five files are to be written to the disk, + ' so it will execute the loop 5 times. + For i = 1 To 5 + ' Insert code to read a file into memory and update file size. + ' Increases the progress bar's value based on the size of + ' the file currently being written. + ProgressBar1.Increment(FileSize) + ' Updates the label to show available drive space. + Label1.Text = "Current Disk Space Used = " &_ + ProgressBar1.Value.ToString() + Next i + End Sub + ``` + + ```csharp + public void readFiles() + { + // Sets the progress bar's minimum value to a number + // representing the hard disk space before the files are read in. + // You will most likely have to set this using a system call. + // NOTE: The code below is meant to be an example and + // will not compile. + progressBar1.Minimum = AvailableDiskSpace(); + // Sets the progress bar's maximum value to a number + // representing the total hard disk space. + // You will most likely have to set this using a system call. + // NOTE: The code below is meant to be an example + // and will not compile. + progressBar1.Maximum = TotalDiskSpace(); + + // Uses a for loop to iterate through the operations to be + // completed. In this case, five files are to be written + // to the disk, so it will execute the loop 5 times. + for (int i = 1; i<= 5; i++) + { + // Insert code to read a file into memory and update file size. + // Increases the progress bar's value based on the size of + // the file currently being written. + progressBar1.Increment(FileSize); + // Updates the label to show available drive space. + label1.Text = "Current Disk Space Used = " + progressBar1.Value.ToString(); + } + } + ``` + +## See also + +- +- +- [ProgressBar Control Overview](progressbar-control-overview-windows-forms.md) +- [ProgressBar Control](progressbar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md new file mode 100644 index 0000000000..9b86e74c36 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md @@ -0,0 +1,76 @@ +--- +title: "How to: Set ToolTips for Controls on a Windows Form at Design Time" +description: Learn how to set ToolTips for controls programmatically or in the Windows Forms Designer in Visual Studio. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "tooltips [Windows Forms], for controls" + - "examples [Windows Forms], tooltips" +ms.assetid: c4b60637-4c0a-44c2-a103-f66dff887936 +--- +# How to: Set ToolTips for controls on a Windows Form at design time + +You can set a string in code or in the Windows Forms Designer in Visual Studio. For more information about the component, see [ToolTip Component Overview](tooltip-component-overview-windows-forms.md). + +## Set a ToolTip programmatically + +1. Add the control that will display the ToolTip. + +2. Use the method of the component. + + ```vb + ' In this example, Button1 is the control to display the ToolTip. + ToolTip1.SetToolTip(Button1, "Save changes") + ``` + + ```csharp + // In this example, button1 is the control to display the ToolTip. + toolTip1.SetToolTip(button1, "Save changes"); + ``` + + ```cpp + // In this example, button1 is the control to display the ToolTip. + toolTip1->SetToolTip(button1, "Save changes"); + ``` + +## Set a ToolTip in the designer + +1. In Visual Studio, add a component to the form. + +2. Select the control that will display the ToolTip, or add it to the form. + +3. In the **Properties** window, set the **ToolTip on ToolTip1** value to an appropriate string of text. + +### To remove a ToolTip programmatically + +1. Use the method of the component. + + ```vb + ' In this example, Button1 is the control displaying the ToolTip. + ToolTip1.SetToolTip(Button1, Nothing) + ``` + + ```csharp + // In this example, button1 is the control displaying the ToolTip. + toolTip1.SetToolTip(button1, null); + ``` + + ```cpp + // In this example, button1 is the control displaying the ToolTip. + toolTip1->SetToolTip(button1, NULL); + ``` + +## Remove a ToolTip in the designer + +1. In Visual Studio, select the control that is displaying the ToolTip. + +2. In the **Properties** window, delete the text in the **ToolTip on ToolTip1**. + +## See also + +- [ToolTip Component Overview](tooltip-component-overview-windows-forms.md) +- [How to: Change the Delay of the Windows Forms ToolTip Component](how-to-change-the-delay-of-the-windows-forms-tooltip-component.md) +- [ToolTip Component](tooltip-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-set-up-automatic-menu-merging-for-mdi-applications.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-up-automatic-menu-merging-for-mdi-applications.md new file mode 100644 index 0000000000..1d79dd9cfa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-set-up-automatic-menu-merging-for-mdi-applications.md @@ -0,0 +1,32 @@ +--- +title: "How to: Set Up Automatic Menu Merging for MDI Applications" +ms.date: "03/30/2017" +helpviewer_keywords: + - "MenuStrip [Windows Forms], merging" + - "Merging [Windows Forms], automatic menu" +ms.assetid: 55e32cad-1141-4a56-aa33-d9543ca3d393 +--- +# How to: Set Up Automatic Menu Merging for MDI Applications +The following procedure gives the basic steps for setting up automatic merging in a multiple-document interface (MDI) application with . + +### To set up automatic menu merging + +1. Create the MDI parent form by setting its property to `true`. + +2. Add a to the MDI parent, setting its property to that . + +3. Create an MDI child form, and set its property to the name of the parent form. + +4. Add a to the MDI child form. + +5. On the child form, set the property of the to `false`. + +6. Add menu items to the child form's that you want to merge into the parent form's when the child form is activated. + +7. Use the property on the menu items in the child form's to control how they merge into the parent form. + +## See also + +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-share-bound-data-across-forms-using-the-bindingsource-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-share-bound-data-across-forms-using-the-bindingsource-component.md new file mode 100644 index 0000000000..4fe18d230e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-share-bound-data-across-forms-using-the-bindingsource-component.md @@ -0,0 +1,35 @@ +--- +title: "How to: Share Bound Data Across Forms Using the BindingSource Component" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "examples [Windows Forms], BindingSource component" + - "data binding [Windows Forms], sharing data across forms" + - "BindingSource component [Windows Forms], examples" + - "BindingSource [Windows Forms], using with multiple forms" +ms.assetid: a1a49630-db9c-4485-b888-1f62a373a4f7 +--- +# How to: Share Bound Data Across Forms Using the BindingSource Component +You can easily share data across forms using the component. For example, you may want to display one read-only form that summarizes the data-source data and another editable form that contains detailed information about the currently selected item in the data source. This example demonstrates this scenario. + +## Example + The following code example demonstrates how to share a and its bound data across forms. In this example, the shared is passed to the constructor of the child form. The child form allows the user to edit the data for the currently selected item in the main form. + +> [!NOTE] +> The event for the component is handled in the example to ensure that the two forms remain synchronized. For more information about why this is done, see [How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized](../multiple-controls-bound-to-data-source-synchronized.md). + + [!code-csharp[System.Windows.Forms.BindingSourceMultipleForms#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.BindingSourceMultipleForms#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Windows.Forms, System.Drawing, System.Data, and System.Xml assemblies. + +## See also + +- [BindingSource Component](bindingsource-component.md) +- [Windows Forms Data Binding](../windows-forms-data-binding.md) +- [How to: Handle Errors and Exceptions that Occur with Databinding](how-to-handle-errors-and-exceptions-that-occur-with-databinding.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-show-a-color-palette-with-the-colordialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-show-a-color-palette-with-the-colordialog-component.md new file mode 100644 index 0000000000..e5dc46ad7d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-show-a-color-palette-with-the-colordialog-component.md @@ -0,0 +1,76 @@ +--- +title: "How to: Show a Color Palette with the ColorDialog Component" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "palettes [Windows Forms], showing color" + - "color dialog box [Windows Forms], showing color palettes" + - "colors [Windows Forms], allowing users to select" + - "color palettes [Windows Forms], dialog box" + - "ColorDialog component [Windows Forms], showing color palettes" + - "color palettes [Windows Forms], showing in ColorDialog component" + - "colors [Windows Forms], showing palettes" +ms.assetid: ee050f61-dbc8-4436-ba22-51360981ab48 +--- +# How to: Show a Color Palette with the ColorDialog Component +The [ColorDialog](colordialog-component-windows-forms.md) component displays a palette of colors and returns a property containing the color the user has selected. + +### To choose a color using the ColorDialog component + +1. Display the dialog box using the method. + +2. Use the property to determine how the dialog box was closed. + +3. Use the property of the component to set the chosen color. + + In the example below, the control's event handler opens a component. When a color is chosen and the user clicks **OK**, the control's background color is set to the chosen color. The example assumes your form has a control and a component. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Button1.Click + If ColorDialog1.ShowDialog() = DialogResult.OK Then + Button1.BackColor = ColorDialog1.Color + End If + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + if(colorDialog1.ShowDialog() == DialogResult.OK) + { + button1.BackColor = colorDialog1.Color; + } + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + if(colorDialog1->ShowDialog() == DialogResult::OK) + { + button1->BackColor = colorDialog1->Color; + } + } + ``` + + (Visual C#, Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + + ```cpp + this->button1->Click += + gcnew System::EventHandler(this, &Form1::button1_Click); + ``` + +## See also + +- +- [ColorDialog Component](colordialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-show-a-font-list-with-the-fontdialog-component.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-show-a-font-list-with-the-fontdialog-component.md new file mode 100644 index 0000000000..67fa7b3f4f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-show-a-font-list-with-the-fontdialog-component.md @@ -0,0 +1,76 @@ +--- +title: "How to: Show a Font List with the FontDialog Component" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "fonts [Windows Forms], showing list" + - "FontDialog component [Windows Forms]" + - "fonts [Windows Forms], attributes" + - "Font property [Windows Forms], setting with FontDialog component" + - "Font dialog box [Windows Forms], displaying" + - "fonts [Windows Forms], selecting" +ms.assetid: 35692c1b-0937-4b7a-9207-1ae6bdc244a0 +--- +# How to: Show a Font List with the FontDialog Component +The [FontDialog](fontdialog-component-windows-forms.md) component allows users to select a font, as well as change its display aspects, such as its weight and size. + + The font selected in the dialog box is returned in the property. Thus, taking advantage of the font selected by the user is as easy as reading a property. + +### To select font properties using the FontDialog Component + +1. Display the dialog box using the method. + +2. Use the property to determine how the dialog box was closed. + +3. Use the property to set the desired font. + + In the example below, the control's event handler opens a component. When a font is chosen and the user clicks **OK**, the property of a control that is on the form is set to the chosen font. The example assumes your form has a control, a control, and a component. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Button1.Click + If FontDialog1.ShowDialog() = DialogResult.OK Then + TextBox1.Font = FontDialog1.Font + End If + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + if(fontDialog1.ShowDialog() == DialogResult.OK) + { + textBox1.Font = fontDialog1.Font; + } + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + if(fontDialog1->ShowDialog() == DialogResult::OK) + { + textBox1->Font = fontDialog1->Font; + } + } + ``` + + (Visual C# and Visual C++) Place the following code in the form's constructor to register the event handler. + + ```csharp + this.button1.Click += new System.EventHandler(this.button1_Click); + ``` + + ```cpp + button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click); + ``` + +## See also + +- +- [FontDialog Component](fontdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-size-a-windows-forms-label-control-to-fit-its-contents.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-size-a-windows-forms-label-control-to-fit-its-contents.md new file mode 100644 index 0000000000..2f4a6341b4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-size-a-windows-forms-label-control-to-fit-its-contents.md @@ -0,0 +1,25 @@ +--- +title: Size a Label Control to Fit Its Contents +ms.date: "03/30/2017" +helpviewer_keywords: + - "captions [Windows Forms], sizing" + - "sizing controls" + - "size [Windows Forms], controls" + - "labels [Windows Forms], sizing to fit contents" + - "Label control [Windows Forms], sizing to fit contents" +ms.assetid: 99648964-63b2-438c-980e-d24103ad602b +--- +# How to: Size a Windows Forms Label Control to Fit Its Contents +The Windows Forms control can be single-line or multi-line, and it can be either fixed in size or can automatically resize itself to accommodate its caption. The property helps you size the controls to fit larger or smaller captions, which is particularly useful if the caption will change at run time. + +### To make a label control resize dynamically to fit its contents + +1. Set its property to `true`. + + If is set to `false`, the words specified in the property will wrap to the next line if possible, but the control will not grow. + +## See also + +- [How to: Create Access Keys with Windows Forms Label Controls](how-to-create-access-keys-with-windows-forms-label-controls.md) +- [Label Control Overview](label-control-overview-windows-forms.md) +- [Label Control](label-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md new file mode 100644 index 0000000000..77b090c565 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md @@ -0,0 +1,31 @@ +--- +title: "How to: Span Rows and Columns in a TableLayoutPanel Control" +ms.date: "03/30/2017" +f1_keywords: + - "net.ComponentModel.StyleCollectionEditor.TLP.SpanRowsColumns" +helpviewer_keywords: + - "columns [Windows Forms], spanning" + - "merging cells" + - "TableLayoutPanel control [Windows Forms], spanning rows and columns" + - "rows [Windows Forms], spanning" + - "cells [Windows Forms], merging" +ms.assetid: a8a2fdd3-a848-48b0-a4cd-4e85ebded87e +--- +# How to: Span Rows and Columns in a TableLayoutPanel Control +Controls in a control can span adjacent rows and columns. + +## To span columns and rows + +1. Drag a control from the **Toolbox** onto your form. + +2. Drag a control from the **Toolbox** into the upper-left cell of the control. + +3. Set the control's **ColumnSpan** property to **2**. Note that the control spans the first and second columns. + +4. Set the control's **RowSpan** property to **2**. Note that the control spans the first and second rows. + +5. Set the control's **ColumnSpan** property to **1**. Note that the control moves into the first column and spans the first and second rows. + +## See also + +- [TableLayoutPanel Control](tablelayoutpanel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-specify-the-edit-mode-for-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-specify-the-edit-mode-for-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..8425b97f70 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-specify-the-edit-mode-for-the-windows-forms-datagridview-control.md @@ -0,0 +1,45 @@ +--- +title: Specify the Edit Mode for DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], edit mode" + - "data grids [Windows Forms], edit mode" +ms.assetid: 93e117e8-94c4-411b-ba31-645e475ed85c +--- +# How to: Specify the Edit Mode for the Windows Forms DataGridView Control +By default, users can edit the contents of the current text box cell by typing in it or pressing F2. This puts the cell in edit mode if all of the following conditions are met: + +- The underlying data source supports editing. + +- The control is enabled. + +- The property value is not . + +- The `ReadOnly` properties of the cell, row, column, and control are all set to `false`. + + In edit mode, the user can change the cell value and press ENTER to commit the change or ESC to revert the cell to its original value. + + You can configure a control so that a cell enters edit mode as soon as it becomes the current cell. The behavior of the ENTER and ESC keys is unchanged in this case, but the cell remains in edit mode after the value is committed or reverted. You can also configure the control so that cells enter edit mode only when users type in the cell or only when users press F2. Finally, you can prevent cells from entering edit mode except when you call the method. + +### To change the edit mode of a DataGridView control + +- Set the property to the appropriate enumeration. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#067](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#067)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#067](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#067)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-split-a-window-horizontally-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-split-a-window-horizontally-using-the-designer.md new file mode 100644 index 0000000000..9066b7cea8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-split-a-window-horizontally-using-the-designer.md @@ -0,0 +1,24 @@ +--- +title: "How to: Split a Window Horizontally Using the Designer" +ms.date: "03/30/2017" +helpviewer_keywords: + - "SplitContainer control [Windows Forms], horizontal splitting" + - "split windows [Windows Forms], horizontal" + - "windows [Windows Forms], splitting horizontally" +ms.assetid: 3872a176-891f-4c70-9779-b2ce85b0b102 +--- +# How to: Split a Window Horizontally Using the Designer + +This example makes the splitter that divides the control horizontal. + +> [!NOTE] +> The property of the control determines the direction of the splitter, not of the control itself. + +## To split a window horizontally + +In the **Properties** window, set the property of the control to . + +## See also + +- +- [SplitContainer Control](splitcontainer-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-split-a-window-horizontally.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-split-a-window-horizontally.md new file mode 100644 index 0000000000..9e3cf985c9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-split-a-window-horizontally.md @@ -0,0 +1,55 @@ +--- +title: "How to: Split a Window Horizontally" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "SplitContainer control [Windows Forms], horizontal splitter" + - "splitter windows [Windows Forms], changing splitter orientation" + - "splitter windows [Windows Forms], horizontal" + - "windows [Windows Forms], splitting horizontally" +ms.assetid: a1f74f29-048c-4723-85fa-b9d375ab8f4b +--- +# How to: Split a Window Horizontally +The following code example makes the splitter that divides the control horizontal. + +> [!NOTE] +> The property of the control determines the direction of the splitter, not of the control itself. + +### To split a window horizontally + +1. Within a procedure, set the property of the control to . + + ```vb + Sub ShowSplitContainer() + Dim splitContainer1 as new SplitContainer() + splitContainer1.BorderStyle = BorderStyle.Fixed3D + splitContainer1.Location = New System.Drawing.Point(74, 20) + splitContainer1.Name = "DemoSplitContainer" + splitContainer1.Size = New System.Drawing.Size(212, 435) + splitContainer1.TabIndex = 0 + splitContainer1.Orientation = Orientation.Horizontal + Controls.Add(splitContainer1) + End Sub + ``` + + ```csharp + public void showSplitContainer() + { + SplitContainer splitContainer1 = new SplitContainer (); + splitContainer1.BorderStyle = BorderStyle.Fixed3D; + splitContainer1.Location = new System.Drawing.Point (74, 20); + splitContainer1.Name = "DemoSplitContainer"; + splitContainer1.Size = new System.Drawing.Size (212, 435); + splitContainer1.TabIndex = 0; + splitContainer1.Orientation = Orientation.Horizontal; + this.Controls.Add (splitContainer1); + + } + ``` + +## See also + +- +- [SplitContainer Control](splitcontainer-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-test-the-run-time-behavior-of-a-usercontrol.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-test-the-run-time-behavior-of-a-usercontrol.md new file mode 100644 index 0000000000..ca6172db60 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-test-the-run-time-behavior-of-a-usercontrol.md @@ -0,0 +1,68 @@ +--- +title: "How to: Test the Run-Time Behavior of a UserControl" +ms.date: "03/30/2017" +helpviewer_keywords: + - "UserControl class [Windows Forms], testing" + - "user controls [Windows Forms], testing" + - "composite controls [Windows Forms], testing" + - "UserControl Test Container" + - "UserControl class [Windows Forms], run-time behavior" +ms.assetid: 4e4d5c49-1346-40ac-9d96-40211b573583 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# How to: Test the run-time behavior of a UserControl + +When you develop a , you need to test its run-time behavior. You can create a separate Windows-based application project and place your control on a test form, but this procedure is inconvenient. A faster and easier way is to use the **UserControl Test Container** provided by Visual Studio. This test container starts directly from your Windows control library project. + +> [!IMPORTANT] +> For the test container to load your , the control must have at least one public constructor. + +> [!NOTE] +> A Visual C++ control cannot be tested using the **UserControl Test Container**. + +## Test the run-time behavior of a UserControl + +1. In Visual Studio, create a Windows control library project, and name it **TestContainerExample**. + +2. In the **Windows Forms Designer**, drag a control from the **Toolbox** onto the control's design surface. + +3. Press F5 to build the project and run the **UserControl Test Container**. The test container appears with your in the **Preview** pane. + +4. Select the property displayed in the control to the right of the **Preview** pane. Change its value to **ControlDark**. Observe that the control changes to a darker color. Try changing other property values and observe the effect on your control. + +5. Click the **Dock Fill User Control** check box below the **Preview** pane. Observe that the control is resized to fill the pane. Resize the test container and observe that the control is resized with the pane. + +6. Close the test container. + +7. Add another user control to the **TestContainerExample** project. + +8. In the **Windows Forms Designer**, drag a control from the **Toolbox** onto the control's design surface. + +9. Press F5 to build the project and run the test container. + +10. Click the **Select User Control** to switch between the two user controls. + +## Test user controls from another project + +You can test user controls from other projects in your current project's test container. + +1. In Visual Studio, create a Windows control library project, and name it **TestContainerExample2**. + +2. In the **Windows Forms Designer**, drag a control from the **Toolbox** onto the control's design surface. + +3. Press F5 to build the project and run the test container. The test container appears with your in the **Preview** pane. + +4. Click the **Load** button. + +5. In the **Open** dialog box, navigate to *TestContainerExample.dll*, which you built in the previous procedure. Select *TestContainerExample.dll* and click the **Open** button to load the user controls. + +6. Use the **Select User Control** to switch between the two user controls from the **TestContainerExample** project. + +## See also + +- +- [How to: Author Composite Controls](how-to-author-composite-controls.md) +- [Walkthrough: Authoring a Composite Control](walkthrough-authoring-a-composite-control-with-visual-csharp.md) +- [User Control Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/183c3hth(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-trigger-menu-events-for-toolbar-buttons.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-trigger-menu-events-for-toolbar-buttons.md new file mode 100644 index 0000000000..58dfa8b62f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-trigger-menu-events-for-toolbar-buttons.md @@ -0,0 +1,136 @@ +--- +title: "How to: Trigger Menu Events for Toolbar Buttons" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], toolbars" + - "ToolBar control [Windows Forms], click event handlers" + - "ToolBar control [Windows Forms], coding button click events" + - "toolbars [Windows Forms], click event handlers" +ms.assetid: 98374f70-993d-4ca4-89fb-48fea6ce5b45 +--- +# How to: Trigger Menu Events for Toolbar Buttons +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + If your Windows Form features a control with toolbar buttons, you will want to know which button the user clicks. + + On the event of the control, you can evaluate the property of the class. In the example below, a message box is shown, indicating which button was clicked. For details, see . + + The example below assumes a control has been added to a Windows Form. + +### To handle the Click event on a toolbar + +1. In a procedure, add toolbar buttons to the control. + + ```vb + Public Sub ToolBarConfig() + ' Instantiate the toolbar buttons, set their Text properties + ' and add them to the ToolBar control. + ToolBar1.Buttons.Add(New ToolBarButton("One")) + ToolBar1.Buttons.Add(New ToolBarButton("Two")) + ToolBar1.Buttons.Add(New ToolBarButton("Three")) + ' Add the event handler delegate. + AddHandler ToolBar1.ButtonClick, AddressOf Me.ToolBar1_ButtonClick + End Sub + ``` + + ```csharp + public void ToolBarConfig() + { + toolBar1.Buttons.Add(new ToolBarButton("One")); + toolBar1.Buttons.Add(new ToolBarButton("Two")); + toolBar1.Buttons.Add(new ToolBarButton("Three")); + + toolBar1.ButtonClick += + new ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); + } + ``` + + ```cpp + public: + void ToolBarConfig() + { + toolBar1->Buttons->Add(gcnew ToolBarButton("One")); + toolBar1->Buttons->Add(gcnew ToolBarButton("Two")); + toolBar1->Buttons->Add(gcnew ToolBarButton("Three")); + + toolBar1->ButtonClick += + gcnew ToolBarButtonClickEventHandler(this, + &Form1::toolBar1_ButtonClick); + } + ``` + +2. Add an event handler for the control's event. Use a case switching statement and the class to determine the toolbar button that was clicked. Based on this, show an appropriate message box. + + > [!NOTE] + > A message box is being used solely as a placeholder in this example. Feel free to add other code to execute when the toolbar buttons are clicked. + + ```vb + Protected Sub ToolBar1_ButtonClick(ByVal sender As Object, _ + ByVal e As ToolBarButtonClickEventArgs) + ' Evaluate the Button property of the ToolBarButtonClickEventArgs + ' to determine which button was clicked. + Select Case ToolBar1.Buttons.IndexOf(e.Button) + Case 0 + MessageBox.Show("First toolbar button clicked") + Case 1 + MessageBox.Show("Second toolbar button clicked") + Case 2 + MessageBox.Show("Third toolbar button clicked") + End Select + End Sub + ``` + + ```csharp + protected void toolBar1_ButtonClick(object sender, + ToolBarButtonClickEventArgs e) + { + // Evaluate the Button property of the ToolBarButtonClickEventArgs + // to determine which button was clicked. + switch (toolBar1.Buttons.IndexOf(e.Button)) + { + case 0 : + MessageBox.Show("First toolbar button clicked"); + break; + case 1 : + MessageBox.Show("Second toolbar button clicked"); + break; + case 2 : + MessageBox.Show("Third toolbar button clicked"); + break; + } + } + ``` + + ```cpp + protected: + void toolBar1_ButtonClick(System::Object ^ sender, + ToolBarButtonClickEventArgs ^ e) + { + // Evaluate the Button property of the ToolBarButtonClickEventArgs + // to determine which button was clicked. + switch (toolBar1->Buttons->IndexOf(e->Button)) + { + case 0 : + MessageBox::Show("First toolbar button clicked"); + break; + case 1 : + MessageBox::Show("Second toolbar button clicked"); + break; + case 2 : + MessageBox::Show("Third toolbar button clicked"); + break; + } + } + ``` + +## See also + +- +- [How to: Add Buttons to a ToolBar Control](how-to-add-buttons-to-a-toolbar-control.md) +- [How to: Define an Icon for a ToolBar Button](how-to-define-an-icon-for-a-toolbar-button.md) +- [ToolBar Control](toolbar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-use-a-background-thread-to-search-for-files.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-a-background-thread-to-search-for-files.md new file mode 100644 index 0000000000..0dcaa8b970 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-a-background-thread-to-search-for-files.md @@ -0,0 +1,761 @@ +--- +title: "How to: Use a Background Thread to Search for Files" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Multithreaded Windows Forms Control sample [Windows Forms]" + - "custom controls [Windows Forms], multithreading" + - "threading [Windows Forms], custom controls" + - "custom controls [Windows Forms], samples" +ms.assetid: 7fe3956f-5b8f-4f78-8aae-c9eb0b28f13a +--- +# How to: Use a Background Thread to Search for Files +The component replaces and adds functionality to the namespace; however, the namespace is retained for both backward compatibility and future use, if you choose. For more information, see [BackgroundWorker Component Overview](backgroundworker-component-overview.md). + + Windows Forms uses the single-threaded apartment (STA) model because Windows Forms is based on native Win32 windows that are inherently apartment-threaded. The STA model implies that a window can be created on any thread, but it cannot switch threads once created, and all function calls to it must occur on its creation thread. Outside Windows Forms, classes in the .NET Framework use the free threading model. For information about threading in the .NET Framework, see [Threading](https://docs.microsoft.com/dotnet/standard/threading/index). + + The STA model requires that any methods on a control that need to be called from outside the control's creation thread must be marshaled to (executed on) the control's creation thread. The base class provides several methods (, , and ) for this purpose. makes synchronous method calls; makes asynchronous method calls. + + If you use multithreading in your control for resource-intensive tasks, the user interface can remain responsive while a resource-intensive computation executes on a background thread. + + The following sample (`DirectorySearcher`) shows a multithreaded Windows Forms control that uses a background thread to recursively search a directory for files matching a specified search string and then populates a list box with the search result. The key concepts illustrated by the sample are as follows: + +- `DirectorySearcher` starts a new thread to perform the search. The thread executes the `ThreadProcedure` method that in turn calls the helper `RecurseDirectory` method to do the actual search and to populate the list box. However, populating the list box requires a cross-thread call, as explained in the next two bulleted items. + +- `DirectorySearcher` defines the `AddFiles` method to add files to a list box; however, `RecurseDirectory` cannot directly invoke `AddFiles` because `AddFiles` can execute only in the STA thread that created `DirectorySearcher`. + +- The only way `RecurseDirectory` can call `AddFiles` is through a cross-thread call — that is, by calling or to marshal `AddFiles` to the creation thread of `DirectorySearcher`. `RecurseDirectory` uses so that the call can be made asynchronously. + +- Marshaling a method requires the equivalent of a function pointer or callback. This is accomplished using delegates in the .NET Framework. takes a delegate as an argument. `DirectorySearcher` therefore defines a delegate (`FileListDelegate`), binds `AddFiles` to an instance of `FileListDelegate` in its constructor, and passes this delegate instance to . `DirectorySearcher` also defines an event delegate that is marshaled when the search is completed. + +```vb +Option Strict +Option Explicit + +Imports System.IO +Imports System.Threading +Imports System.Windows.Forms + +Namespace Microsoft.Samples.DirectorySearcher + '

+ ' This class is a Windows Forms control that implements a simple directory searcher. + ' You provide, through code, a search string and it will search directories on + ' a background thread, populating its list box with matches. + ' + Public Class DirectorySearcher + Inherits Control + ' Define a special delegate that handles marshaling + ' lists of file names from the background directory search + ' thread to the thread that contains the list box. + Delegate Sub FileListDelegate(files() As String, startIndex As Integer, count As Integer) + + Private _listBox As ListBox + Private _searchCriteria As String + Private _searching As Boolean + Private _deferSearch As Boolean + Private _searchThread As Thread + Private _fileListDelegate As FileListDelegate + Private _onSearchComplete As EventHandler + + Public Sub New() + _listBox = New ListBox() + _listBox.Dock = DockStyle.Fill + + Controls.Add(_listBox) + + _fileListDelegate = New FileListDelegate(AddressOf AddFiles) + _onSearchComplete = New EventHandler(AddressOf OnSearchComplete) + End Sub + + Public Property SearchCriteria() As String + Get + Return _searchCriteria + End Get + Set + ' If currently searching, abort + ' the search and restart it after + ' setting the new criteria. + ' + Dim wasSearching As Boolean = Searching + + If wasSearching Then + StopSearch() + End If + + _listBox.Items.Clear() + _searchCriteria = value + + If wasSearching Then + BeginSearch() + End If + End Set + End Property + + Public ReadOnly Property Searching() As Boolean + Get + Return _searching + End Get + End Property + + Public Event SearchComplete As EventHandler + + ' + ' This method is called from the background thread. It is called through + ' a BeginInvoke call so that it is always marshaled to the thread that + ' owns the list box control. + ' + ' + ' + ' + Private Sub AddFiles(files() As String, startIndex As Integer, count As Integer) + While count > 0 + count -= 1 + _listBox.Items.Add(files((startIndex + count))) + End While + End Sub + + Public Sub BeginSearch() + ' Create the search thread, which + ' will begin the search. + ' If already searching, do nothing. + ' + If Searching Then + Return + End If + + ' Start the search if the handle has + ' been created. Otherwise, defer it until the + ' handle has been created. + If IsHandleCreated Then + _searchThread = New Thread(New ThreadStart(AddressOf ThreadProcedure)) + _searching = True + _searchThread.Start() + Else + _deferSearch = True + End If + End Sub + + Protected Overrides Sub OnHandleDestroyed(e As EventArgs) + ' If the handle is being destroyed and you are not + ' recreating it, then abort the search. + If Not RecreatingHandle Then + StopSearch() + End If + MyBase.OnHandleDestroyed(e) + End Sub + + Protected Overrides Sub OnHandleCreated(e As EventArgs) + MyBase.OnHandleCreated(e) + If _deferSearch Then + _deferSearch = False + BeginSearch() + End If + End Sub + + ' + ' This method is called by the background thread when it has + ' finished the search. + ' + ' + ' + Private Sub OnSearchComplete(sender As Object, e As EventArgs) + RaiseEvent SearchComplete(sender, e) + End Sub + + Public Sub StopSearch() + If Not _searching Then + Return + End If + + If _searchThread.IsAlive Then + _searchThread.Abort() + _searchThread.Join() + End If + + _searchThread = Nothing + _searching = False + End Sub + + ' + ' Recurses the given path, adding all files on that path to + ' the list box. After it finishes with the files, it + ' calls itself once for each directory on the path. + ' + ' + Private Sub RecurseDirectory(searchPath As String) + ' Split searchPath into a directory and a wildcard specification. + ' + Dim directoryPath As String = Path.GetDirectoryName(searchPath) + Dim search As String = Path.GetFileName(searchPath) + + ' If a directory or search criteria are not specified, then return. + ' + If directoryPath Is Nothing Or search Is Nothing Then + Return + End If + + Dim files() As String + + ' File systems like NTFS that have + ' access permissions might result in exceptions + ' when looking into directories without permission. + ' Catch those exceptions and return. + Try + files = Directory.GetFiles(directoryPath, search) + Catch e As UnauthorizedAccessException + Return + Catch e As DirectoryNotFoundException + Return + End Try + + ' Perform a BeginInvoke call to the list box + ' in order to marshal to the correct thread. It is not + ' very efficient to perform this marshal once for every + ' file, so batch up multiple file calls into one + ' marshal invocation. + Dim startingIndex As Integer = 0 + While startingIndex < files.Length + ' Batch up 20 files at once, unless at the + ' end. + ' + Dim count As Integer = 20 + If count + startingIndex >= files.Length Then + count = files.Length - startingIndex + End If + ' Begin the cross-thread call. Because you are passing + ' immutable objects into this invoke method, you do not have to + ' wait for it to finish. If these were complex objects, you would + ' have to either create new instances of them or + ' wait for the thread to process this invoke before modifying + ' the objects. + Dim r As IAsyncResult = BeginInvoke(_fileListDelegate, New Object() {files, startingIndex, count}) + startingIndex += count + End While + ' Now that you have finished the files in this directory, recurse + ' for each subdirectory. + Dim directories As String() = Directory.GetDirectories(directoryPath) + Dim d As String + For Each d In directories + RecurseDirectory(Path.Combine(d, search)) + Next d + End Sub + + '/ + '/ This is the actual thread procedure. This method runs in a background + '/ thread to scan directories. When finished, it simply exits. + '/ + Private Sub ThreadProcedure() + ' Get the search string. Individual + ' field assigns are atomic in .NET, so you do not + ' need to use any thread synchronization to grab + ' the string value here. + Try + Dim localSearch As String = SearchCriteria + + ' Now, search the file system. + ' + RecurseDirectory(localSearch) + Finally + ' You are done with the search, so update. + ' + _searching = False + + ' Raise an event that notifies the user that + ' the search has terminated. + ' You do not have to do this through a marshaled call, but + ' marshaling is recommended for the following reason: + ' Users of this control do not know that it is + ' multithreaded, so they expect its events to + ' come back on the same thread as the control. + BeginInvoke(_onSearchComplete, New Object() {Me, EventArgs.Empty}) + End Try + End Sub + End Class +End Namespace +``` + +```csharp +namespace Microsoft.Samples.DirectorySearcher +{ + using System; + using System.IO; + using System.Threading; + using System.Windows.Forms; + + /// + /// This class is a Windows Forms control that implements a simple directory searcher. + /// You provide, through code, a search string and it will search directories on + /// a background thread, populating its list box with matches. + /// + public class DirectorySearcher : Control + { + // Define a special delegate that handles marshaling + // lists of file names from the background directory search + // thread to the thread that contains the list box. + private delegate void FileListDelegate(string[] files, int startIndex, int count); + + private ListBox listBox; + private string searchCriteria; + private bool searching; + private bool deferSearch; + private Thread searchThread; + private FileListDelegate fileListDelegate; + private EventHandler onSearchComplete; + + public DirectorySearcher() + { + listBox = new ListBox(); + listBox.Dock = DockStyle.Fill; + + Controls.Add(listBox); + + fileListDelegate = new FileListDelegate(AddFiles); + onSearchComplete = new EventHandler(OnSearchComplete); + } + + public string SearchCriteria + { + get + { + return searchCriteria; + } + set + { + // If currently searching, abort + // the search and restart it after + // setting the new criteria. + // + bool wasSearching = Searching; + + if (wasSearching) + { + StopSearch(); + } + + listBox.Items.Clear(); + searchCriteria = value; + + if (wasSearching) + { + BeginSearch(); + } + } + } + + public bool Searching + { + get + { + return searching; + } + } + + public event EventHandler SearchComplete; + + /// + /// This method is called from the background thread. It is called through + /// a BeginInvoke call so that it is always marshaled to the thread that + /// owns the list box control. + /// + /// + /// + /// + private void AddFiles(string[] files, int startIndex, int count) + { + while(count-- > 0) + { + listBox.Items.Add(files[startIndex + count]); + } + } + + public void BeginSearch() + { + // Create the search thread, which + // will begin the search. + // If already searching, do nothing. + // + if (Searching) + { + return; + } + + // Start the search if the handle has + // been created. Otherwise, defer it until the + // handle has been created. + if (IsHandleCreated) + { + searchThread = new Thread(new ThreadStart(ThreadProcedure)); + searching = true; + searchThread.Start(); + } + else + { + deferSearch = true; + } + } + + protected override void OnHandleDestroyed(EventArgs e) + { + // If the handle is being destroyed and you are not + // recreating it, then abort the search. + if (!RecreatingHandle) + { + StopSearch(); + } + base.OnHandleDestroyed(e); + } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + if (deferSearch) + { + deferSearch = false; + BeginSearch(); + } + } + + /// + /// This method is called by the background thread when it has finished + /// the search. + /// + /// + /// + private void OnSearchComplete(object sender, EventArgs e) + { + if (SearchComplete != null) + { + SearchComplete(sender, e); + } + } + + public void StopSearch() + { + if (!searching) + { + return; + } + + if (searchThread.IsAlive) + { + searchThread.Abort(); + searchThread.Join(); + } + + searchThread = null; + searching = false; + } + + /// + /// Recurses the given path, adding all files on that path to + /// the list box. After it finishes with the files, it + /// calls itself once for each directory on the path. + /// + /// + private void RecurseDirectory(string searchPath) + { + // Split searchPath into a directory and a wildcard specification. + // + string directory = Path.GetDirectoryName(searchPath); + string search = Path.GetFileName(searchPath); + + // If a directory or search criteria are not specified, then return. + // + if (directory == null || search == null) + { + return; + } + + string[] files; + + // File systems like NTFS that have + // access permissions might result in exceptions + // when looking into directories without permission. + // Catch those exceptions and return. + try + { + files = Directory.GetFiles(directory, search); + } + catch(UnauthorizedAccessException) + { + return; + } + catch(DirectoryNotFoundException) + { + return; + } + + // Perform a BeginInvoke call to the list box + // in order to marshal to the correct thread. It is not + // very efficient to perform this marshal once for every + // file, so batch up multiple file calls into one + // marshal invocation. + int startingIndex = 0; + + while(startingIndex < files.Length) + { + // Batch up 20 files at once, unless at the + // end. + // + int count = 20; + if (count + startingIndex >= files.Length) + { + count = files.Length - startingIndex; + } + + // Begin the cross-thread call. Because you are passing + // immutable objects into this invoke method, you do not have to + // wait for it to finish. If these were complex objects, you would + // have to either create new instances of them or + // wait for the thread to process this invoke before modifying + // the objects. + IAsyncResult r = BeginInvoke(fileListDelegate, new object[] {files, startingIndex, count}); + startingIndex += count; + } + + // Now that you have finished the files in this directory, recurse for + // each subdirectory. + string[] directories = Directory.GetDirectories(directory); + foreach(string d in directories) + { + RecurseDirectory(Path.Combine(d, search)); + } + } + + /// + /// This is the actual thread procedure. This method runs in a background + /// thread to scan directories. When finished, it simply exits. + /// + private void ThreadProcedure() + { + // Get the search string. Individual + // field assigns are atomic in .NET, so you do not + // need to use any thread synchronization to grab + // the string value here. + try + { + string localSearch = SearchCriteria; + + // Now, search the file system. + // + RecurseDirectory(localSearch); + } + finally + { + // You are done with the search, so update. + // + searching = false; + + // Raise an event that notifies the user that + // the search has terminated. + // You do not have to do this through a marshaled call, but + // marshaling is recommended for the following reason: + // Users of this control do not know that it is + // multithreaded, so they expect its events to + // come back on the same thread as the control. + BeginInvoke(onSearchComplete, new object[] {this, EventArgs.Empty}); + } + } + } +} +``` + +## Using the Multithreaded Control on a Form + The following example shows how the multithreaded `DirectorySearcher` control can be used on a form. + +```vb +Option Explicit +Option Strict + +Imports System.Collections +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Windows.Forms +Imports Microsoft.Samples.DirectorySearcher + +Namespace SampleUsage + + ' + ' Summary description for Form1. + ' + Public Class Form1 + Inherits System.Windows.Forms.Form + Private WithEvents directorySearcher As DirectorySearcher + Private searchText As System.Windows.Forms.TextBox + Private searchLabel As System.Windows.Forms.Label + Private WithEvents searchButton As System.Windows.Forms.Button + + Public Sub New() + ' + ' Required for Windows Forms designer support. + ' + InitializeComponent() + ' + ' Add any constructor code after InitializeComponent call here. + ' + End Sub + + #Region "Windows Form Designer generated code" + ' + ' Required method for designer support. Do not modify + ' the contents of this method with the code editor. + ' + Private Sub InitializeComponent() + Me.directorySearcher = New Microsoft.Samples.DirectorySearcher.DirectorySearcher() + Me.searchButton = New System.Windows.Forms.Button() + Me.searchText = New System.Windows.Forms.TextBox() + Me.searchLabel = New System.Windows.Forms.Label() + Me.directorySearcher.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right + Me.directorySearcher.Location = New System.Drawing.Point(8, 72) + Me.directorySearcher.SearchCriteria = Nothing + Me.directorySearcher.Size = New System.Drawing.Size(271, 173) + Me.directorySearcher.TabIndex = 2 + Me.searchButton.Location = New System.Drawing.Point(8, 16) + Me.searchButton.Size = New System.Drawing.Size(88, 40) + Me.searchButton.TabIndex = 0 + Me.searchButton.Text = "&Search" + Me.searchText.Anchor = System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right + Me.searchText.Location = New System.Drawing.Point(104, 24) + Me.searchText.Size = New System.Drawing.Size(175, 20) + Me.searchText.TabIndex = 1 + Me.searchText.Text = "c:\*.cs" + Me.searchLabel.ForeColor = System.Drawing.Color.Red + Me.searchLabel.Location = New System.Drawing.Point(104, 48) + Me.searchLabel.Size = New System.Drawing.Size(176, 16) + Me.searchLabel.TabIndex = 3 + Me.ClientSize = New System.Drawing.Size(291, 264) + Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.searchLabel, Me.directorySearcher, Me.searchText, Me.searchButton}) + Me.Text = "Search Directories" + End Sub + #End Region + + ' + ' The main entry point for the application. + ' + _ + Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Private Sub searchButton_Click(sender As Object, e As System.EventArgs) Handles searchButton.Click + directorySearcher.SearchCriteria = searchText.Text + searchLabel.Text = "Searching..." + directorySearcher.BeginSearch() + End Sub + + Private Sub directorySearcher_SearchComplete(sender As Object, e As System.EventArgs) Handles directorySearcher.SearchComplete + searchLabel.Text = String.Empty + End Sub + End Class +End Namespace +``` + +```csharp +namespace SampleUsage +{ + using System; + using System.Collections; + using System.ComponentModel; + using System.Data; + using System.Drawing; + using System.Windows.Forms; + using Microsoft.Samples.DirectorySearcher; + + /// + /// Summary description for Form1. + /// + public class Form1 : System.Windows.Forms.Form + { + private DirectorySearcher directorySearcher; + private System.Windows.Forms.TextBox searchText; + private System.Windows.Forms.Label searchLabel; + private System.Windows.Forms.Button searchButton; + + public Form1() + { + // + // Required for Windows Forms designer support. + // + InitializeComponent(); + + // + // Add any constructor code after InitializeComponent call here. + // + } + + #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.directorySearcher = new Microsoft.Samples.DirectorySearcher.DirectorySearcher(); + this.searchButton = new System.Windows.Forms.Button(); + this.searchText = new System.Windows.Forms.TextBox(); + this.searchLabel = new System.Windows.Forms.Label(); + this.directorySearcher.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right); + this.directorySearcher.Location = new System.Drawing.Point(8, 72); + this.directorySearcher.SearchCriteria = null; + this.directorySearcher.Size = new System.Drawing.Size(271, 173); + this.directorySearcher.TabIndex = 2; + this.directorySearcher.SearchComplete += new System.EventHandler(this.directorySearcher_SearchComplete); + this.searchButton.Location = new System.Drawing.Point(8, 16); + this.searchButton.Size = new System.Drawing.Size(88, 40); + this.searchButton.TabIndex = 0; + this.searchButton.Text = "&Search"; + this.searchButton.Click += new System.EventHandler(this.searchButton_Click); + this.searchText.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right); + this.searchText.Location = new System.Drawing.Point(104, 24); + this.searchText.Size = new System.Drawing.Size(175, 20); + this.searchText.TabIndex = 1; + this.searchText.Text = "c:\\*.cs"; + this.searchLabel.ForeColor = System.Drawing.Color.Red; + this.searchLabel.Location = new System.Drawing.Point(104, 48); + this.searchLabel.Size = new System.Drawing.Size(176, 16); + this.searchLabel.TabIndex = 3; + this.ClientSize = new System.Drawing.Size(291, 264); + this.Controls.AddRange(new System.Windows.Forms.Control[] {this.searchLabel, + this.directorySearcher, + this.searchText, + this.searchButton}); + this.Text = "Search Directories"; + + } + #endregion + + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.Run(new Form1()); + } + + private void searchButton_Click(object sender, System.EventArgs e) + { + directorySearcher.SearchCriteria = searchText.Text; + searchLabel.Text = "Searching..."; + directorySearcher.BeginSearch(); + } + + private void directorySearcher_SearchComplete(object sender, System.EventArgs e) + { + searchLabel.Text = string.Empty; + } + } +} +``` + +## See also + +- +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [Event-based Asynchronous Pattern Overview](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-use-a-control-rendering-class.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-a-control-rendering-class.md new file mode 100644 index 0000000000..677d3259cd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-a-control-rendering-class.md @@ -0,0 +1,33 @@ +--- +title: "How to: Use a Control Rendering Class" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "professional appearance [Windows Forms], rendering Windows Forms controls" + - "visual themes [Windows Forms], applying to Windows Forms controls" + - "visual styles [Windows Forms], rendering Windows Forms controls" +ms.assetid: c0125e34-cd74-4c35-818c-3e40f462b0a3 +--- +# How to: Use a Control Rendering Class +This example demonstrates how to use the class to render the drop-down arrow of a combo box control. The example consists of the method of a simple custom control. The property is used to determine whether visual styles are enabled in the client area of application windows. If visual styles are active, then the method will render the drop-down arrow with visual styles; otherwise, the method will render the drop-down arrow in the classic Windows style. + +## Example + [!code-cpp[System.Windows.Forms_ControlRenderer#10](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/form1.cpp#10)] + [!code-csharp[System.Windows.Forms_ControlRenderer#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/CS/form1.cs#10)] + [!code-vb[System.Windows.Forms_ControlRenderer#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/VB/form1.vb#10)] + +## Compiling the Code + This example requires: + +- A custom control derived from the class. + +- A that hosts the custom control. + +- References to the , , , and namespaces. + +## See also + +- [Rendering Controls with Visual Styles](rendering-controls-with-visual-styles.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-use-the-spring-property-interactively-in-a-statusstrip.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-the-spring-property-interactively-in-a-statusstrip.md new file mode 100644 index 0000000000..4b96263de4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-the-spring-property-interactively-in-a-statusstrip.md @@ -0,0 +1,39 @@ +--- +title: "How to: Use the Spring Property Interactively in a StatusStrip" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "StatusStrip control [Windows Forms]" + - "ToolStrip control [Windows Forms]" + - "status bars [Windows Forms], examples" + - "Spring property [Windows Forms]" +ms.assetid: 18bde842-a93c-48dd-9db3-15738a1775ce +--- +# How to: Use the Spring Property Interactively in a StatusStrip +You can use the property to position a control in a control. The property determines whether the control automatically fills the available space on the control. + +## Example + The following code example demonstrates how to use the property to position a control in a control. The event handler performs an exclusive-or (XOR) operation to switch the value of the property. + + To use this code example, compile and run the application, and then click **Middle (Spring)** on the control to switch the value of the property. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#1)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#1)] +[!code-csharp[System.Windows.Forms.ToolStrip.Misc#50](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#50)] +[!code-vb[System.Windows.Forms.ToolStrip.Misc#50](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#50)] + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-use-toolstrippanels-for-mdi.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-toolstrippanels-for-mdi.md new file mode 100644 index 0000000000..28d56880aa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-toolstrippanels-for-mdi.md @@ -0,0 +1,30 @@ +--- +title: "How to: Use ToolStripPanels for MDI" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "MDI [Windows Forms], using ToolStripPanels [Windows Forms]" + - "ToolStripPanel control [Windows Forms], using for MDI" + - "toolbars [Windows Forms], using for MDI" +ms.assetid: d6b884fc-0846-465f-83c3-5dc0fe93b00f +--- +# How to: Use ToolStripPanels for MDI +The provides flexibility for multiple-document interface (MDI) applications by using the method. + +## Example + The following code example demonstrates how to use controls for MDI. + + [!code-csharp[System.Windows.Forms.ToolStrip.Misc#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs#10)] + [!code-vb[System.Windows.Forms.ToolStrip.Misc#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb#10)] + +## Compiling the Code + This example requires: + +- References to the System.Design, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- [How to: Join ToolStripPanels](how-to-join-toolstrippanels.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-use-tooltips-in-toolstrip-controls.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-tooltips-in-toolstrip-controls.md new file mode 100644 index 0000000000..c5063ad5d1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-use-tooltips-in-toolstrip-controls.md @@ -0,0 +1,38 @@ +--- +title: "How to: Use ToolTips in ToolStrip Controls" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], adding tooltips" + - "toolbars [Windows Forms], adding tooltips" + - "tooltips [Windows Forms], adding" +ms.assetid: c5d86024-a7c5-44ee-8b3f-2daf53d80d3e +--- +# How to: Use ToolTips in ToolStrip Controls +You can display a for the control you want by setting the control's property to `true`. + +### To display a ToolTip + +- Set the property of the control to `true`. + + The default value of is `true`, and the default value of and is `false`. + +### To use the ToolTipText property for the ToolTip text of a ToolStripButton + +1. Set the property of the button to `true`. + +2. Set the property of the button to `false`. + + The `AutoToolTip` property is `true` by default for , , and . + + A uses its `Text` property for the text by default. Use this procedure to display custom text in a . + +> [!NOTE] +> If you set to or , no text will appear on the button, but the tool tip still appears. + +## See also + +- +- +- +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-validate-data-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-validate-data-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..85da98b1cf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-validate-data-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,38 @@ +--- +title: Validate Data in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data [Windows Forms], validation" + - "DataGridView control [Windows Forms], data validation" + - "data grids [Windows Forms], validating data" + - "data validation [Windows Forms], Windows Forms" +ms.assetid: d10aef35-701e-4a3c-a684-2a2ed1aeaca6 +--- +# How to: Validate Data in the Windows Forms DataGridView Control +The following code example demonstrates how to validate data entered by a user into a control. In this example, the is populated with rows from the `Customers` table of the Northwind sample database. When the user edits a cell in the `CompanyName` column, its value is tested for validity by checking that it is not empty. If the event handler for the event finds that the value is an empty string, the prevents the user from exiting the cell until a non-empty string is entered. + + For a complete explanation of this code example, see [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewDataValidation#00](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs#00)] + [!code-vb[System.Windows.Forms.DataGridViewDataValidation#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Windows.Forms and System.XML assemblies. + +## .NET Framework Security + Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + +## See also + +- +- +- [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md) +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) +- [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-validate-input-with-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-validate-input-with-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..0dc6b17448 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-validate-input-with-the-windows-forms-datagrid-control.md @@ -0,0 +1,87 @@ +--- +title: Validate Input with DataGrid Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGrid control [Windows Forms], examples" + - "user input [Windows Forms], validating" + - "examples [Windows Forms], DataGrid control" + - "DataGrid control [Windows Forms], validating input" + - "validation [Windows Forms], user input" +ms.assetid: f1e9c3a0-d0a1-4893-a615-b4b0db046c63 +--- + +# How to: Validate Input with the Windows Forms DataGrid Control + +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + +There are two types of input validation available for the Windows Forms control. If the user attempts to enter a value that is of an unacceptable data type for the cell, for example a string into an integer, the new invalid value is replaced with the old value. This kind of input validation is done automatically and cannot be customized. + +The other type of input validation can be used to reject any unacceptable data, for example a 0 value in a field that must be greater than or equal to 1, or an inappropriate string. This is done in the dataset by writing an event handler for the or event. The example below uses the event because the unacceptable value is disallowed for the "Product" column in particular. You might use the event for checking that the value of an "End Date" column is later than the "Start Date" column in the same row. + +## To validate user input + +1. Write code to handle the event for the appropriate table. When inappropriate input is detected, call the method of the object. + + ```vb + Private Sub Customers_ColumnChanging(ByVal sender As Object, _ + ByVal e As System.Data.DataColumnChangeEventArgs) + ' Only check for errors in the Product column + If (e.Column.ColumnName.Equals("Product")) Then + ' Do not allow "Automobile" as a product. + If CType(e.ProposedValue, String) = "Automobile" Then + Dim badValue As Object = e.ProposedValue + e.ProposedValue = "Bad Data" + e.Row.RowError = "The Product column contains an error" + e.Row.SetColumnError(e.Column, "Product cannot be " & _ + CType(badValue, String)) + End If + End If + End Sub + ``` + + ```csharp + //Handle column changing events on the Customers table + private void Customers_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e) { + + //Only check for errors in the Product column + if (e.Column.ColumnName.Equals("Product")) { + + //Do not allow "Automobile" as a product + if (e.ProposedValue.Equals("Automobile")) { + object badValue = e.ProposedValue; + e.ProposedValue = "Bad Data"; + e.Row.RowError = "The Product column contains an error"; + e.Row.SetColumnError(e.Column, "Product cannot be " + badValue); + } + } + } + ``` + +2. Connect the event handler to the event. + + Place the following code within either the form's event or its constructor. + + ```vb + ' Assumes the grid is bound to a dataset called customersDataSet1 + ' with a table called Customers. + ' Put this code in the form's Load event or its constructor. + AddHandler customersDataSet1.Tables("Customers").ColumnChanging, AddressOf Customers_ColumnChanging + ``` + + ```csharp + // Assumes the grid is bound to a dataset called customersDataSet1 + // with a table called Customers. + // Put this code in the form's Load event or its constructor. + customersDataSet1.Tables["Customers"].ColumnChanging += new DataColumnChangeEventHandler(this.Customers_ColumnChanging); + ``` + +## See also + +- +- +- +- [DataGrid Control](datagrid-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md new file mode 100644 index 0000000000..d2e886fa81 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md @@ -0,0 +1,53 @@ +--- +title: View Multiple Lines in TextBox Control +description: Learn how to view multiple lines in the Windows Forms TextBox control by setting the Multiline, WordWrap, and ScrollBars properties. +ms.date: "03/30/2017" +helpviewer_keywords: + - "newline" + - "end of line" + - "ScrollBars property [Windows Forms], in TextBox control" + - "CRLF" + - "MultiLine property in TextBox control" + - "line-feed" + - "TextBox control [Windows Forms], viewing multiple lines" + - "carriage return" +ms.assetid: 43173201-0b74-4067-a472-605029ca5f35 +--- +# How to: View Multiple Lines in the Windows Forms TextBox Control +By default, the Windows Forms control displays a single line of text and does not display scroll bars. If the text is longer than the available space, only part of the text is visible. You can change this default behavior by setting the , , and properties to appropriate values. + +### To display a carriage return in the TextBox control + +- To display a carriage return in a multi-line , use the property. + + Be aware that the interpretation of escape characters (\\) is language-specific. Visual Basic uses `Chr$(13) & Chr$(10)` for the carriage return and linefeed character combination. + +### To view multiple lines in the TextBox control + +1. Set the property to `true`. If is `true` (the default), then the text in the control will appear as one or more paragraphs; otherwise it will appear as a list, in which some lines may be clipped at the edge of the control. + +2. Set the property to an appropriate value. + + |Value|Description| + |-----------|-----------------| + ||Use this value if the text will be a paragraph that almost always fits the control. The user can use the mouse pointer to move around inside the control if the text is too long to display all at once.| + ||Use this value if you want to display a list of lines, some of which may be longer than the width of the control.| + ||Use this value if the list may be longer than the height of the control.| + +3. Set the property to an appropriate value. + + |Value|Description| + |-----------|-----------------| + |`false`|Text in the control will not automatically be wrapped, so it will scroll to the right until a line break is reached. Use this value if you chose scroll bars or , above.| + |`true` (default)|The horizontal scrollbar will not appear. Use this value if you chose scroll bars or , above, to display one or more paragraphs.| + +## See also + +- +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) +- [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) +- [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) +- [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) +- [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) +- [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..9dd98f3bc7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,32 @@ +--- +title: Work with Image Columns in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "image columns" + - "image columns [Windows Forms], Windows Forms" + - "DataGridView control [Windows Forms], image columns" +ms.assetid: 8a37aa75-3c6e-4893-91d0-7a5f34bfe287 +--- +# How to: Work with Image Columns in the Windows Forms DataGridView Control +The following code example shows how to use the image columns in an interactive user interface (UI). The example also demonstrates image sizing and layout possibilities with the . + +## Example + [!code-cpp[System.Windows.Forms.DataGridView.ImageColumn_TicTacToe#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CPP/tictactoe.cpp#0)] + [!code-csharp[System.Windows.Forms.DataGridView.ImageColumn_TicTacToe#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CS/tictactoe.cs#0)] + [!code-vb[System.Windows.Forms.DataGridView.ImageColumn_TicTacToe#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/VB/tictactoe.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) +- [How to: Display Images in Cells of the Windows Forms DataGridView Control](how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/how-to-wrap-a-windows-forms-control-with-toolstripcontrolhost.md b/dotnet-desktop-guide/framework/winforms/controls/how-to-wrap-a-windows-forms-control-with-toolstripcontrolhost.md new file mode 100644 index 0000000000..bf177d04f2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/how-to-wrap-a-windows-forms-control-with-toolstripcontrolhost.md @@ -0,0 +1,65 @@ +--- +title: Wrap Control with ToolStripControlHost +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], wrapping controls" + - "toolbars [Windows Forms], wrapping controls" + - "ToolStrip control [Windows Forms], hosting controls" +ms.assetid: e2ce4990-661d-4882-a116-8a9eb575dc84 +--- +# How to: Wrap a Windows Forms Control with ToolStripControlHost + is designed to enable hosting of arbitrary Windows Forms controls by using the constructor or by extending itself. It is easier to wrap the control by extending and implementing properties and methods that expose frequently used properties and methods of the control. You can also expose events for the control at the level. + +### To host a control in a ToolStripControlHost by derivation + +1. Extend . Implement a parameterless constructor that calls the base class constructor passing in the desired control. + + [!code-cpp[System.Windows.Forms.ToolStripControlHost#10](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp#10)] + [!code-csharp[System.Windows.Forms.ToolStripControlHost#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs#10)] + [!code-vb[System.Windows.Forms.ToolStripControlHost#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb#10)] + +2. Declare a property of the same type as the wrapped control and return `Control` as the correct type of control in the property's accessor. + + [!code-cpp[System.Windows.Forms.ToolStripControlHost#11](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp#11)] + [!code-csharp[System.Windows.Forms.ToolStripControlHost#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs#11)] + [!code-vb[System.Windows.Forms.ToolStripControlHost#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb#11)] + +3. Expose other frequently used properties and methods of the wrapped control with properties and methods in the extended class. + + [!code-cpp[System.Windows.Forms.ToolStripControlHost#12](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp#12)] + [!code-csharp[System.Windows.Forms.ToolStripControlHost#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs#12)] + [!code-vb[System.Windows.Forms.ToolStripControlHost#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb#12)] + +4. Optionally, override the , and methods and add the control events you want to expose. + + [!code-cpp[System.Windows.Forms.ToolStripControlHost#16](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp#16)] + [!code-csharp[System.Windows.Forms.ToolStripControlHost#16](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs#16)] + [!code-vb[System.Windows.Forms.ToolStripControlHost#16](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb#16)] + +5. Provide the necessary wrapping for the events you want to expose. + + [!code-cpp[System.Windows.Forms.ToolStripControlHost#17](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp#17)] + [!code-csharp[System.Windows.Forms.ToolStripControlHost#17](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs#17)] + [!code-vb[System.Windows.Forms.ToolStripControlHost#17](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb#17)] + +## Example + [!code-cpp[System.Windows.Forms.ToolStripControlHost#13](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp#13)] + [!code-csharp[System.Windows.Forms.ToolStripControlHost#13](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs#13)] + [!code-vb[System.Windows.Forms.ToolStripControlHost#13](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb#13)] + +## Compiling the Code + +This example requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/hscrollbar-and-vscrollbar-controls-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/hscrollbar-and-vscrollbar-controls-overview-windows-forms.md new file mode 100644 index 0000000000..a02d410f34 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/hscrollbar-and-vscrollbar-controls-overview-windows-forms.md @@ -0,0 +1,36 @@ +--- +title: "HScrollBar and VScrollBar Controls Overview" +ms.date: "03/30/2017" +f1_keywords: + - "HScrollBar" + - "VScrollBar" +helpviewer_keywords: + - "ScrollBar control [Windows Forms]" + - "HScrollBar control [Windows Forms], about HScrollBar" + - "VScrollBar control [Windows Forms], about VScrollBar control" + - "ScrollBar control [Windows Forms], about ScrollBar control" + - "scroll bars [Windows Forms], about scroll bars" +ms.assetid: 8b307679-1cae-41d8-99aa-3d1efd207cd6 +--- +# HScrollBar and VScrollBar Controls Overview (Windows Forms) +Windows Forms controls are used to provide easy navigation through a long list of items or a large amount of information by scrolling either horizontally or vertically within an application or control. Scroll bars are a common element of the Windows interface, so the control is often used with controls that do not derive from the class. Similarly, many developers choose to incorporate the control when authoring their own user controls. + + The (horizontal) and (vertical) controls operate independently from other controls and have their own set of events, properties, and methods. controls are not the same as the built-in scroll bars that are attached to text boxes, list boxes, combo boxes, or MDI forms (the control has a property to show or hide scroll bars that are attached to the control). + + The controls use the event to monitor the movement of the scroll box (sometimes referred to as the thumb) along the scroll bar. Using the event provides access to the scroll bar value as it is being dragged. + +## Value Property + The property (which, by default, is 0) is an `integer` value corresponding to the position of the scroll box in the scroll bar. When the scroll box position is at the minimum value, it moves to the left-most position (for horizontal scroll bars) or the top position (for vertical scroll bars). When the scroll box is at the maximum value, the scroll box moves to the right-most or bottom position. Similarly, a value halfway between the bottom and top of the range places the leading edge of the scroll box in the middle of the scroll bar. + + In addition to using mouse clicks to change the scroll bar value, a user can also drag the scroll box to any point along the bar. The resulting value depends on the position of the scroll box, but it is always within the range of the to properties set by the user. + +## LargeChange and SmallChange Properties + When the user presses the PAGE UP or PAGE DOWN key or clicks in the scroll bar track on either side of the scroll box, the property changes according to the value set in the property. + + When the user presses one of the arrow keys or clicks one of the scroll bar buttons, the property changes according to the value set in the property. + +## See also + +- +- +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/hscrollbar-and-vscrollbar-controls-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/hscrollbar-and-vscrollbar-controls-windows-forms.md new file mode 100644 index 0000000000..7add8a6274 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/hscrollbar-and-vscrollbar-controls-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "HScrollBar and VScrollBar Controls" +ms.date: "03/30/2017" +helpviewer_keywords: + - "scroll bars" + - "VScrollBar control [Windows Forms]" + - "scroll bars [Windows Forms], Windows Forms" + - "HScrollBar control [Windows Forms]" + - "Scroll Bar control [Windows Forms]" +ms.assetid: f5e9cda7-d8f3-406b-b0e6-bdb4375d6eb0 +--- +# HScrollBar and VScrollBar Controls (Windows Forms) +Windows Forms scroll bar controls are used to provide easy navigation through a long list of items or a large amount of information by scrolling either horizontally or vertically within an application or control. Scroll bars are a common element of the Windows interface. + +## In This Section + [HScrollBar and VScrollBar Controls Overview](hscrollbar-and-vscrollbar-controls-overview-windows-forms.md) + Introduces the general concepts of the and controls, which allow users to scroll horizontally and vertically through large amounts of information. + +## Reference + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/imagelist-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/imagelist-component-overview-windows-forms.md new file mode 100644 index 0000000000..f59a98c6be --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/imagelist-component-overview-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "ImageList Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ImageList" +helpviewer_keywords: + - "collection controls [Windows Forms], images" + - "icon list control" + - "ImageList component [Windows Forms], about ImageList component" +ms.assetid: 7e25d89b-5633-40c1-afc3-82e0e301ffa2 +--- +# ImageList Component Overview (Windows Forms) + +The Windows Forms component is used to store images, which can then be displayed by controls. An image list allows you to write code for a single, consistent catalog of images. For example, you can rotate images displayed by a control simply by changing the button's or property. You can also associate the same image list with multiple controls. For example, if you are using both a control and a control to display the same list of files, changing a file's icon in the image list will cause the new icon to appear in both views. + +## Using ImageList with Controls + +You can use an image list with any control that has an `ImageList` property — or in the case of the control, and properties. The controls that can be associated with an image list include: the , , , , , , , and controls. To associate the image list with a control, set the control's `ImageList` property to the name of the component. + +## Key Properties + +The key property of the component is , which contains the pictures to be used by the associated control. Each individual image can be accessed by its index value or by its key. The property determines the number of colors that the images are rendered with. The images will all be displayed at the same size, set by the property. Images that are larger will be scaled to fit. + +## See also + +- +- [How to: Add or Remove Images with the Windows Forms ImageList Component](how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/imagelist-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/imagelist-component-windows-forms.md new file mode 100644 index 0000000000..8efe3f10f0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/imagelist-component-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "ImageList Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ImageList component [Windows Forms]" + - "image controls" +ms.assetid: 83b48634-782b-464d-9b7d-568dc6e0bef2 +--- +# ImageList Component (Windows Forms) +The Windows Forms `ImageList` component is used to store images, which can then be displayed by controls. An image list allows you to write code for a single, consistent catalog of images. + +## In This Section + [ImageList Component Overview](imagelist-component-overview-windows-forms.md) + Explains what this component is and its key features and properties + + [How to: Add or Remove Images with the Windows Forms ImageList Component](how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md) + Gives directions for adding and removing images from an image list. + + Also see [How to: Add or Remove ImageList Images with the Designer](how-to-add-or-remove-imagelist-images-with-the-designer.md). + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/implement-two-way-com-between-dhtml-and-client.md b/dotnet-desktop-guide/framework/winforms/controls/implement-two-way-com-between-dhtml-and-client.md new file mode 100644 index 0000000000..f8384f3c13 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/implement-two-way-com-between-dhtml-and-client.md @@ -0,0 +1,110 @@ +--- +title: "How to: Implement Two-Way Communication Between DHTML Code and Client Application Code" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +f1_keywords: + - "WebBrowser.ObjectForScripting" + - "WebBrowser.Document" +helpviewer_keywords: + - "WebBrowser control [Windows Forms], examples" + - "communications [Windows Forms], DHTML and client applications" + - "examples [Windows Forms], WebBrowser control" + - "WebBrowser control [Windows Forms], communication between DHTML and client application" + - "DHTML [Windows Forms], embedding in Windows Forms" +ms.assetid: 55353a32-b09e-4479-a521-ff3a5ff9a708 +--- +# How to: Implement Two-Way Communication Between DHTML Code and Client Application Code + +You can use the control to add existing dynamic HTML (DHTML) Web application code to your Windows Forms client applications. This is useful when you have invested significant development time in creating DHTML-based controls and you want to take advantage of the rich user interface capabilities of Windows Forms without having to rewrite existing code. + +The control lets you implement two-way communication between your client application code and your Web page scripting code through the and properties. Additionally, you can configure the control so that your Web controls blend seamlessly with other controls on your application form, hiding their DHTML implementation. To seamlessly blend the controls, format the page displayed so that its background color and visual style match the rest of the form, and use the , , and properties to disable standard browser features. + +## To embed DHTML in your Windows Forms application + +1. Set the control's property to `false` to prevent the control from opening files dropped onto it. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#1)] + +2. Set the control's property to `false` to prevent the control from displaying its shortcut menu when the user right-clicks it. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#2)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#2)] + +3. Set the control's property to `false` to prevent the control from responding to shortcut keys. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#3)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#3)] + +4. Set the property in the form's constructor or a event handler. + + The following code uses the form class itself for the scripting object. + + > [!NOTE] + > Component Object Model (COM) must be able to access the scripting object. To make your form visible to COM, add the attribute to your form class. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#4)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#4)] + +5. Implement public properties or methods in your application code that your script code will use. + + For example, if you use the form class for the scripting object, add the following code to your form class. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#5)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#5)] + +6. Use the `window.external` object in your scripting code to access public properties and methods of the specified object. + + The following HTML code demonstrates how to call a method on the scripting object from a button click. Copy this code into the BODY element of an HTML document that you load using the control's method or that you assign to the control's property. + + ```html + + ``` + +7. Implement functions in your script code that your application code will use. + + The following HTML SCRIPT element provides an example function. Copy this code into the HEAD element of an HTML document that you load using the control's method or that you assign to the control's property. + + ```html + + ``` + +8. Use the property to access the script code from your client application code. + + For example, add the following code to a button event handler. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#8](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#8)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#8](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#8)] + +9. When you are finished debugging your DHTML, set the control's property to `true` to prevent the control from displaying error messages for script code problems. + + [!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#9](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#9)] + [!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#9](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#9)] + +## Example + +The following complete code example provides a demonstration application that you can use to understand this feature. The HTML code is loaded into the control through the property instead of being loaded from a separate HTML file. + +[!code-csharp[System.Windows.Forms.WebBrowser.ObjectForScripting#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs#0)] +[!code-vb[System.Windows.Forms.WebBrowser.ObjectForScripting#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb#0)] + +## Compiling the Code + +This code requires: + +- References to the System and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [WebBrowser Control](webbrowser-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/implementing-virtual-mode-jit-data-loading-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/implementing-virtual-mode-jit-data-loading-in-the-datagrid.md new file mode 100644 index 0000000000..4fb5ad3366 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/implementing-virtual-mode-jit-data-loading-in-the-datagrid.md @@ -0,0 +1,75 @@ +--- +title: Implementing Virtual Mode with Just-In-Time Data Loading in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "examples [Windows Forms], just-in-time data loading" + - "data [Windows Forms], managing large data sets" + - "DataGridView control [Windows Forms], virtual mode" + - "just-in-time data loading" + - "DataGridView control [Windows Forms], large data sets" + - "virtual mode [Windows Forms], just-in-time data loading" +ms.assetid: c2a052b9-423c-4ff7-91dc-d8c7c79345f6 +--- +# Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control +One reason to implement virtual mode in the control is to retrieve data only as it is needed. This is called *just-in-time data loading*. + + If you are working with a very large table in a remote database, for example, you might want to avoid startup delays by retrieving only the data that is necessary for display and retrieving additional data only when the user scrolls new rows into view. If the client computers running your application have a limited amount of memory available for storing data, you might also want to discard unused data when retrieving new values from the database. + + The following sections describe how to use a control with a just-in-time cache. + + To copy the code in this topic as a single listing, see [How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md). + +## The Form + The following code example defines a form containing a read-only control that interacts with a `Cache` object through a event handler. The `Cache` object manages the locally stored values and uses a `DataRetriever` object to retrieve values from the Orders table of the sample Northwind database. The `DataRetriever` object, which implements the `IDataPageRetriever` interface required by the `Cache` class, is also used to initialize the control rows and columns. + + The `IDataPageRetriever`, `DataRetriever`, and `Cache` types are described later in this topic. + +> [!NOTE] +> Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + + [!code-csharp[System.Windows.Forms.DataGridView.Virtual_lazyloading#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs#100)] + [!code-vb[System.Windows.Forms.DataGridView.Virtual_lazyloading#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb#100)] + +## The IDataPageRetriever Interface + The following code example defines the `IDataPageRetriever` interface, which is implemented by the `DataRetriever` class. The only method declared in this interface is the `SupplyPageOfData` method, which requires an initial row index and a count of the number of rows in a single page of data. These values are used by the implementer to retrieve a subset of data from a data source. + + A `Cache` object uses an implementation of this interface during construction to load two initial pages of data. Whenever an uncached value is needed, the cache discards one of these pages and requests a new page containing the value from the `IDataPageRetriever`. + + [!code-csharp[System.Windows.Forms.DataGridView.Virtual_lazyloading#201](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs#201)] + [!code-vb[System.Windows.Forms.DataGridView.Virtual_lazyloading#201](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb#201)] + +## The DataRetriever Class + The following code example defines the `DataRetriever` class, which implements the `IDataPageRetriever` interface to retrieve pages of data from a server. The `DataRetriever` class also provides `Columns` and `RowCount` properties, which the control uses to create the necessary columns and to add the appropriate number of empty rows to the collection. Adding the empty rows is necessary so that the control will behave as though it contains all the data in the table. This means that the scroll box in the scroll bar will have the appropriate size, and the user will be able to access any row in the table. The rows are filled by the event handler only when they are scrolled into view. + + [!code-csharp[System.Windows.Forms.DataGridView.Virtual_lazyloading#200](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs#200)] + [!code-vb[System.Windows.Forms.DataGridView.Virtual_lazyloading#200](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb#200)] + +## The Cache Class + The following code example defines the `Cache` class, which manages two pages of data populated through an `IDataPageRetriever` implementation. The `Cache` class defines an inner `DataPage` structure, which contains a to store the values in a single cache page and which calculates the row indexes that represent the upper and lower boundaries of the page. + + The `Cache` class loads two pages of data at construction time. Whenever the event requests a value, the `Cache` object determines if the value is available in one of its two pages and, if so, returns it. If the value is not available locally, the `Cache` object determines which of its two pages is farthest from the currently displayed rows and replaces the page with a new one containing the requested value, which it then returns. + + Assuming that the number of rows in a data page is the same as the number of rows that can be displayed on screen at once, this model allows users paging through the table to efficiently return to the most recently viewed page. + + [!code-csharp[System.Windows.Forms.DataGridView.Virtual_lazyloading#300](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs#300)] + [!code-vb[System.Windows.Forms.DataGridView.Virtual_lazyloading#300](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb#300)] + +## Additional Considerations + The previous code examples are provided as a demonstration of just-in-time data loading. You will need to modify the code for your own needs to achieve maximum efficiency. At minimum, you will need to choose an appropriate value for the number of rows per page of data in the cache. This value is passed into the `Cache` constructor. The number of rows per page should be no less than the number of rows that can be displayed simultaneously in your control. + + For best results, you will need to conduct performance testing and usability testing to determine the requirements of your system and your users. Several factors that you will need to take into consideration include the amount of memory in the client machines running your application, the available bandwidth of the network connection used, and the latency of the server used. The bandwidth and latency should be determined at times of peak usage. + + To improve the scrolling performance of your application, you can increase the amount of data stored locally. To improve startup time, however, you must avoid loading too much data initially. You may want to modify the `Cache` class to increase the number of data pages it can store. Using more data pages can improve scrolling efficiency, but you will need to determine the ideal number of rows in a data page, depending on the available bandwidth and the server latency. With smaller pages, the server will be accessed more frequently, but will take less time to return the requested data. If latency is more of an issue than bandwidth, you may want to use larger data pages. + +## See also + +- +- +- [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) +- [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) +- [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md) +- [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md) +- [How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/implementing-virtual-mode-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/implementing-virtual-mode-wf-datagridview-control.md new file mode 100644 index 0000000000..93041eb854 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/implementing-virtual-mode-wf-datagridview-control.md @@ -0,0 +1,136 @@ +--- +title: "Walkthrough: Implement virtual mode in DataGridView control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data [Windows Forms], managing large data sets" + - "DataGridView control [Windows Forms], virtual mode" + - "virtual mode [Windows Forms], walkthroughs" + - "DataGridView control [Windows Forms], large data sets" + - "walkthroughs [Windows Forms], DataGridView control" +ms.assetid: 74eb5276-5ab8-4ce0-8005-dae751d85f7c +--- +# Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control +When you want to display very large quantities of tabular data in a control, you can set the property to `true` and explicitly manage the control's interaction with its data store. This lets you fine-tune the performance of the control in this situation. + + The control provides several events that you can handle to interact with a custom data store. This walkthrough guides you through the process of implementing these event handlers. The code example in this topic uses a very simple data source for illustration purposes. In a production setting, you will typically load only the rows you need to display into a cache, and handle events to interact with and update the cache. For more information, see [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md) + + To copy the code in this topic as a single listing, see [How to: Implement Virtual Mode in the Windows Forms DataGridView Control](how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md). + +## Creating the Form + +#### To implement virtual mode + +1. Create a class that derives from and contains a control. + + The following code contains some basic initialization. It declares some variables that will be used in later steps, provides a `Main` method, and provides a simple form layout in the class constructor. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#001](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#001)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#001](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#001)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#001](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#001)] + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#002](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#002)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#002](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#002)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#002](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#002)] + +2. Implement a handler for your form's event that initializes the control and populates the data store with sample values. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#110](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#110)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#110](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#110)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#110](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#110)] + +3. Implement a handler for the event that retrieves the requested cell value from the data store or the `Customer` object currently in edit. + + This event occurs whenever the control needs to paint a cell. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#120](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#120)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#120](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#120)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#120](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#120)] + +4. Implement a handler for the event that stores an edited cell value in the `Customer` object representing the edited row. This event occurs whenever the user commits a cell value change. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#130](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#130)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#130](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#130)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#130](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#130)] + +5. Implement a handler for the event that creates a new `Customer` object representing a newly created row. + + This event occurs whenever the user enters the row for new records. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#140](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#140)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#140](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#140)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#140](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#140)] + +6. Implement a handler for the event that saves new or modified rows to the data store. + + This event occurs whenever the user changes the current row. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#150](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#150)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#150](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#150)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#150](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#150)] + +7. Implement a handler for the event that indicates whether the event will occur when the user signals row reversion by pressing ESC twice in edit mode or once outside of edit mode. + + By default, occurs upon row reversion when any cells in the current row have been modified unless the property is set to `true` in the event handler. This event is useful when the commit scope is determined at run time. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#160](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#160)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#160](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#160)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#160](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#160)] + +8. Implement a handler for the event that discards the values of the `Customer` object representing the current row. + + This event occurs when the user signals row reversion by pressing ESC twice in edit mode or once outside of edit mode. This event does not occur if no cells in the current row have been modified or if the value of the property has been set to `false` in a event handler. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#170](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#170)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#170](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#170)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#170](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#170)] + +9. Implement a handler for the event that deletes an existing `Customer` object from the data store or discards an unsaved `Customer` object representing a newly created row. + + This event occurs whenever the user deletes a row by clicking a row header and pressing the DELETE key. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#180](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#180)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#180](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#180)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#180](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#180)] + +10. Implement a simple `Customers` class to represent the data items used by this code example. + + [!code-cpp[System.Windows.Forms.DataGridView.VirtualMode#200](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp#200)] + [!code-csharp[System.Windows.Forms.DataGridView.VirtualMode#200](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs#200)] + [!code-vb[System.Windows.Forms.DataGridView.VirtualMode#200](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb#200)] + +## Testing the Application + You can now test the form to make sure it behaves as expected. + +#### To test the form + +- Compile and run the application. + + You will see a control populated with three customer records. You can modify the values of multiple cells in a row and press ESC twice in edit mode and once outside of edit mode to revert the entire row to its original values. When you modify, add, or delete rows in the control, `Customer` objects in the data store are modified, added, or deleted as well. + +## Next Steps + This application gives you a basic understanding of the events you must handle to implement virtual mode in the control. You can improve this basic application in a number of ways: + +- Implement a data store that caches values from an external database. The cache should retrieve and discard values as necessary so that it only contains what is necessary for display while consuming a small amount of memory on the client computer. + +- Fine-tune the performance of the data store depending on your requirements. For example, you might want to compensate for slow network connections rather than client-computer memory limitations by using a larger cache size and minimizing the number of database queries. + + For more information about caching values from an external database, see [How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md). + +## See also + +- +- +- +- +- +- +- +- +- +- [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) +- [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) +- [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md) +- [How to: Implement Virtual Mode in the Windows Forms DataGridView Control](how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/index.md b/dotnet-desktop-guide/framework/winforms/controls/index.md new file mode 100644 index 0000000000..b733cbd7a7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/index.md @@ -0,0 +1,38 @@ +--- +title: Controls +description: Learn how to add and position Windows Form controls. You can also manipulate controls in the designer and write code to add controls dynamically at run time. +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls" + - "controls [Windows Forms]" + - "Windows Forms controls, about Windows Forms controls" +ms.assetid: f050de8f-4ebd-4042-94b8-edf9a1dbd52a +--- +# Windows Forms controls + +As you design and modify the user interface of your Windows Forms applications, you will need to add, align, and position controls. Controls are objects that are contained within form objects. Each type of control has its own set of properties, methods, and events that make it suitable for a particular purpose. You can manipulate controls in the designer and write code to add controls dynamically at run time. + +## In this section + +[Putting Controls on Windows Forms](putting-controls-on-windows-forms.md)\ +Provides links related to putting controls on forms. + +[Arranging Controls on Windows Forms](how-to-align-multiple-controls-on-windows-forms.md)\ +Articles related to arranging controls on forms. + +[Labeling Individual Windows Forms Controls and Providing Shortcuts to Them](labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md)\ +Describes the uses of keyboard shortcuts, text labels on controls, and modifier keys. + +[Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md)\ +Lists the controls that work with Windows Forms, and basic things you can accomplish with each control. + +[Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md)\ +Provides background information and samples to help users develop custom Windows Forms controls. + +[Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md)\ +Describes techniques for creating custom controls through design and inheritance. + +## Related sections + +[Client Applications](https://docs.microsoft.com/dotnet/framework/develop-client-apps)\ +Provides an overview of developing Windows-based applications. diff --git a/dotnet-desktop-guide/framework/winforms/controls/keyboard-shortcuts-for-the-windows-forms-datagrid-control.md b/dotnet-desktop-guide/framework/winforms/controls/keyboard-shortcuts-for-the-windows-forms-datagrid-control.md new file mode 100644 index 0000000000..ef4985ebf4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/keyboard-shortcuts-for-the-windows-forms-datagrid-control.md @@ -0,0 +1,50 @@ +--- +title: Keyboard Shortcuts for DataGrid Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "keyboard shortcuts [Windows Forms], DataGrid control" + - "DataGrid control [Windows Forms], navigation keys" +ms.assetid: a01780f9-20d5-4f5f-808f-c790c9a007a5 +--- +# Keyboard Shortcuts for the Windows Forms DataGrid Control +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md). + + The following table lists the keyboard shortcuts that can be used for navigation within the Windows Forms control: + +|Action|Shortcut| +|------------|--------------| +|Complete a cell entry and move down to the next cell.

If focus is on a child table link, navigate to that table.|ENTER| +|Cancel cell editing if in cell edit mode.

If in marquee selection, cancel editing on the row.|ESC| +|Delete the character before the insertion point when editing a cell.|BACKSPACE| +|Delete the character after the insertion point when editing a cell.|DELETE| +|Move to the first cell in the current row.|HOME| +|Move to the last cell in the current row.|END| +|Highlight characters in the current cell and position the insertion point at the end of the line. Same behavior as double-clicking a cell.|F2| +|If focus is on a cell, move to the next cell in the row.

If focus is on the last cell in a row, move to the first child table link of the row and expand it.

If focus is on a child link, move to the next child link.

If focus is on the last child link, move to the first cell of the next row.|TAB| +|If focus is on a cell, move to the previous cell in the row.

If focus is on the first cell in a row, move to the last expanded child table link of the previous row, or move to the last cell of the previous row.

If focus is on a child link, move to the previous child link.

If focus is on the first child link, move to the last cell of the previous row.|SHIFT+TAB| +|Move to the next control in the tab order.|CTRL+TAB| +|Move to the previous control in the tab order.|CTRL+SHIFT+TAB| +|Move up to the parent table if in a child table. Same behavior as clicking the Back button.|ALT+LEFT ARROW| +|Expand child table links. ALT+DOWN ARROW expands all links, not just the ones selected.|ALT+DOWN ARROW or CTRL+PLUS SIGN| +|Collapse child table links. ALT+UP ARROW collapses all links, not just the ones selected.|ALT+UP ARROW or CTRL+MINUS SIGN| +|Move to the farthest nonblank cell in the direction of the arrow.|CTRL+ARROW| +|Extend the selection one row in the direction of the arrow (excluding child table links).|SHIFT+UP/DOWN ARROW| +|Extend the selection to farthest nonblank row in the direction of the arrow (excluding child table links).|CTRL+SHIFT+ UP/DOWN ARROW| +|Move to the upper-left cell.|CTRL+HOME| +|Move to the lower-right cell.|CTRL+END| +|Extend the selection to the top row.|CTRL+SHIFT+HOME| +|Extend the selection to the bottom row.|CTRL+SHIFT+END| +|Select the current row (excluding child table links).|SHIFT+SPACEBAR| +|Select the entire grid (excluding child table links).|CTRL+A| +|Display the parent row when in a child table.|CTRL+PAGE DOWN| +|Hide the parent row when in a child table.|CTRL+PAGE UP| +|Extend the selection down one screen (excluding child table links).|SHIFT+PAGE DOWN| +|Extend the selection up one screen (excluding child table links).|SHIFT+PAGE UP| +|Call the method for the current row.|CTRL+ENTER| +|Enter a value into a cell when in edit mode.|CTRL+0| + +## See also + +- [DataGrid Control Overview](datagrid-control-overview-windows-forms.md) +- [DataGrid Control](datagrid-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/known-folder-guids-for-file-dialog-custom-places.md b/dotnet-desktop-guide/framework/winforms/controls/known-folder-guids-for-file-dialog-custom-places.md new file mode 100644 index 0000000000..931e806c71 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/known-folder-guids-for-file-dialog-custom-places.md @@ -0,0 +1,286 @@ +--- +title: "Known Folder GUIDs for File Dialog Custom Places" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Known Folder GUIDs [Windows Forms], Custom Places" + - "Custom Places [Windows Forms], Known Folder GUIDs" + - "Windows Vista Known Folder GUIDs [Windows Forms], Custom Places" +ms.assetid: d8d8b544-8b4d-4da5-ba3a-b05e93244778 +--- +# Known Folder GUIDs for File Dialog Custom Places +You use a to specify a Windows Vista Known Folder when you add folders to a collection. Known Folder GUIDs are not case sensitive and are defined in the KnownFolders.h file in the Windows SDK. + +> [!NOTE] +> In some cases, a Known Folder added to the will not be shown in the **Favorite Links** area. For example, if the specified Known Folder is not present on the computer that is running the application, the Known Folder is not shown. + +## List of GUIDs + The following table lists Windows Vista Known Folders and their associated . + + AddNewPrograms + DE61D971-5EBC-4F02-A3A9-6C82895E5C04 + + AdminTools + 724EF170-A42D-4FEF-9F26-B60E846FBA4F + + AppDataLow + A520A1A4-1780-4FF6-BD18-167343C5AF16 + + AppUpdates + A305CE99-F527-492B-8B1A-7E76FA98D6E4 + + CDBurning + 9E52AB10-F80D-49DF-ACB8-4330F5687855 + + ChangeRemovePrograms + DF7266AC-9274-4867-8D55-3BD661DE872D + + CommonAdminTools + D0384E7D-BAC3-4797-8F14-CBA229B392B5 + + CommonOEMLinks + C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D + + CommonPrograms + 0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8 + + CommonStartMenu + A4115719-D62E-491D-AA7C-E74B8BE3B067 + + CommonStartup + 82A5EA35-D9CD-47C5-9629-E15D2F714E6E + + CommonTemplates + B94237E7-57AC-4347-9151-B08C6C32D1F7 + + Computer + 0AC0837C-BBF8-452A-850D-79D08E667CA7 + + Conflict + 4BFEFB45-347D-4006-A5BE-AC0CB0567192 + + Connections + 6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD + + Contacts + 56784854-C6CB-462B-8169-88E350ACB882 + + ControlPanel + 82A74AEB-AEB4-465C-A014-D097EE346D63 + + Cookies + 2B0F765D-C0E9-4171-908E-08A611B84FF6 + + Desktop + B4BFCC3A-DB2C-424C-B029-7FE99A87C641 + + Documents + FDD39AD0-238F-46AF-ADB4-6C85480369C7 + + Downloads + 374DE290-123F-4565-9164-39C4925E467B + + Favorites + 1777F761-68AD-4D8A-87BD-30B759FA33DD + + Fonts + FD228CB7-AE11-4AE3-864C-16F3910AB8FE + + Games + CAC52C1A-B53D-4EDC-92D7-6B2E8AC19434 + + GameTasks + 054FAE61-4DD8-4787-80B6-090220C4B700 + + History + D9DC8A3B-B784-432E-A781-5A1130A75963 + + Internet + 4D9F7874-4E0C-4904-967B-40B0D20C3E4B + + InternetCache + 352481E8-33BE-4251-BA85-6007CAEDCF9D + + Links + BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968 + + LocalAppData + F1B32785-6FBA-4FCF-9D55-7B8E7F157091 + + LocalizedResourcesDir + 2A00375E-224C-49DE-B8D1-440DF7EF3DDC + + Music + 4BD8D571-6D19-48D3-BE97-422220080E43 + + NetHood + C5ABBF53-E17F-4121-8900-86626FC2C973 + + Network + D20BEEC4-5CA8-4905-AE3B-BF251EA09B53 + + OriginalImages + 2C36C0AA-5812-4B87-BFD0-4CD0DFB19B39 + + PhotoAlbums + 69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C + + Pictures + 33E28130-4E1E-4676-835A-98395C3BC3BB + + Playlists + DE92C1C7-837F-4F69-A3BB-86E631204A23 + + Printers + 76FC4E2D-D6AD-4519-A663-37BD56068185 + + PrintHood + 9274BD8D-CFD1-41C3-B35E-B13F55A758F4 + + Profile + 5E6C858F-0E22-4760-9AFE-EA3317B67173 + + ProgramData + 62AB5D82-FDC1-4DC3-A9DD-070D1D495D97 + + ProgramFiles + 905E63B6-C1BF-494E-B29C-65B732D3D21A + + ProgramFilesCommon + F7F1ED05-9F6D-47A2-AAAE-29D317C6F066 + + ProgramFilesCommonX64 + 6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D + + ProgramFilesCommonX86 + DE974D24-D9C6-4D3E-BF91-F4455120B917 + + ProgramFilesX64 + 6D809377-6AF0-444B-8957-A3773F02200E + + ProgramFilesX86 + 7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E + + Programs + A77F5D77-2E2B-44C3-A6A2-ABA601054A51 + + Public + DFDF76A2-C82A-4D63-906A-5644AC457385 + + PublicDesktop + C4AA340D-F20F-4863-AFEF-F87EF2E6BA25 + + PublicDocuments + ED4824AF-DCE4-45A8-81E2-FC7965083634 + + PublicDownloads + 3D644C9B-1FB8-4F30-9B45-F670235F79C0 + + PublicGameTasks + DEBF2536-E1A8-4C59-B6A2-414586476AEA + + PublicMusic + 3214FAB5-9757-4298-BB61-92A9DEAA44FF + + PublicPictures + B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5 + + PublicVideos + 2400183A-6185-49FB-A2D8-4A392A602BA3 + + QuickLaunch + 52A4F021-7B75-48A9-9F6B-4B87A210BC8F + + Recent + AE50C081-EBD2-438A-8655-8A092E34987A + + RecordedTV + BD85E001-112E-431E-983B-7B15AC09FFF1 + + RecycleBin + B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC + + ResourceDir + 8AD10C31-2ADB-4296-A8F7-E4701232C972 + + RoamingAppData + 3EB685DB-65F9-4CF6-A03A-E3EF65729F3D + + SampleMusic + B250C668-F57D-4EE1-A63C-290EE7D1AA1F + + SamplePictures + C4900540-2379-4C75-844B-64E6FAF8716B + + SamplePlaylists + 15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5 + + SampleVideos + 859EAD94-2E85-48AD-A71A-0969CB56A6CD + + SavedGames + 4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4 + + SavedSearches + 7D1D3A04-DEBB-4115-95CF-2F29DA2920DA + + SEARCH_CSC + EE32E446-31CA-4ABA-814F-A5EBD2FD6D5E + + SEARCH_MAPI + 98EC0E18-2098-4D44-8644-66979315A281 + + SearchHome + 190337D1-B8CA-4121-A639-6D472D16972A + + SendTo + 8983036C-27C0-404B-8F08-102D10DCFD74 + + SidebarDefaultParts + 7B396E54-9EC5-4300-BE0A-2482EBAE1A26 + + SidebarParts + A75D362E-50FC-4FB7-AC2C-A8BEAA314493 + + StartMenu + 625B53C3-AB48-4EC1-BA1F-A1EF4146FC19 + + Startup + B97D20BB-F46A-4C97-BA10-5E3608430854 + + SyncManager + 43668BF8-C14E-49B2-97C9-747784D784B7 + + SyncResults + 289A9A43-BE44-4057-A41B-587A76D7E7F9 + + SyncSetup + 0F214138-B1D3-4A90-BBA9-27CBC0C5389A + + System + 1AC14E77-02E7-4E5D-B744-2EB1AE5198B7 + + SystemX86 + D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27 + + Templates + A63293E8-664E-48DB-A079-DF759E0509F7 + + TreeProperties + 5B3749AD-B49F-49C1-83EB-15370FBD4882 + + UserProfiles + 0762D272-C50A-4BB0-A382-697DCD729B80 + + UsersFiles + F3CE0F7C-4901-4ACC-8648-D5D44B04EF8F + + Videos + 18989B1D-99B5-455B-841C-AB7C74E4DDFC + + Windows + F38BF404-1D43-42F2-9305-67DE0B28FC23 + +## See also + +- +- [How To: Add a Custom Place to a File Dialog Box](how-to-add-a-custom-place-to-a-file-dialog-box.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/label-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/label-control-overview-windows-forms.md new file mode 100644 index 0000000000..92a225e335 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/label-control-overview-windows-forms.md @@ -0,0 +1,24 @@ +--- +title: "Label Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "Label" +helpviewer_keywords: + - "images [Windows Forms], displaying in labels" + - "labels" + - "Label control [Windows Forms], about Label control" +ms.assetid: dcad7f44-11b7-4c55-b0c0-d984ade43d7d +--- +# Label Control Overview (Windows Forms) +Windows Forms controls are used to display text or images that cannot be edited by the user. They are used to identify objects on a form — to provide a description of what a certain control will do if clicked, for example, or to display information in response to a run-time event or process in your application. 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. For example, if your application takes a few minutes to process a change, you can display a processing-status message in a label. + +## Working with the Label Control + Because the control cannot receive the focus, it can also be used to create access keys for other controls. An access key allows a user to select the other control by pressing the ALT key with the access key. For more information, see [Creating Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md) and [How to: Create Access Keys with Windows Forms Label Controls](how-to-create-access-keys-with-windows-forms-label-controls.md). + + 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-text-displayed-by-a-windows-forms-control.md). + +## See also + +- +- [How to: Size a Windows Forms Label Control to Fit Its Contents](how-to-size-a-windows-forms-label-control-to-fit-its-contents.md) +- [How to: Create Access Keys with Windows Forms Label Controls](how-to-create-access-keys-with-windows-forms-label-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/label-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/label-control-windows-forms.md new file mode 100644 index 0000000000..3579203cdd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/label-control-windows-forms.md @@ -0,0 +1,32 @@ +--- +title: "Label Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Label control [Windows Forms]" + - "labels" + - "LinkLabel control [Windows Forms]" +ms.assetid: 2028bbe3-ffe2-43e8-8ae3-dec759d2ecec +--- +# Label Control (Windows Forms) +> [!IMPORTANT] +> The control replaces and adds functionality to the control. You can use the with other new controls such as the . However, the control is retained for both backward compatibility and future use, if you choose. + + Windows Forms controls are used to display text or images that cannot be edited by the user. They are used to identify objects on a form—to provide a description of what a certain control will do if clicked, for example, or to display information in response to a run-time event or process in your application. Because the control cannot receive focus, it can also be used to create access keys for other controls. + +## In This Section + [Label Control Overview](label-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Create Access Keys with Windows Forms Label Controls](how-to-create-access-keys-with-windows-forms-label-controls.md) + Describes how to use a label to define an access key for another control. + + [How to: Size a Windows Forms Label Control to Fit Its Contents](how-to-size-a-windows-forms-label-control-to-fit-its-contents.md) + Explains adjusting the size of a label control for its caption. + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md b/dotnet-desktop-guide/framework/winforms/controls/labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md new file mode 100644 index 0000000000..4da9830081 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md @@ -0,0 +1,32 @@ +--- +title: Label Controls and Provide Shortcuts +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], access keys" + - "shortcuts [Windows Forms], controls" + - "keyboard shortcuts [Windows Forms], controls" + - "Windows Forms controls, labels" +ms.assetid: 6eaf868c-819f-4131-8f59-048e20c286f7 +--- +# Label individual Windows Forms controls and provide shortcuts + +Controls added to Windows Forms have properties and methods that are used to further specialize the user experience. Customizing your user interface to suit the needs of the user is extremely important for well-designed Windows applications. + +## In this section + +[How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md)\ +Describes how to assign a text label to a control. + +[How to: Set the Image Displayed by a Windows Forms Control](how-to-set-the-image-displayed-by-a-windows-forms-control.md)\ +Explains how to configure a control to display images. + +[How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md)\ +Gives information about creating predefined keyboard shortcuts. + +[Providing Accessibility Information for Controls on a Windows Form](providing-accessibility-information-for-controls-on-a-windows-form.md)\ +Gives information about enabling your controls to work with accessibility aids. + +## Related sections + +[Windows Forms Controls](index.md)\ +Links to other basic things you can do with controls. diff --git a/dotnet-desktop-guide/framework/winforms/controls/layout-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/layout-in-windows-forms-controls.md new file mode 100644 index 0000000000..7929207e91 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/layout-in-windows-forms-controls.md @@ -0,0 +1,46 @@ +--- +title: Layout of controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "layout [Windows Forms]" + - "sizing [Windows Forms], automatic [Windows Forms]" + - "Margin property [Windows Forms]" + - "Padding property [Windows Forms]" +ms.assetid: 99400e3a-720e-4f56-b68f-89df911a251c +--- + +# Layout in Windows Forms Controls + +Precise placement of controls on your form is a high priority for many applications. The namespace gives you many layout tools to accomplish this. + +## In This Section + +[AutoSize Property Overview](autosize-property-overview.md)\ +Describes the property and its role in layout. + +[Margin and Padding in Windows Forms Controls](margin-and-padding-in-windows-forms-controls.md)\ +Describes the and properties and their roles in layout. + +[How to: Align a Control to the Edges of Forms](how-to-align-a-control-to-the-edges-of-forms.md)\ +Demonstrates how to use the property to align your control to the edge of the form it occupies. + +[How to: Create a Border Around a Windows Forms Control Using Padding](how-to-create-a-border-around-a-windows-forms-control-using-padding.md)\ +Demonstrates how to use the property to outline a control. + +[How to: Implement a Custom Layout Engine](how-to-implement-a-custom-layout-engine.md)\ +Demonstrates how to implement a for arranging Windows Forms controls. + +## Reference + +\ +Provides reference documentation for the control. + +\ +Provides reference documentation for the control. + +## See also + +- [How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md) +- [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) +- [How to: Design a Windows Forms Layout that Responds Well to Localization](how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md) +- [AutoSize Behavior in the TableLayoutPanel Control](autosize-behavior-in-the-tablelayoutpanel-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/limitations-of-the-timer-component-interval-property.md b/dotnet-desktop-guide/framework/winforms/controls/limitations-of-the-timer-component-interval-property.md new file mode 100644 index 0000000000..520e2ae069 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/limitations-of-the-timer-component-interval-property.md @@ -0,0 +1,29 @@ +--- +title: Limitations of Timer Component Interval Property +ms.date: "03/30/2017" +helpviewer_keywords: + - "timers [Windows Forms], event intervals" + - "Interval property [Windows Forms], limitations" + - "timers [Windows Forms], Windows-based" + - "Timer component [Windows Forms], limitations of Interval property" +ms.assetid: 7e5fb513-77e7-4046-a8e8-aab94e61ca0f +--- +# Limitations of the Windows Forms Timer Component's Interval Property +The Windows Forms component has an property that specifies the number of milliseconds that pass between one timer event and the next. Unless the component is disabled, a timer continues to receive the event at roughly equal intervals of time. + + This component is designed for a Windows Forms environment. If you need a timer that is suitable for a server environment, see [Introduction to Server-Based Timers](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/tb9yt5e6(v=vs.90)). + +## The Interval Property + The property has a few limitations to consider when you are programming a component: + +- If your application or another application is making heavy demands on the system — such as long loops, intensive calculations, or drive, network, or port access — your application may not get timer events as often as the property specifies. + +- The interval is not guaranteed to elapse exactly on time. To ensure accuracy, the timer should check the system clock as needed, rather than try to keep track of accumulated time internally. + +- The precision of the property is in milliseconds. Some computers provide a high-resolution counter that has a resolution higher than milliseconds. The availability of such a counter depends on the processor hardware of your computer. + +## See also + +- +- [Timer Component](timer-component-windows-forms.md) +- [Timer Component Overview](timer-component-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/link-to-an-object-or-web-page-with-wf-linklabel-control.md b/dotnet-desktop-guide/framework/winforms/controls/link-to-an-object-or-web-page-with-wf-linklabel-control.md new file mode 100644 index 0000000000..1d3bc0ed0b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/link-to-an-object-or-web-page-with-wf-linklabel-control.md @@ -0,0 +1,183 @@ +--- +title: Link to an Object or Web Page with LinkLabel Control +description: Learn how to create Web-style links to an object or web page with the Windows Forms LinkLabel control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], LinkLabel control" + - "Windows Forms, linking to objects" + - "Web page link control" + - "linking [Windows Forms], to other forms" + - "Windows Forms, linking to Web pages" + - "links [Windows Forms], to other forms" + - "LinkLabel control [Windows Forms], linking to object or Web page" + - "LinkLabel control [Windows Forms], examples" +ms.assetid: 6c91c975-3cb7-4504-82f0-fc6255f8fb85 +--- +# How to: Link to an Object or Web Page with the Windows Forms LinkLabel Control + +The Windows Forms control allows you to create Web-style links on your form. When the link is clicked, you can change its color to indicate the link has been visited. For more information on changing the color, see [How to: Change the Appearance of the Windows Forms LinkLabel Control](how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md). + +## Linking to Another Form + +#### To link to another form with a LinkLabel control + +1. Set the property to an appropriate caption. + +2. Set the property to determine which part of the caption will be indicated as a link. How it is indicated depends on the appearance-related properties of the link label. The value is represented by a object containing two numbers, the starting character position and the number of characters. The property can be set in the Properties window or in code in a manner similar to the following: + + ```vb + ' In this code example, the link area has been set to begin + ' at the first character and extend for eight characters. + ' You may need to modify this based on the text entered in Step 1. + LinkLabel1.LinkArea = New LinkArea(0, 8) + ``` + + ```csharp + // In this code example, the link area has been set to begin + // at the first character and extend for eight characters. + // You may need to modify this based on the text entered in Step 1. + linkLabel1.LinkArea = new LinkArea(0,8); + ``` + + ```cpp + // In this code example, the link area has been set to begin + // at the first character and extend for eight characters. + // You may need to modify this based on the text entered in Step 1. + linkLabel1->LinkArea = LinkArea(0,8); + ``` + +3. In the event handler, invoke the method to open another form in the project, and set the property to `true`. + + > [!NOTE] + > An instance of the class carries a reference to the control that was clicked, so there is no need to cast the `sender` object. + + ```vb + Protected Sub LinkLabel1_LinkClicked(ByVal Sender As System.Object, _ + ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ + Handles LinkLabel1.LinkClicked + ' Show another form. + Dim f2 As New Form() + f2.Show + LinkLabel1.LinkVisited = True + End Sub + ``` + + ```csharp + protected void linkLabel1_LinkClicked(object sender, System. Windows.Forms.LinkLabelLinkClickedEventArgs e) + { + // Show another form. + Form f2 = new Form(); + f2.Show(); + linkLabel1.LinkVisited = true; + } + ``` + + ```cpp + private: + void linkLabel1_LinkClicked(System::Object ^ sender, + System::Windows::Forms::LinkLabelLinkClickedEventArgs ^ e) + { + // Show another form. + Form ^ f2 = new Form(); + f2->Show(); + linkLabel1->LinkVisited = true; + } + ``` + +## Linking to a Web Page + +The control can also be used to display a Web page with the default browser. + +#### To start Internet Explorer and link to a Web page with a LinkLabel control + +1. Set the property to an appropriate caption. + +2. Set the property to determine which part of the caption will be indicated as a link. + +3. In the event handler, in the midst of an exception-handling block, call a second procedure that sets the property to `true` and uses the method to start the default browser with a URL. To use the method you need to add a reference to the namespace. + + > [!IMPORTANT] + > If the code below is run in a partial-trust environment (such as on a shared drive), the JIT compiler fails when the `VisitLink` method is called. The `System.Diagnostics.Process.Start` statement causes a link demand that fails. By catching the exception when the `VisitLink` method is called, the code below ensures that if the JIT compiler fails, the error is handled gracefully. + + ```vb + Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _ + ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ + Handles LinkLabel1.LinkClicked + Try + VisitLink() + Catch ex As Exception + ' The error message + MessageBox.Show("Unable to open link that was clicked.") + End Try + End Sub + + Sub VisitLink() + ' Change the color of the link text by setting LinkVisited + ' to True. + LinkLabel1.LinkVisited = True + ' Call the Process.Start method to open the default browser + ' with a URL: + System.Diagnostics.Process.Start("http://www.microsoft.com") + End Sub + ``` + + ```csharp + private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) + { + try + { + VisitLink(); + } + catch (Exception ex ) + { + MessageBox.Show("Unable to open link that was clicked."); + } + } + + private void VisitLink() + { + // Change the color of the link text by setting LinkVisited + // to true. + linkLabel1.LinkVisited = true; + //Call the Process.Start method to open the default browser + //with a URL: + System.Diagnostics.Process.Start("http://www.microsoft.com"); + } + ``` + + ```cpp + private: + void linkLabel1_LinkClicked(System::Object ^ sender, + System::Windows::Forms::LinkLabelLinkClickedEventArgs ^ e) + { + try + { + VisitLink(); + } + catch (Exception ^ ex) + { + MessageBox::Show("Unable to open link that was clicked."); + } + } + private: + void VisitLink() + { + // Change the color of the link text by setting LinkVisited + // to true. + linkLabel1->LinkVisited = true; + // Call the Process.Start method to open the default browser + // with a URL: + System::Diagnostics::Process::Start("http://www.microsoft.com"); + } + ``` + +## See also + +- +- [LinkLabel Control Overview](linklabel-control-overview-windows-forms.md) +- [How to: Change the Appearance of the Windows Forms LinkLabel Control](how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md) +- [LinkLabel Control](linklabel-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/linklabel-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/linklabel-control-overview-windows-forms.md new file mode 100644 index 0000000000..7a814246e7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/linklabel-control-overview-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "LinkLabel Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "LinkLabel" +helpviewer_keywords: + - "links [Windows Forms], LinkLabel control" + - "Label control [Windows Forms], about Label control" + - "LinkLabel control [Windows Forms], about LinkLabel control" +ms.assetid: 9e248549-10ca-43a3-bb5e-60f583d369f1 +--- +# LinkLabel Control Overview (Windows Forms) +The Windows Forms control allows you to add Web-style links to Windows Forms applications. You can use the control for everything that you can use the control for; you can also set part of the text as a link to a file, folder, or Web page. + +## What You Can Do with the LinkLabel Control + In addition to all the properties, methods, and events of the control, the control has properties for hyperlinks and link colors. The property sets the area of the text that activates the link. The , , and properties set the colors of the link. The event determines what happens when the link text is selected. + + The simplest use of the control is to display a single link using the property, but you can also display multiple hyperlinks using the property. The property enables you to access a collection of links. You can also specify data in the property of each individual object. The value of the property can be used to store the location of a file to display or the address of a Web site. + +## See also + +- +- [Label Control Overview](label-control-overview-windows-forms.md) +- [How to: Link to an Object or Web Page with the Windows Forms LinkLabel Control](link-to-an-object-or-web-page-with-wf-linklabel-control.md) +- [How to: Change the Appearance of the Windows Forms LinkLabel Control](how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/linklabel-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/linklabel-control-windows-forms.md new file mode 100644 index 0000000000..3640d562c3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/linklabel-control-windows-forms.md @@ -0,0 +1,34 @@ +--- +title: "LinkLabel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Label control [Windows Forms]" + - "links [Windows Forms], adding to Windows Forms" + - "Windows Forms, adding links" + - "Web page link control" + - "LinkLabel control [Windows Forms]" +ms.assetid: af1fd04e-e126-4fd7-9a4e-13b49010c5ca +--- +# LinkLabel Control (Windows Forms) +The Windows Forms `LinkLabel` control enables you to add Web-style links to Windows Forms applications. You can use the `LinkLabel` control for everything that you can use the control for; you can also set part of the text as a link to an object or Web page. + +## In This Section + [LinkLabel Control Overview](linklabel-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Change the Appearance of the Windows Forms LinkLabel Control](how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md) + Lists ways to specify the color and underlining of Web-style links in link labels. + + [How to: Link to an Object or Web Page with the Windows Forms LinkLabel Control](link-to-an-object-or-web-page-with-wf-linklabel-control.md) + Provides how-to instructions for opening a form or Web page when a link is clicked. + + [How to: Display a Web Page from a Windows Forms LinkLabel Control (Visual Basic)](display-a-web-page-from-a-wf-linklabel-control-visual-basic.md) + Shows how to display a Web page in the default browser when a user clicks a Windows Forms `LinkLabel` control. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information about their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/listbox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/listbox-control-overview-windows-forms.md new file mode 100644 index 0000000000..bcd8c104a8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/listbox-control-overview-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "ListBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ListBox" +helpviewer_keywords: + - "list boxes [Windows Forms], about list boxes" + - "ListBox control [Windows Forms], about ListBox control" +ms.assetid: 37ea226b-6fc8-4c70-936a-c6af4e0cad4c +--- +# ListBox Control Overview (Windows Forms) +A Windows Forms control displays a list from which the user can select one or more items. If the total number of items exceeds the number that can be displayed, a scroll bar is automatically added to the control. When the property is set to `true`, the list box displays items in multiple columns and a horizontal scroll bar appears. When the property is set to `false`, the list box displays items in a single column and a vertical scroll bar appears. When is set to `true`, the scroll bar appears regardless of the number of items. The property determines how many list items can be selected at a time. + +## Ways to Change the ListBox Control + The property returns an integer value that corresponds to the first selected item in the list box. You can programmatically change the selected item by changing the value in code; the corresponding item in the list will appear highlighted on the Windows Form. If no item is selected, the value is -1. If the first item in the list is selected, the value is 0. When multiple items are selected, the value reflects the selected item that appears first in the list. The property is similar to , but returns the item itself, usually a string value. The property reflects the number of items in the list, and the value of the property is always one more than the largest possible value because is zero-based. + + To add or delete items in a control, use the , , or method. Alternatively, you can add items to the list by using the property at design time. + +## See also + +- +- [How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control](add-and-remove-items-from-a-wf-combobox.md) +- [How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control](sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md) +- [How to: Bind a Windows Forms ComboBox or ListBox Control to Data](how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md) +- [ComboBox Control Overview](combobox-control-overview-windows-forms.md) +- [CheckedListBox Control Overview](checkedlistbox-control-overview-windows-forms.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) +- [How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control](create-a-lookup-table-for-a-wf-combobox-listbox.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/listbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/listbox-control-windows-forms.md new file mode 100644 index 0000000000..6a06d55272 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/listbox-control-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "ListBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ListBox control [Windows Forms]" + - "list controls [Windows Forms], Windows Forms" + - "list box controls" + - "list boxes [Windows Forms], Windows Forms controls" + - "list items [Windows Forms], Windows Forms controls that display" + - "list boxes" +ms.assetid: b0172473-c5f2-411e-aaa4-c8f17cb5eed4 +--- +# ListBox Control (Windows Forms) +A Windows Forms `ListBox` control displays a list of items from which the user can select one or more. + +## In This Section + [ListBox Control Overview](listbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) + Provides a list of things you can do with list boxes, combo boxes, and checked list boxes. diff --git a/dotnet-desktop-guide/framework/winforms/controls/listview-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/listview-control-overview-windows-forms.md new file mode 100644 index 0000000000..b4a9d5b141 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/listview-control-overview-windows-forms.md @@ -0,0 +1,57 @@ +--- +title: "ListView Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ListView" +helpviewer_keywords: + - "lists" + - "ListView control [Windows Forms], about ListView control" + - "list views" +ms.assetid: c9ef56c1-3bb1-4101-9f4e-e95e720f2756 +--- +# ListView Control Overview (Windows Forms) +The Windows Forms control displays a list of items with icons. You can use a list view to create a user interface like the right pane of Windows Explorer. The control has four view modes: LargeIcon, SmallIcon, List, and Details. + +## What You Can Do with the ListView Control + +> [!NOTE] +> An additional view mode, Tile, is only available on Windows XP and the Windows Server 2003 operating system. For more information, see [How to: Enable Tile View in a Windows Forms ListView Control](how-to-enable-tile-view-in-a-windows-forms-listview-control.md). + + The LargeIcon mode displays large icons next to the item text; the items appear in multiple columns if the control is large enough. The SmallIcon mode is the same except that it displays small icons. The List mode displays small icons but is always in a single column. The Details mode displays items in multiple columns. For details, see [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md). The view mode is determined by the property. All of the view modes can display images from image lists. For details, see [How to: Display Icons for the Windows Forms ListView Control](how-to-display-icons-for-the-windows-forms-listview-control.md). + + The following table lists some of the members and the views they are valid in. + +|ListView member|View| +|---------------------|----------| +| property| or | +| property| or | +| method|| +| property| or | +| event|| +| method|, , or | +| method| or | +| method| or | +| property|All views except | +| property|.| +| property|, , or | + + The key property of the control is , which contains the items displayed by the control. The property contains a collection of the items currently selected in the control. The user can select multiple items, for example to drag and drop several items at a time to another control, if the property is set to `true`. The control can display check boxes next to the items, if the property is set to `true`. + + The property determines what type of action the user must take to activate an item in the list: the options are , , and . activation requires a single click to activate the item. activation requires the user to double-click to activate the item; a single click changes the color of the item text. activation requires the user to double-click to activate an item, but the item does not change appearance. + + The control also supports the visual styles and other features available on the Windows XP platform, including grouping, tile view, and insertion marks. + +## See also + +- +- [ListView Control](listview-control-windows-forms.md) +- [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) +- [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md) +- [How to: Display Icons for the Windows Forms ListView Control](how-to-display-icons-for-the-windows-forms-listview-control.md) +- [How to: Display Subitems in Columns with the Windows Forms ListView Control](how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md) +- [How to: Select an Item in the Windows Forms ListView Control](how-to-select-an-item-in-the-windows-forms-listview-control.md) +- [How to: Group Items in a Windows Forms ListView Control](how-to-group-items-in-a-windows-forms-listview-control.md) +- [How to: Display an Insertion Mark in a Windows Forms ListView Control](how-to-display-an-insertion-mark-in-a-windows-forms-listview-control.md) +- [How to: Add Search Capabilities to a ListView Control](how-to-add-search-capabilities-to-a-listview-control.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) +- [How to: Create a Multipane User Interface with Windows Forms](how-to-create-a-multipane-user-interface-with-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/listview-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/listview-control-windows-forms.md new file mode 100644 index 0000000000..1d5a8fec3a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/listview-control-windows-forms.md @@ -0,0 +1,75 @@ +--- +title: "ListView Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "lists" + - "checked list items [Windows Forms], Windows Forms controls" + - "user interface [Windows Forms], creating" + - "lists [Windows Forms], items with icons" + - "icons [Windows Forms], listing with items" + - "list views" + - "ListView control [Windows Forms]" + - "list controls [Windows Forms], List view" +ms.assetid: 9f71cf5c-82da-488a-a04e-ef52c0817187 +--- +# ListView Control (Windows Forms) +The Windows Forms `ListView` control displays a list of items with icons. You can use a list view to create a user interface like the right pane of Windows Explorer. + +## In This Section + [ListView Control Overview](listview-control-overview-windows-forms.md) + Describes this control and its key features and properties. + + [How to: Add and Remove Items with the Windows Forms ListView Control](how-to-add-and-remove-items-with-the-windows-forms-listview-control.md) + Describes how to add or remove items from a list view. + + [How to: Add Columns to the Windows Forms ListView Control](how-to-add-columns-to-the-windows-forms-listview-control.md) + Describes how to create columns in order to display information about each list item. + + [How to: Display Icons for the Windows Forms ListView Control](how-to-display-icons-for-the-windows-forms-listview-control.md) + Describes how to associate a list view with an appropriate image list for displaying large or small icons. + + [How to: Display Subitems in Columns with the Windows Forms ListView Control](how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md) + Describes how to display information about each list item in columns. + + [How to: Select an Item in the Windows Forms ListView Control](how-to-select-an-item-in-the-windows-forms-listview-control.md) + Describes how to programmatically select an item. + + [How to: Group Items in a Windows Forms ListView Control](how-to-group-items-in-a-windows-forms-listview-control.md) + Describes how to create groups for categorized display and how to assign items to each group. + + [How to: Enable Tile View in a Windows Forms ListView Control](how-to-enable-tile-view-in-a-windows-forms-listview-control.md) + Describes how to display items as tiles, each of which is comprised of a large icon and multiple lines of text. + + [How to: Display an Insertion Mark in a Windows Forms ListView Control](how-to-display-an-insertion-mark-in-a-windows-forms-listview-control.md) + Describes how to implement user-feedback for drag-and-drop operations in which an insertion mark indicates the drop location for each mouse-pointer position. + + [How to: Add Search Capabilities to a ListView Control](how-to-add-search-capabilities-to-a-listview-control.md) + Describes how to programmatically find an item using either text search or screen coordinates. + +- [How to: Enable Tile View in a Windows Forms ListView Control Using the Designer](enable-tile-view-in-a-wf-listview-control-using-the-designer.md) + +- [How to: Add and Remove Items with the Windows Forms ListView Control Using the Designer](add-and-remove-items-with-wf-listview-control-using-the-designer.md) + +- [How to: Add Columns to the Windows Forms ListView Control Using the Designer](how-to-add-columns-to-the-windows-forms-listview-control-using-the-designer.md) + +- [How to: Group Items in a Windows Forms ListView Control Using the Designer](how-to-group-items-in-a-windows-forms-listview-control-using-the-designer.md) + +- [Walkthrough: Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer](creating-an-explorer-style-interface-with-the-listview-and-treeview.md) + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) + Describes how to inherit from an item in a list view or a node in a tree view in order to add any fields, methods, or constructors you need. + + [ImageList Component](imagelist-component-windows-forms.md) + Explains what an image list is and its key features and properties. + + [How to: Create a Multipane User Interface with Windows Forms](how-to-create-a-multipane-user-interface-with-windows-forms.md) + Gives instructions for laying out a Windows Form with multiple panes. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/load-save-and-cancel-bindingnavigator.md b/dotnet-desktop-guide/framework/winforms/controls/load-save-and-cancel-bindingnavigator.md new file mode 100644 index 0000000000..688ea2a406 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/load-save-and-cancel-bindingnavigator.md @@ -0,0 +1,114 @@ +--- +title: Add Load, Save, and Cancel Buttons to BindingNavigator Control +description: Learn how to add Load, Save, and Cancel buttons to the Windows Forms BindingNavigator control. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], manipulating" + - "BindingNavigator control [Windows Forms], adding buttons" +ms.assetid: faa33042-186e-4bb2-8798-17ceb987ec62 +--- +# How to: Add Load, Save, and Cancel Buttons to the Windows Forms BindingNavigator Control + +The control is a special-purpose control that is intended for navigating and manipulating controls on your form that are bound to data. + +Because it's a control, the component can be easily modified to include additional or alternative commands for the user. + +In the following procedure, a control is bound to data, and the control that is added to the form is modified to include load, save, and cancel buttons. + +## Add load, save, and cancel buttons to the BindingNavigator component + +1. In Visual Studio, add a control to your form. + +2. Bind it to a , which is bound to a data source. For this example, the is bound to a database. + +3. After the dataset and table adapter are generated, drag a control to the form. + +4. Set the control's property to the on the form that is bound to the controls. + +5. Select the control. + +6. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) so the **BindingNavigator Tasks** dialog appears and select **Edit Items**. + + The **Items Collection Editor** appears. + +7. In the **Items Collection Editor**, complete the following: + + 1. Add a and three items by selecting the appropriate type of and clicking the **Add** button. + + 2. Set the property of the buttons to **LoadButton**, **SaveButton**, and **CancelButton**, respectively. + + 3. Set the property of the buttons to **Load**, **Save**, and **Cancel**. + + 4. Set the property for each of the buttons to **Text**. Alternatively, you can set this property to **Image** or **ImageAndText**, and set the image to be displayed in the property. + + 5. Click **OK** to close the dialog box. The buttons are added to the . + +8. Right-click the form and choose **View Code**. + +9. In the Code Editor, find the line of code that loads data into the table adapter. This code was generated when you set up the data binding in step 2. The code should be similar to the following: `TableAdapterName.Fill(DataSetName.TableName)`. It will most likely be in the form's event. + +10. Create an event handler for the event of the **Load** you created earlier and move this data-loading code into it. + + Your code should now look similar to the following: + + ```vb + Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadButton.Click + TableAdapterName.Fill(DataSetName.TableName) + End Sub + ``` + + ```csharp + private void LoadButton_Click(System.Object sender, + System.EventArgs e) + { + TableAdapterName.Fill(DataSetName.TableName); + } + ``` + +11. Create an event handler for the event of the **Save** you created earlier and write code to update the data within the table the control is bound to. + + ```vb + Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click + TableAdapterName.Update(DataSetName.TableName) + End Sub + ``` + + ```csharp + private void SaveButton_Click(System.Object sender, + System.EventArgs e) + { + TableAdapterName.Update(DataSetName.TableName); + } + ``` + + > [!NOTE] + > In some cases, the component already has a **Save** button, but no code has been generated by the Windows Forms Designer. In this case, you can place the preceding code in the event handler for that button, rather than creating an entirely new button on the . However, the button is disabled by default, so you must set the property of the button to `true` to have the button function correctly. + +12. Create an event handler for the event of the **Cancel** you created earlier and write code to cancel any changes to the data record that is displayed. + + ```vb + Private Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CancelButton.Click + BindingSourceName.CancelEdit() + End Sub + ``` + + ```csharp + private void CancelButton_Click(System.Object sender, System.EventArgs e) + { + BindingSourceName.CancelEdit(); + } + ``` + + > [!NOTE] + > The method is scoped to the row of data. Save any changes you make while viewing that individual record before navigating to the next record. + +## See also + +- +- +- +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) +- [BindingSource Component Overview](bindingsource-component-overview.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/mainmenu-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/mainmenu-component-overview-windows-forms.md new file mode 100644 index 0000000000..44e717f010 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/mainmenu-component-overview-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "MainMenu Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "MenuItem" + - "MainMenu" +helpviewer_keywords: + - "MainMenu control [Windows Forms], about MainMenu control" + - "menus" +ms.assetid: b41cc5a3-cc59-4996-aa3c-8dd9c17d3c90 +--- +# MainMenu Component Overview (Windows Forms) +> [!IMPORTANT] +> Although and replace and add functionality to the and controls of previous versions, and are retained for both backward compatibility and future use if you choose. + + The Windows Forms component displays a menu at run time. All submenus of the main menu and individual items are objects. + +## Key Properties + A menu item can be designated as the default item by setting the property to `true`. The default item appears in bold text when the menu is clicked. The menu item's property is either `true` or `false`, and indicates whether the menu item is selected. The menu item's property customizes the appearance of the selected item: if is set to `true`, a radio button appears next to the item; if is set to `false`, a check mark appears next to the item. + +## See also + +- +- +- +- +- +- [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/mainmenu-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/mainmenu-component-windows-forms.md new file mode 100644 index 0000000000..17300f6069 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/mainmenu-component-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "MainMenu Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "MainMenu control [Windows Forms]" +ms.assetid: 7cd22f29-828b-42e8-9c88-f08aa4533850 +--- +# MainMenu Component (Windows Forms) +> [!NOTE] +> Although `MenuStrip` and `ContextMenuStrip` replace and add functionality to the `MainMenu` and controls of previous versions, `MainMenu` and are retained for both backward compatibility and future use if you choose. + + The Windows Forms `MainMenu` component displays a menu at run time. + +## In This Section + [MainMenu Component Overview](mainmenu-component-overview-windows-forms.md) + Explains what this component is and its key features and properties. + +## Reference + + Describes this class and has links to all its members. + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/make-columns-read-only-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/make-columns-read-only-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..2b0082e605 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/make-columns-read-only-in-the-datagrid-using-the-designer.md @@ -0,0 +1,34 @@ +--- +title: Make Columns Read-Only in DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, columns" + - "DataGridView control [Windows Forms], read-only columns" + - "data [Windows Forms], displaying" + - "columns [Windows Forms], read-only" +ms.assetid: b4ef7a75-ab33-4ee3-b2cf-201530e454e9 +--- +# How to: Make Columns Read-Only in the Windows Forms DataGridView Control Using the Designer +By default, users can modify text and numerical data displayed in the Windows Forms control. If you want to display data that is not meant for modification, you must make the columns that contain the data read-only. For information about how to make the control entirely read-only, see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer](prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md). + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To make a column read-only by using the designer + +1. Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then select **Edit Columns**. + +2. Select a column from the **Selected Columns** list. + +3. In the **Column Properties** grid, set the property to `true`. + + > [!NOTE] + > You can also make a column read-only when you add it by selecting the **Read Only** check box in the **Add Column** dialog box. + +## See also + +- +- +- [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md) +- [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer](prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/margin-and-padding-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/margin-and-padding-in-windows-forms-controls.md new file mode 100644 index 0000000000..c7adcf7f65 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/margin-and-padding-in-windows-forms-controls.md @@ -0,0 +1,32 @@ +--- +title: Margin and Padding in Controls +description: Learn how to add margins and padding in Windows Form controls with the Margin and Padding properties. +ms.date: "03/30/2017" +helpviewer_keywords: + - "Padding property [Windows Forms]" + - "layout [Windows Forms], margins and padding" + - "Windows Forms, layout" + - "Margin property [Windows Forms]" +ms.assetid: 3781b5a1-3085-4072-bed0-44670c23ffdc +--- +# Margin and Padding in Windows Forms Controls +Precise placement of controls on your form is a high priority for many applications. The namespace gives you many layout features to accomplish this. Two of the most important are the and properties. + + The property defines the space around the control that keeps other controls a specified distance from the control's borders. + + The property defines the space in the interior of a control that keeps the control's content (for example, the value of its property) a specified distance from the control's borders. + + The following illustration shows the and properties on a control. + + ![Padding And Margin for Windows Forms Controls](./media/vs-winformpadmargin.gif "VS_WinFormPadMargin") + + There is design-time support for this feature in Visual Studio. Also see [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md). + +## See also + +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/maskedtextbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/maskedtextbox-control-windows-forms.md new file mode 100644 index 0000000000..3cb3a8fe45 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/maskedtextbox-control-windows-forms.md @@ -0,0 +1,29 @@ +--- +title: "MaskedTextBox Control" +ms.date: "03/30/2017" +f1_keywords: + - "MaskedTextBox" +helpviewer_keywords: + - "MaskedTextBox control [Windows Forms]" + - "user input [Windows Forms], validating in Windows Forms" + - "validating user input [Windows Forms], Windows Forms" + - "text boxes [Windows Forms], validating user input" +ms.assetid: 235d6121-027d-481d-8d59-4f6794d15d0c +--- +# MaskedTextBox Control (Windows Forms) +This topic links to others about the `MaskedTextBox` control. + +## In This Section + [Walkthrough: Working with the MaskedTextBox Control](walkthrough-working-with-the-maskedtextbox-control.md) + Demonstrates the key features of the `MaskedTextBox` control. + + [How to: Bind Data to the MaskedTextBox Control](how-to-bind-data-to-the-maskedtextbox-control.md) + Demonstrates how to reformat the data when data in the database does not match the format expected by your mask definition. + +## Reference + + The primary class for the implementation of the masked text box control. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/bindingnavigator-control-overview-windows-forms/bindingnavigator-control-form.gif b/dotnet-desktop-guide/framework/winforms/controls/media/bindingnavigator-control-overview-windows-forms/bindingnavigator-control-form.gif new file mode 100644 index 0000000000..3dc2b09f8c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/bindingnavigator-control-overview-windows-forms/bindingnavigator-control-form.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-inheritance-diagram.gif b/dotnet-desktop-guide/framework/winforms/controls/media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-inheritance-diagram.gif new file mode 100644 index 0000000000..4711fa0ee1 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-inheritance-diagram.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-value-inheritance-diagram.gif b/dotnet-desktop-guide/framework/winforms/controls/media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-value-inheritance-diagram.gif new file mode 100644 index 0000000000..e0b6d5ea7e Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/cell-styles-in-the-windows-forms-datagridview-control/datagridviewcells-value-inheritance-diagram.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/creating-a-wf-control-design-time-features/demo-marquee-control.gif b/dotnet-desktop-guide/framework/winforms/controls/media/creating-a-wf-control-design-time-features/demo-marquee-control.gif new file mode 100644 index 0000000000..16bb1fe3af Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/creating-a-wf-control-design-time-features/demo-marquee-control.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/datagrid-bound-multiple-tables.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/datagrid-bound-multiple-tables.gif new file mode 100644 index 0000000000..b12753a0f6 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/datagrid-bound-multiple-tables.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/show-hide-parent-rows.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/show-hide-parent-rows.gif new file mode 100644 index 0000000000..648cf51abf Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/show-hide-parent-rows.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/visual-basic-columns.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/visual-basic-columns.gif new file mode 100644 index 0000000000..b65350e840 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagrid-control-overview-windows-forms/visual-basic-columns.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewcell-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewcell-object-model.gif new file mode 100644 index 0000000000..006da4ba23 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewcell-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewcolumn-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewcolumn-object-model.gif new file mode 100644 index 0000000000..82971dc8e2 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewcolumn-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewediting-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewediting-object-model.gif new file mode 100644 index 0000000000..c975d75283 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewediting-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewelement-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewelement-object-model.gif new file mode 100644 index 0000000000..67b9ad8086 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewelement-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewrow-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewrow-object-model.gif new file mode 100644 index 0000000000..8b7dfb2fce Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/datagridview-control-architecture-windows-forms/datagridviewrow-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/designer-actions-glyph.gif b/dotnet-desktop-guide/framework/winforms/controls/media/designer-actions-glyph.gif new file mode 100644 index 0000000000..fe17769d2b Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/designer-actions-glyph.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/enable-tile-view-in-a-wf-listview-control-using-the-designer/tile-view-in-listview-control.gif b/dotnet-desktop-guide/framework/winforms/controls/media/enable-tile-view-in-a-wf-listview-control-using-the-designer/tile-view-in-listview-control.gif new file mode 100644 index 0000000000..f0c57c7fd3 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/enable-tile-view-in-a-wf-listview-control-using-the-designer/tile-view-in-listview-control.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/errorprovider-component-overview-windows-forms/vb-error-provider-icon.gif b/dotnet-desktop-guide/framework/winforms/controls/media/errorprovider-component-overview-windows-forms/vb-error-provider-icon.gif new file mode 100644 index 0000000000..f66f1bdcf8 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/errorprovider-component-overview-windows-forms/vb-error-provider-icon.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control/listview-insertion-mark.gif b/dotnet-desktop-guide/framework/winforms/controls/media/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control/listview-insertion-mark.gif new file mode 100644 index 0000000000..e78c983451 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/how-to-display-an-insertion-mark-in-a-windows-forms-listview-control/listview-insertion-mark.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/how-to-enable-tile-view-in-a-windows-forms-listview-control/tile-view-in-listview-control.gif b/dotnet-desktop-guide/framework/winforms/controls/media/how-to-enable-tile-view-in-a-windows-forms-listview-control/tile-view-in-listview-control.gif new file mode 100644 index 0000000000..f0c57c7fd3 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/how-to-enable-tile-view-in-a-windows-forms-listview-control/tile-view-in-listview-control.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer/odd-even-list-view-groups.gif b/dotnet-desktop-guide/framework/winforms/controls/media/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer/odd-even-list-view-groups.gif new file mode 100644 index 0000000000..c932dcfd94 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/how-to-group-items-in-a-windows-forms-listview-control-using-the-designer/odd-even-list-view-groups.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/net-bindsrcdatabindarch.gif b/dotnet-desktop-guide/framework/winforms/controls/media/net-bindsrcdatabindarch.gif new file mode 100644 index 0000000000..9ecee7478c Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/net-bindsrcdatabindarch.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/net-flpanchorexp.gif b/dotnet-desktop-guide/framework/winforms/controls/media/net-flpanchorexp.gif new file mode 100644 index 0000000000..b316771adb Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/net-flpanchorexp.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/toolstrip-control-architecture/toolstrip-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/toolstrip-control-architecture/toolstrip-object-model.gif new file mode 100644 index 0000000000..7352bec479 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/toolstrip-control-architecture/toolstrip-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/toolstrip-control-architecture/toolstripitem-object-model.gif b/dotnet-desktop-guide/framework/winforms/controls/media/toolstrip-control-architecture/toolstripitem-object-model.gif new file mode 100644 index 0000000000..7876d20901 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/toolstrip-control-architecture/toolstripitem-object-model.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/visual-studio-ellipsis-button.png b/dotnet-desktop-guide/framework/winforms/controls/media/visual-studio-ellipsis-button.png new file mode 100644 index 0000000000..d69ca5e3b0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/visual-studio-ellipsis-button.png differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/vs-flpanchor2.gif b/dotnet-desktop-guide/framework/winforms/controls/media/vs-flpanchor2.gif new file mode 100644 index 0000000000..d483095a73 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/vs-flpanchor2.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor.gif b/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor.gif new file mode 100644 index 0000000000..ef23cf4692 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor2.gif b/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor2.gif new file mode 100644 index 0000000000..4a3a11aed3 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor2.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor3.gif b/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor3.gif new file mode 100644 index 0000000000..c4c7b72e71 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/vs-tlpanchor3.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/vs-winformpadmargin.gif b/dotnet-desktop-guide/framework/winforms/controls/media/vs-winformpadmargin.gif new file mode 100644 index 0000000000..64e5f5c549 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/vs-winformpadmargin.gif differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/windows-forms-designer-error-page-collapsed.png b/dotnet-desktop-guide/framework/winforms/controls/media/windows-forms-designer-error-page-collapsed.png new file mode 100644 index 0000000000..e86ade22a5 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/windows-forms-designer-error-page-collapsed.png differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/media/windows-forms-designer-error-page-expanded.png b/dotnet-desktop-guide/framework/winforms/controls/media/windows-forms-designer-error-page-expanded.png new file mode 100644 index 0000000000..01a465a8b7 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/controls/media/windows-forms-designer-error-page-expanded.png differ diff --git a/dotnet-desktop-guide/framework/winforms/controls/menustrip-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/menustrip-control-overview-windows-forms.md new file mode 100644 index 0000000000..43f04501a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/menustrip-control-overview-windows-forms.md @@ -0,0 +1,58 @@ +--- +title: "MenuStrip Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "MenuStrip" +helpviewer_keywords: + - "MenuStrip control [Windows Forms], about MenuStrip control" + - "menus [Windows Forms], creating" +ms.assetid: f45516e5-bf01-4468-b851-d45f4c33c055 +--- +# MenuStrip Control Overview (Windows Forms) +Menus expose functionality to your users by holding commands that are grouped by a common theme. + + The control was introduced in version 2.0 of the .NET Framework. With the control, you can easily create menus like those found in Microsoft Office. + + The control supports the multiple-document interface (MDI) and menu merging, tool tips, and overflow. You can enhance the usability and readability of your menus by adding access keys, shortcut keys, check marks, images, and separator bars. + + The control replaces and adds functionality to the control; however, the control is retained for backward compatibility and future use if you choose. + +## Ways to Use the MenuStrip Control + Use the control to: + +- Create easily customized, commonly employed menus that support advanced user interface and layout features, such as text and image ordering and alignment, drag-and-drop operations, MDI, overflow, and alternate modes of accessing menu commands. + +- Support the typical appearance and behavior of the operating system. + +- Handle events consistently for all containers and contained items, in the same way you handle events for other controls. + + The following table shows some particularly important properties of and associated classes. + +|Property|Description| +|--------------|-----------------| +||Gets or sets the that is used to display a list of MDI child forms.| +||Gets or sets how child menus are merged with parent menus in MDI applications.| +||Gets or sets the position of a merged item within a menu in MDI applications.| +||Gets or sets a value indicating whether the form is a container for MDI child forms.| +||Gets or sets a value indicating whether tool tips are shown for the .| +||Gets or sets a value indicating whether the supports overflow functionality.| +||Gets or sets the shortcut keys associated with the .| +||Gets or sets a value indicating whether the shortcut keys that are associated with the are displayed next to the .| + + The following table shows the important companion classes. + +|Class|Description| +|-----------|-----------------| +||Represents a selectable option displayed on a or .| +||Represents a shortcut menu.| +||Represents a control that allows the user to select a single item from a list that is displayed when the user clicks a or a higher-level menu item.| +||Provides basic functionality for controls derived from that display drop-down items when clicked.| + +## See also + +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/menustrip-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/menustrip-control-windows-forms.md new file mode 100644 index 0000000000..16a9d55137 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/menustrip-control-windows-forms.md @@ -0,0 +1,78 @@ +--- +title: "MenuStrip Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "MenuStrip control [Windows Forms]" + - "menus" +ms.assetid: e361bf98-eed8-4ed3-9dfb-5a2e865e3ce6 +--- +# MenuStrip Control (Windows Forms) +This control groups application commands and makes them easily accessible. + +## In This Section + [MenuStrip Control Overview](menustrip-control-overview-windows-forms.md) + Explains what the control is and its key features and properties. + + [How to: Add Enhancements to ToolStripMenuItems](how-to-add-enhancements-to-toolstripmenuitems.md) + Describes how to add check marks, images, shortcut keys, access keys, and separator bars to menus and menu commands. + + [How to: Append a MenuStrip to an MDI Parent Window](how-to-append-a-menustrip-to-an-mdi-parent-window-windows-forms.md) + Describes how to set several properties to append the multiple-document interface (MDI) child menu to the MDI parent menu. + + [How to: Create an MDI Window List with MenuStrip](how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md) + Demonstrates how to create a list of all the active child forms on the parent's Window menu. + + [How to: Disable ToolStripMenuItems](how-to-disable-toolstripmenuitems.md) + Describes how to disable both entire menus and individual menu commands. + + [How to: Hide ToolStripMenuItems](how-to-hide-toolstripmenuitems.md) + Describes how to hide both entire menus and individual menu commands. + + [How to: Insert a MenuStrip into an MDI Drop-Down Menu](how-to-insert-a-menustrip-into-an-mdi-drop-down-menu-windows-forms.md) + Describes how to set several properties to insert a group of menu items from the MDI child menu into the drop-down part of the MDI parent menu. + + [How to: Remove a ToolStripMenuItem from an MDI Drop-Down Menu](how-to-remove-a-toolstripmenuitem-from-an-mdi-drop-down-menu-windows-forms.md) + Describes how to set several properties to remove a menu item from the drop-down part of the MDI parent menu. + + [How to: Configure MenuStrip Check Margins and Image Margins](how-to-configure-menustrip-check-margins-and-image-margins.md) + Describes how to customize a by setting check and image margin properties in various ways. + + [How to: Provide Standard Menu Items to a Form](how-to-provide-standard-menu-items-to-a-form.md) + Describes how to use a control to create a form with a standard menu. + + [How to: Display Option Buttons in a MenuStrip](how-to-display-option-buttons-in-a-menustrip-windows-forms.md) + Describes how to implement option-button (or radio-button) behavior in a . + + [Merging Menu Items in the Windows Forms MenuStrip Control](merging-menu-items-in-the-windows-forms-menustrip-control.md) + Describes general concepts and methods for menu merging. + + [How to: Set Up Automatic Menu Merging for MDI Applications](how-to-set-up-automatic-menu-merging-for-mdi-applications.md) + Describes how to merge menu items automatically at run time. + +- [MenuStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233625(v=vs.100)) + +- [How to: Copy ToolStripMenuItems](how-to-copy-toolstripmenuitems.md) + +- [How to: Hide ToolStripMenuItems Using the Designer](how-to-hide-toolstripmenuitems-using-the-designer.md) + +- [How to: Disable ToolStripMenuItems Using the Designer](how-to-disable-toolstripmenuitems-using-the-designer.md) + +- [How to: Move ToolStripMenuItems](how-to-move-toolstripmenuitems.md) + +- [Walkthrough: Providing Standard Menu Items to a Form](walkthrough-providing-standard-menu-items-to-a-form.md) + +- [MenuStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233645(v=vs.100)) + +## Reference + + Describes the features of the class, which provides a menu system for a form. + + + Describes the features of the , which represents a shortcut menu. + + + Describes the features of the class, which represents a selectable option displayed on a or . + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/merging-menu-items-in-the-windows-forms-menustrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/merging-menu-items-in-the-windows-forms-menustrip-control.md new file mode 100644 index 0000000000..ca5c5a5c70 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/merging-menu-items-in-the-windows-forms-menustrip-control.md @@ -0,0 +1,56 @@ +--- +title: Merging Menu Items in MenuStrip Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "MenuStrip [Windows Forms], merging" + - "merging [Windows Forms], general concepts" +ms.assetid: 95e113ba-f362-4dda-8a76-6d95ddc45cee +--- +# Merging Menu Items in the Windows Forms MenuStrip Control +If you have a multiple-document interface (MDI) application, you can merge menu items or whole menus from the child form into the menus of the parent form. + + This topic describes the basic concepts associated with merging menu items in an MDI application. + +## General Concepts + Merging procedures involve both a target and a source control: + +- The target is the control on the main or MDI parent form into which you are merging menu items. + +- The source is the control on the MDI child form that contains the menu items you want to merge into the target menu. + + The property identifies the menu item whose drop-down list you will populate with the titles of the current MDI parent form's MDI children. For example, you typically list MDI children that are currently open on the **Window** menu. + + The property identifies which menu items come from a on an MDI child form. + + You can merge menu items manually or automatically. The menu items merge in the same way for both methods, but the merge is activated differently, as discussed in the "Manual Merging" and "Automatic Merging" sections later in this topic. In both manual and automatic merging, each merge action affects the next merge action. + + merging moves menu items from one to another rather than cloning them, as was the case with . + +## MergeAction Values + You set the merge action on menu items in the source using the property. + + The following table describes the meaning and typical use of the available merge actions. + +|MergeAction Value|Description|Typical Use| +|-----------------------|-----------------|-----------------| +||(Default) Adds the source item to the end of the target item's collection.|Adding menu items to the end of the menu when some part of the program is activated.| +||Adds the source item to the target item's collection, in the location specified by the property set on the source item.|Adding menu items to the middle or the beginning of the menu when some part of the program is activated.

If the value of is the same for both menu items, they are added in reverse order. Set appropriately to preserve the original order.| +||Finds a text match, or uses the value if no text match is found, and then replaces the matching target menu item with the source menu item.|Replacing a target menu item with a source menu item of the same name that does something different.| +||Finds a text match, or uses the value if no text match is found, and then adds all the drop-down items from the source to the target.|Building a menu structure that inserts or adds menu items into a submenu, or removes menu items from a submenu. For example, you can add a menu item from an MDI child to a main **Save As** menu.

allows you to navigate through the menu structure without taking any action. It provides a way to evaluate the subsequent items.| +||Finds a text match, or uses the value if no text match is found, and then removes the item from the target.|Removing a menu item from the target .| + +## Manual Merging + Only controls participate in automatic merging. To combine the items of other controls, such as and controls, you must merge them manually, by calling the and methods in your code as required. + +## Automatic Merging + You can use automatic merging for MDI applications by activating the source form. To use a in an MDI application, set the property to the target so that merging actions performed on the source are reflected in the target . + + You can trigger automatic merging by activating the on the MDI source. Upon activation, the source is merged into the MDI target. When a new form becomes active, the merge is reverted on the last form and triggered on the new form. You can control this behavior by setting the property as needed on each , and by setting the property on each . + +## See also + +- +- +- [MenuStrip Control](menustrip-control-windows-forms.md) +- [How to: Create an MDI Window List with MenuStrip](how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md) +- [How to: Set Up Automatic Menu Merging for MDI Applications](how-to-set-up-automatic-menu-merging-for-mdi-applications.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/method-implementation-in-custom-controls.md b/dotnet-desktop-guide/framework/winforms/controls/method-implementation-in-custom-controls.md new file mode 100644 index 0000000000..388ed241bb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/method-implementation-in-custom-controls.md @@ -0,0 +1,75 @@ +--- +title: "Method Implementation in Custom Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "user controls [Windows Forms], method implementation" + - "custom controls [Windows Forms], overloading methods" + - "custom controls [Windows Forms], method implementation" + - "methods [Windows Forms]" + - "methods [Windows Forms], custom controls" +ms.assetid: 35d14fca-4bb4-4a27-8211-1f7a98ea27de +--- +# Method Implementation in Custom Controls +A method is implemented in a control in the same manner a method would be implemented in any other component. + + In Visual Basic, if a method is required to return a value, it is implemented as a `Public Function`. If no value is returned, it is implemented as a `Public Sub`. Methods are declared using the following syntax: + +```vb +Public Function ConvertMatterToEnergy(Matter as Integer) As Integer + ' Conversion code goes here. +End Function +``` + + Because functions return a value, they must specify a return type, such as integer, string, object, and so on. The arguments `Function` or `Sub` procedures take, if any, must also be specified. + + C# makes no distinction between functions and procedures, as Visual Basic does. A method either returns a value or returns `void`. The syntax for declaring a C# public method is: + +```csharp +public int ConvertMatterToEnergy(int matter) +{ + // Conversion code goes here. +} +``` + + When you declare a method, declare all of its arguments as explicit data types whenever possible. Arguments that take object references should be declared as specific class types — for example, `As Widget` instead of `As Object`. In Visual Basic, the default setting `Option Strict` automatically enforces this rule. + + Typed arguments allow many developer errors to be caught by the compiler, rather than at run time. The compiler always catches errors, whereas run-time testing is only as good as the test suite. + +## Overloaded Methods + If you want to allow users of your control to supply different combinations of parameters to a method, provide multiple overloads of the method, using explicit data types. Avoid creating parameters declared `As Object` that can contain any data type, as this can lead to errors that might not be caught in testing. + +> [!NOTE] +> The universal data type in the common language runtime is `Object` rather than `Variant`. `Variant` has been removed from the language. + + For example, the `Spin` method of a hypothetical `Widget` control might allow either direct specification of spin direction and speed, or specification of another `Widget` object from which angular momentum is to be absorbed: + +```vb +Overloads Public Sub Spin( _ + ByVal SpinDirection As SpinDirectionsEnum, _ + ByVal RevolutionsPerSecond As Double) + ' Implementation code here. +End Sub +Overloads Public Sub Spin(ByVal Driver As Widget) _ + ' Implementation code here. +End Sub +``` + +```csharp +public void Spin(SpinDirectionsEnum spinDirection, double revolutionsPerSecond) +{ + // Implementation code here. +} + +public void Spin(Widget driver) +{ + // Implementation code here. +} +``` + +## See also + +- [Events](https://docs.microsoft.com/dotnet/standard/events/index) +- [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/monthcalendar-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/monthcalendar-control-overview-windows-forms.md new file mode 100644 index 0000000000..5b7eaf65ce --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/monthcalendar-control-overview-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "MonthCalendar Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "MonthCalendar" +helpviewer_keywords: + - "calendars [Windows Forms], Windows Forms controls" + - "calendar controls [Windows Forms], Windows Forms" + - "MonthCalendar control [Windows Forms], setting the first day of the week" +ms.assetid: 788c5325-b721-44ec-95bf-9b680ba0f6a2 +--- +# MonthCalendar Control Overview (Windows Forms) +The Windows Forms control presents an intuitive graphical interface for users to view and set date information. The control displays a calendar: a grid containing the numbered days of the month, arranged in columns underneath the days of the week, with the selected range of dates highlighted. You can select a different month by clicking the arrow buttons on either side of the month caption. Unlike the similar control, you can select more than one date with this control. For more information about the control, see [DateTimePicker Control](datetimepicker-control-windows-forms.md). + +## Configuring the MonthCalendar Control + The control's appearance is highly configurable. By default, today's date is displayed as circled, and is also noted at the bottom of the grid. You can change this feature by setting the and properties to `false`. You can also add week numbers to the calendar by setting the property to `true`. By setting the property, you can have multiple months displayed horizontally and vertically. By default, Sunday is shown as the first day of the week, but any day can be designated using the property. + + You can also set certain dates to be displayed in bold on a one-time basis, annually, or monthly, by adding objects to the , , and properties. For more information, see [How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control](display-specific-days-in-bold-with-wf-monthcalendar-control.md). + + The key property of the control is , the range of dates selected in the control. The value cannot exceed the maximum number of days that can be selected, set in the property. The earliest and latest dates the user can select are determined by the and properties. + +## See also + +- +- [MonthCalendar Control](monthcalendar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/monthcalendar-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/monthcalendar-control-windows-forms.md new file mode 100644 index 0000000000..98cc4ad070 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/monthcalendar-control-windows-forms.md @@ -0,0 +1,39 @@ +--- +title: "MonthCalendar Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "calendar controls" + - "MonthCalendar control [Windows Forms]" + - "dates [Windows Forms], controls" + - "calendars" +ms.assetid: 051c6518-e0ca-426b-855c-f9bf70972970 +--- +# MonthCalendar Control (Windows Forms) +The Windows Forms `MonthCalendar` control presents an intuitive graphical interface for users to view and set date information. The control displays a grid containing the numbered days of the month, arranged in columns underneath the days of the week. You can select a different month by clicking the arrow buttons on either side of the month caption. Unlike the similar control, you can select a range of dates with this control; however, the control allows you to set times as well as dates. + +## In This Section + [MonthCalendar Control Overview](monthcalendar-control-overview-windows-forms.md) + Introduces the general concepts of the `MonthCalendar` control, which allows users to view and set date information for an application. + + [How to: Change the Windows Forms MonthCalendar Control's Appearance](how-to-change-monthcalendar-control-appearance.md) + Describes how to customize the appearance of the `MonthCalendar` control. + + [How to: Display More than One Month in the Windows Forms MonthCalendar Control](display-more-than-one-month-wf-monthcalendar-control.md) + Describes how to configure the `MonthCalendar` control to display several months simultaneously. + + [How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control](display-specific-days-in-bold-with-wf-monthcalendar-control.md) + Explains how to set certain dates to appear bold. + + [How to: Select a Range of Dates in the Windows Forms MonthCalendar Control](how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md) + Explains how to programmatically select a range of dates from the `MonthCalendar` control. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [DateTimePicker Control](datetimepicker-control-windows-forms.md) + Describes a control similar to , although the control also allows you to select a time and does not allow you to select a range of dates. diff --git a/dotnet-desktop-guide/framework/winforms/controls/move-through-a-dataset-with-wf-bindingnavigator-control.md b/dotnet-desktop-guide/framework/winforms/controls/move-through-a-dataset-with-wf-bindingnavigator-control.md new file mode 100644 index 0000000000..cc8a0032fe --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/move-through-a-dataset-with-wf-bindingnavigator-control.md @@ -0,0 +1,37 @@ +--- +title: Move Through a DataSet with BindingNavigator Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "datasets [Windows Forms], moving through" + - "BindingNavigator control [Windows Forms], moving through datasets" + - "examples [Windows Forms], BindingNavigator control" +ms.assetid: 146d97be-3d97-400e-accb-860bbf47729d +--- +# How to: Move Through a DataSet with the Windows Forms BindingNavigator Control +As you build data-driven applications, you will often need to display collections of data to users. The control, in conjunction with the component, provides a convenient and extensible solution for moving through a collection and displaying items sequentially. + +## Example + The following code example demonstrates how to use a control to move through data. The set is contained in a , which is bound to a control with a component. + +> [!NOTE] +> Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + + [!code-csharp[System.Windows.Forms.DataNavigator#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataNavigator#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing, System.Windows.Forms and System.Xml assemblies. + +## See also + +- +- +- +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/multithreading-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/multithreading-in-windows-forms-controls.md new file mode 100644 index 0000000000..a7eb9a3a8f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/multithreading-in-windows-forms-controls.md @@ -0,0 +1,37 @@ +--- +title: Multithreading in Controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "BackgroundWorker component" + - "threading [Windows Forms], controls" +ms.assetid: c311d652-0f26-45fa-bdcc-b1615d73ce4e +--- +# Multithreading in Windows Forms Controls +In many applications, you can make your user interface (UI) more responsive by performing time-consuming operations on another thread. A number of tools are available for multithreading your Windows Forms controls, including the namespace, the method, and the `BackgroundWorker` component. + +> [!NOTE] +> The `BackgroundWorker` component replaces and adds functionality to the namespace and the method; however, these are retained for both backward compatibility and future use, if you choose. For more information, see [BackgroundWorker Component Overview](backgroundworker-component-overview.md). + +## In This Section + [How to: Make Thread-Safe Calls to Windows Forms Controls](how-to-make-thread-safe-calls-to-windows-forms-controls.md) + Shows how to make thread-safe calls to Windows Forms controls. + + [How to: Use a Background Thread to Search for Files](how-to-use-a-background-thread-to-search-for-files.md) + Shows how to use the namespace and the method to search for files asynchronously. + +## Reference + + Documents a component that encapsulates a worker thread for asynchronous operations. + + + Documents how to load a sound asynchronously. + + + Documents how to load an image asynchronously. + +## Related Sections + [How to: Run an Operation in the Background](how-to-run-an-operation-in-the-background.md) + Shows how to perform a time-consuming operation with the component. + + [BackgroundWorker Component Overview](backgroundworker-component-overview.md) + Provides topics that describe how to use the component for asynchronous operations. diff --git a/dotnet-desktop-guide/framework/winforms/controls/notifyicon-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/notifyicon-component-overview-windows-forms.md new file mode 100644 index 0000000000..061ac2ed41 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/notifyicon-component-overview-windows-forms.md @@ -0,0 +1,29 @@ +--- +title: "NotifyIcon Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "NotifyIcon" +helpviewer_keywords: + - "NotifyIcon component [Windows Forms], about NotifyIcon component" + - "system tray icons [Windows Forms], about system tray icons" + - "system tray icons [Windows Forms], using in Windows Forms" +ms.assetid: 5b9189fa-d4ae-41a6-9b97-eb1f44bb1a69 +--- +# NotifyIcon Component Overview (Windows Forms) + +The Windows Forms component is typically used to display icons for processes that run in the background and do not show a user interface much of the time. An example would be a virus protection program that can be accessed by clicking an icon in the status notification area of the taskbar. + +## Key Properties of NotifyIcons + +Each component displays a single icon in the status area. If you have three background processes and wish to display an icon for each, you must add three components to the form. The key properties of the component are and . The property sets the icon that appears in the status area. In order for the icon to appear, the property must be set to `true`. + +## NotifyIcons Options + +You can associate balloon tips, shortcut menus, and ToolTips with a to assist the user. + +You can display balloon tips for a by calling the method specifying the time span you wish the balloon tip to display. You can also specify the text, icon and title of the balloon tip with the , and , respectively. components can also have associated ToolTips and shortcut menus. For more information, see [ToolTip Component Overview](tooltip-component-overview-windows-forms.md) and [ContextMenu Component Overview](contextmenu-component-overview-windows-forms.md). + +## See also + +- +- [NotifyIcon Component](notifyicon-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/notifyicon-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/notifyicon-component-windows-forms.md new file mode 100644 index 0000000000..ecd0014d90 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/notifyicon-component-windows-forms.md @@ -0,0 +1,34 @@ +--- +title: "NotifyIcon Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "application icons [Windows Forms], background processes" + - "context menus [Windows Forms], for background processes" + - "status tray icon" + - "system tray icons" + - "user interface [Windows Forms], for background processes" + - "background program icon" + - "NotifyIcon component" + - "SysTray icons" +ms.assetid: 20312268-1d67-494a-8601-5c43b7f1b513 +--- +# NotifyIcon Component (Windows Forms) +The Windows Forms `NotifyIcon` component displays icons in the status notification area of the taskbar for processes that run in the background and would not otherwise have user interfaces. An example would be a virus protection program that can be accessed by clicking an icon in the status notification area of the taskbar. + +## In This Section + [NotifyIcon Component Overview](notifyicon-component-overview-windows-forms.md) + Introduces the general concepts of the `NotifyIcon` component, which allows users to see icons for processes running in the background that do not have a user interface. + + [How to: Add Application Icons to the TaskBar with the Windows Forms NotifyIcon Component](app-icons-to-the-taskbar-with-wf-notifyicon.md) + Provides steps for setting the icon displayed by the `NotifyIcon` component. + + [How to: Associate a Shortcut Menu with a Windows Forms NotifyIcon Component](how-to-associate-a-shortcut-menu-with-a-windows-forms-notifyicon-component.md) + Provides steps for adding a shortcut menu to a `NotifyIcon` component. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/numericupdown-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/numericupdown-control-overview-windows-forms.md new file mode 100644 index 0000000000..e565f4b82c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/numericupdown-control-overview-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "NumericUpDown Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "NumericUpDown" +helpviewer_keywords: + - "numeric spin button control [Windows Forms], Windows Forms" + - "NumericUpDown control [Windows Forms], about NumericUpDown control" + - "spin button control [Windows Forms], Windows Forms" +ms.assetid: cff3cf30-4d46-4381-87df-37bfe83c71c5 +--- +# NumericUpDown Control Overview (Windows Forms) +The control looks like a combination of a text box and a pair of arrows that the user can click to adjust a value. The control displays and sets a single numeric value from a list of fixed numeric-value choices. The user can increase and decrease the number by clicking the up and down arrows, by pressing the UP and DOWN ARROW keys, or by typing a number in the text box part of the control. Clicking the UP ARROW key moves the number toward the maximum; clicking the DOWN ARROW key moves the number toward the minimum. + + Because of its versatile functionality, this control is an obvious choice, for example, if you want to create a volume control for a music player application. The control is used in many Windows Control Panel applications. + +## Key Properties and Methods + The numbers displayed in the control's text box can be in a variety of formats, including hexadecimal. For more information, see [How to: Set the Format for the Windows Forms NumericUpDown Control](how-to-set-the-format-for-the-windows-forms-numericupdown-control.md). The key properties of the control are , (default value 100), (default value 0), and (default value 1). The property sets the current number selected in the control. The property sets the amount that the number is adjusted by when the user clicks an up or down arrow. When focus moves off the control, any typed input will be validated against the minimum and maximum numeric values. You can increase the speed that the control moves through numbers, when the user continuously presses the up or down arrow, with the property. The key methods of the control are and . + +## See also + +- +- [NumericUpDown Control](numericupdown-control-windows-forms.md) +- [How to: Set the Format for the Windows Forms NumericUpDown Control](how-to-set-the-format-for-the-windows-forms-numericupdown-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/numericupdown-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/numericupdown-control-windows-forms.md new file mode 100644 index 0000000000..3f90305b73 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/numericupdown-control-windows-forms.md @@ -0,0 +1,35 @@ +--- +title: "NumericUpDown Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, NumericUpDown control" + - "spin button control [Windows Forms], up-down controls" + - "up-down controls [Windows Forms], spin button control" + - "up-down controls" + - "spin button control" + - "NumericUpDown control [Windows Forms]" +ms.assetid: 32b0c20d-4f37-4aea-873d-faded741d2db +--- +# NumericUpDown Control (Windows Forms) +The Windows Forms `NumericUpDown` control looks like a combination of a text box and a pair of arrows that the user can click to adjust a value. The control displays and sets a single numeric value from a list of choices. The user can increase and decrease the number by clicking up and down buttons, by pressing the UP and DOWN ARROW keys, or by typing a number. Clicking the UP ARROW key moves the value toward its maximum; clicking the DOWN ARROW key moves the position toward the minimum. An example where this kind of control might be useful is for a volume control on a music player. Numeric up-down controls are used in some Windows control panel applications. + +## In This Section + [NumericUpDown Control Overview](numericupdown-control-overview-windows-forms.md) + Introduces the general concepts of the `NumericUpDown` control, which allows users to browse through and select from a list of numeric values. + + [How to: Set and Return Numeric Values with the Windows Forms NumericUpDown Control](set-and-return-numeric-values-with-wf-numericupdown-control.md) + Describes how to test for the value of the control. + + [How to: Set the Format for the Windows Forms NumericUpDown Control](how-to-set-the-format-for-the-windows-forms-numericupdown-control.md) + Describes how to configure how values are displayed in the control. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [DomainUpDown Control](domainupdown-control-windows-forms.md) + Introduces a control similar to , except that the control displays string instead of numeric values. diff --git a/dotnet-desktop-guide/framework/winforms/controls/openfiledialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/openfiledialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..880661540a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/openfiledialog-component-overview-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "OpenFileDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "OpenFileDialog" +helpviewer_keywords: + - "OpenFileDialog component [Windows Forms], about OpenFileDialog" + - "Open File dialog box [Windows Forms], displaying in Windows Forms" +ms.assetid: cd717300-46b6-4f82-8207-b218fa7fa407 +--- +# OpenFileDialog Component Overview (Windows Forms) + +The Windows Forms component is a pre-configured dialog box. It is the same **Open File** dialog box exposed by the Windows operating system. It inherits from the class. + +## Use this component + +Use this component within your Windows-based application as a simple solution for file selection in lieu of configuring your own dialog box. By relying on standard Windows dialog boxes, you create applications whose basic functionality is immediately familiar to users. Be aware, however, that when using the component, you must write your own file-opening logic. + +Use the method to display the dialog at run time. You can enable users to multi-select files to be opened with the property. Additionally, you can use the property to determine if a read-only check box appears in the dialog box. The property indicates whether the read-only check box is selected. Finally, the property sets the current file name filter string, which determines the choices that appear in the "Files of type" box in the dialog box. + +When it is added to a form, the component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio. + +## See also + +- +- [OpenFileDialog Component](openfiledialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/openfiledialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/openfiledialog-component-windows-forms.md new file mode 100644 index 0000000000..84ed84d6c9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/openfiledialog-component-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "OpenFileDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Open File dialog box" + - "OpenFileDialog component" +ms.assetid: d2efa832-a272-42ff-aa26-c4ac13ff59ba +--- +# OpenFileDialog Component (Windows Forms) +The Windows Forms component is a pre-configured dialog box. It is the same **Open File** dialog box exposed by the Windows operating system. It inherits from the class. + +## In This Section + [OpenFileDialog Component Overview](openfiledialog-component-overview-windows-forms.md) + Introduces the general concepts of the component, which allows you to display a pre-configured dialog box that users can use to open files. + + [How to: Open Files Using the OpenFileDialog Component](how-to-open-files-using-the-openfiledialog-component.md) + Explains how to open a file at run time via an instance of the component. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Describes a set of controls and components that allow users to perform standard interactions with the application or system. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/overriding-the-onpaint-method.md b/dotnet-desktop-guide/framework/winforms/controls/overriding-the-onpaint-method.md new file mode 100644 index 0000000000..15792c60c1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/overriding-the-onpaint-method.md @@ -0,0 +1,87 @@ +--- +title: "Overriding the OnPaint Method" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Paint event [Windows Forms], handling in Windows Forms custom control" + - "OnPaint method [Windows Forms], overriding in Windows Forms custom controls" +ms.assetid: e9ca2723-0107-4540-bb21-4f5ffb4a9906 +--- +# Overriding the OnPaint Method +The basic steps for overriding any event defined in the .NET Framework are identical and are summarized in the following list. + +#### To override an inherited event + +1. Override the protected `On`*EventName* method. + +2. Call the `On`*EventName* method of the base class from the overridden `On`*EventName* method, so that registered delegates receive the event. + + The event is discussed in detail here because every Windows Forms control must override the event that it inherits from . The base class does not know how a derived control needs to be drawn and does not provide any painting logic in the method. The method of simply dispatches the event to registered event receivers. + + If you worked through the sample in [How to: Develop a Simple Windows Forms Control](how-to-develop-a-simple-windows-forms-control.md), you have seen an example of overriding the method. The following code fragment is taken from that sample. + +```vb +Public Class FirstControl + Inherits Control + + Public Sub New() + End Sub + + Protected Overrides Sub OnPaint(e As PaintEventArgs) + ' Call the OnPaint method of the base class. + MyBase.OnPaint(e) + ' Call methods of the System.Drawing.Graphics object. + e.Graphics.DrawString(Text, Font, New SolidBrush(ForeColor), RectangleF.op_Implicit(ClientRectangle)) + End Sub +End Class +``` + +```csharp +public class FirstControl : Control { + public FirstControl() {} + protected override void OnPaint(PaintEventArgs e) { + // Call the OnPaint method of the base class. + base.OnPaint(e); + // Call methods of the System.Drawing.Graphics object. + e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle); + } +} +``` + + The class contains data for the event. It has two properties, as shown in the following code. + +```vb +Public Class PaintEventArgs + Inherits EventArgs + ... + Public ReadOnly Property ClipRectangle() As System.Drawing.Rectangle + ... + End Property + + Public ReadOnly Property Graphics() As System.Drawing.Graphics + ... + End Property + ... +End Class +``` + +```csharp +public class PaintEventArgs : EventArgs { +... + public System.Drawing.Rectangle ClipRectangle {} + public System.Drawing.Graphics Graphics {} +... +} +``` + + is the rectangle to be painted, and the property refers to a object. The classes in the namespace are managed classes that provide access to the functionality of GDI+, the new Windows graphics library. The object has methods to draw points, strings, lines, arcs, ellipses, and many other shapes. + + A control invokes its method whenever it needs to change its visual display. This method in turn raises the event. + +## See also + +- [Events](https://docs.microsoft.com/dotnet/standard/events/index) +- [Rendering a Windows Forms Control](rendering-a-windows-forms-control.md) +- [Defining an Event](defining-an-event-in-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/overview-of-using-controls-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/overview-of-using-controls-in-windows-forms.md new file mode 100644 index 0000000000..702d4e7d32 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/overview-of-using-controls-in-windows-forms.md @@ -0,0 +1,223 @@ +--- +title: "Overview of Using Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, controls" + - "controls [Windows Forms]" + - "custom controls [Windows Forms]" +ms.assetid: fddbe951-4485-459d-a5fd-665ea346dbc1 +--- +# Overview of Using Controls in Windows Forms +This topic describes the essential elements of a Windows Forms application and provides a simple example that uses controls and handles events in a Windows Forms application. + +## Simple Windows Forms Applications + At a minimum, a Windows Forms application consists of the following elements: + +- One or more classes that derive from . + +- A `Main` method that invokes the `static` (`shared` in Visual Basic) method and passes a instance to it. The method processes messages from the operating system to the application. + + The following code example shows the essential elements of a Windows Forms application. + +```vb +Option Explicit +Option Strict + +Imports System +Imports System.Windows.Forms + +Public Class MyForm + Inherits Form + + Public Sub New() + Me.Text = "Hello World" + End Sub 'New + + _ + Public Shared Sub Main() + Dim aform As New MyForm() + ' The Application.Run method processes messages from the operating system + ' to your application. If you comment out the next line of code, + ' your application will compile and execute, but because it is not in the + ' message loop, it will exit after an instance of the form is created. + Application.Run(aform) + End Sub +End Class +``` + +```csharp +using System; +using System.Windows.Forms; + +public class MyForm : Form { + + public MyForm() { + this.Text = "Hello World"; + } + [STAThread] + public static void Main(string[] args) { + MyForm aform = new MyForm(); +// The Application.Run method processes messages from the operating system +// to your application. If you comment out the next line of code, +// your application will compile and execute, but because it is not in the // message loop, it will exit after an instance of the form is created. + Application.Run(aform); + } +} +``` + +## Using Controls in a Windows Forms Application + The following code example shows a simple application that illustrates how Windows Forms applications use controls and handle events. The example consists of three buttons on a form; each button changes the background color when clicked. + +```vb +Option Explicit +Option Strict + +Imports System +Imports System.ComponentModel +Imports System.Windows.Forms +Imports System.Resources +Imports System.Drawing + +Public Class MyForm + Inherits Form + Private red As Button + Private blue As Button + Private green As Button + + Public Sub New() + InitializeComponent() + End Sub + + Protected Overloads Overrides Sub Dispose(disposing as Boolean) + MyBase.Dispose(disposing) + End Sub + + ' InitializeComponent is a helper method for the constructor. + ' It is included for consistency with code that is + ' auto-generated by the Windows Forms designer in Visual Studio. + Private Sub InitializeComponent() + + ' Creates three buttons, sets their properties, and attaches + ' an event handler to each button. + red = New Button() + red.Text = "Red" + red.Location = New Point(100, 50) + red.Size = New Size(50, 50) + AddHandler red.Click, AddressOf button_Click + Controls.Add(red) + + blue = New Button() + blue.Text = "Blue" + blue.Location = New Point(100, 100) + blue.Size = New Size(50, 50) + AddHandler blue.Click, AddressOf button_Click + Controls.Add(blue) + + green = New Button() + green.Text = "Green" + green.Location = New Point(100, 150) + green.Size = New Size(50, 50) + AddHandler green.Click, AddressOf button_Click + Controls.Add(green) + End Sub + + ' Event handler. + Private Sub button_Click(sender As Object, e As EventArgs) + If sender Is red Then + Me.BackColor = Color.Red + Else + If sender Is blue Then + Me.BackColor = Color.Blue + Else + Me.BackColor = Color.Green + End If + End If + End Sub + + ' The STAThreadAttribute informs the common language runtime that + ' Windows Forms uses the single-threaded apartment model. + _ + Public Shared Sub Main() + Application.Run(New MyForm()) + End Sub +End Class +``` + +```csharp +using System; +using System.ComponentModel; +using System.Windows.Forms; +using System.Resources; +using System.Drawing; + +public class MyForm : Form { + private Button red; + private Button blue; + private Button green; + + public MyForm() : base() { + InitializeComponent(); + } + + protected override void Dispose(bool disposing) { + base.Dispose(disposing); + } + +// InitializeComponent is a helper method for the constructor. +// It is included for consistency with code that is +// auto-generated by the Windows Forms designer in Visual Studio. + private void InitializeComponent() { + +// A delegate for the click event of a button. The argument to +// the constructor contains a reference to the method that performs the +// event handling logic. + EventHandler handler = new EventHandler(button_Click); + +// Creates three buttons, sets their properties, and attaches +// an event handler to each button. + + red = new Button(); + red.Text = "Red"; + red.Location = new Point(100, 50); + red.Size = new Size(50, 50); + red.Click +=handler; + Controls.Add(red); + + blue = new Button(); + blue.Text = "Blue"; + blue.Location = new Point(100, 100); + blue.Size = new Size(50, 50); + blue.Click += handler; + Controls.Add(blue); + + green = new Button(); + green.Text = "Green"; + green.Location = new Point(100, 150); + green.Size = new Size(50, 50); + green.Click += handler; + Controls.Add(green); + } + + // Event handler. + private void button_Click(object sender, EventArgs e) { + if (sender == red) this.BackColor = Color.Red ; + else if (sender == blue) this.BackColor = Color.Blue; + else this.BackColor = Color.Green; + } + // The STAThreadAttribute informs the common language runtime that + // Windows Forms uses the single-threaded apartment model. + [STAThread] + public static void Main(string[] args) { + Application.Run(new MyForm()); + } + +} +``` + +## See also + +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [Windows Forms Control Development Basics](windows-forms-control-development-basics.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/pagesetupdialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/pagesetupdialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..4736592f90 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/pagesetupdialog-component-overview-windows-forms.md @@ -0,0 +1,24 @@ +--- +title: "PageSetupDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "PageSetupDialog" +helpviewer_keywords: + - "Page Setup dialog box [Windows Forms], displaying" + - "PageSetupDialog component" +ms.assetid: 791caacb-a5ca-4fca-bad9-1a5721ad697c +--- +# PageSetupDialog Component Overview (Windows Forms) + +The Windows Forms component is a pre-configured dialog box used to set page details for printing in Windows-based applications. Use it within your Windows-based application as a simple solution for users to set page preferences in lieu of configuring your own dialog box. You can enable users to set border and margin adjustments, headers and footers, and portrait or landscape orientation. By relying on standard Windows dialog boxes, you create applications whose basic functionality is immediately familiar to users. + +## Key Properties and Methods + +Use the method to display the dialog at run time. This component has properties you can set that relate to either a single page ( class) or any document ( class). Additionally, the component can be used to determine specific printer settings, which are stored in the class. + +When it is added to a form, the component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio. + +## See also + +- +- [PageSetupDialog Component](pagesetupdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/pagesetupdialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/pagesetupdialog-component-windows-forms.md new file mode 100644 index 0000000000..e72ca4e759 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/pagesetupdialog-component-windows-forms.md @@ -0,0 +1,42 @@ +--- +title: "PageSetupDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "printing [Windows Forms], page setup" + - "margins [Windows Forms], page setup options" + - "paper orientation" + - "print options [Windows Forms], PageSetupDialog component" + - "page properties" + - "printing [Windows Forms], displaying setup dialog boxes" + - "portrait orientation" + - "headers [Windows Forms], printing" + - "footers [Windows Forms], page setup options" + - "landscape orientation" + - "page footer" + - "page setup" + - "Page Setup dialog box" + - "PageSetupDialog component" + - "page header" + - "printing [Windows Forms], headers and footers" +ms.assetid: 1c7ccb02-ac62-4fc8-8e4f-c67b01a86802 +--- +# PageSetupDialog Component (Windows Forms) +The Windows Forms component is a pre-configured dialog box used to set page details for printing in Windows-based applications. Use it within your Windows-based application as a simple solution for users to set page preferences in lieu of configuring your own dialog box. You can enable users to set border and margin adjustments, headers and footers, and portrait vs. landscape orientation. By relying on standard Windows dialog boxes, you create applications whose basic functionality is immediately familiar to users. + +## In This Section + [PageSetupDialog Component Overview](pagesetupdialog-component-overview-windows-forms.md) + Introduces the general concepts of the component, which you can use to display a pre-configured dialog box that users can use to manipulate page settings. + + [How to: Determine Page Properties Using the PageSetupDialog Component](how-to-determine-page-properties-using-the-pagesetupdialog-component.md) + Explains how to set page properties by using an instance of the component at run time. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Describes a set of controls and components that allow users to perform standard interactions with the application or system. diff --git a/dotnet-desktop-guide/framework/winforms/controls/panel-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/panel-control-overview-windows-forms.md new file mode 100644 index 0000000000..18e953530b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/panel-control-overview-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "Panel Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "Panel" +helpviewer_keywords: + - "grouping controls [Windows Forms], Panel control" + - "Panel control [Windows Forms], about Panel control" +ms.assetid: b6b83636-2c39-4dad-89d6-f0fa41049a74 +--- +# Panel Control Overview (Windows Forms) +Windows Forms controls are used to provide an identifiable grouping for other controls. Typically, you use panels to subdivide a form by function. For example, you may have an order form that specifies mailing options such as which overnight carrier to use. Grouping all options in a panel gives the user a logical visual cue. At design time all the controls can be moved easily — when you move the control, all its contained controls move, too. The controls grouped in a panel can be accessed through its property. This property returns a collection of instances, so you will typically need to cast a control retrieved this way to its specific type. + +## Panel Versus GroupBox + The control is similar to the control; however, only the control can have scroll bars, and only the control displays a caption. + +## Key Properties + To display scroll bars, set the property to `true`. You can also customize the appearance of the panel by setting the , , and properties. For more information on the and properties, see [How to: Set the Background of a Panel](how-to-set-the-background-of-a-windows-forms-panel.md). The property determines if the panel is outlined with no visible border (), a plain line (), or a shadowed line (). + +## See also + +- +- [GroupBox Control](groupbox-control-windows-forms.md) +- [How to: Group Controls with the Windows Forms Panel Control Using the Designer](group-controls-with-wf-panel-control-using-the-designer.md) +- [How to: Set the Background of a Windows Forms Panel Using the Designer](how-to-set-the-background-of-a-windows-forms-panel-using-the-designer.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/panel-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/panel-control-windows-forms.md new file mode 100644 index 0000000000..a48b0663be --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/panel-control-windows-forms.md @@ -0,0 +1,36 @@ +--- +title: "Panel Control" +description: Learn how to use the Windows Forms Panel control, specifically how to use panels to subdivide a form by function. +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], grouping" + - "grouping controls" + - "Panel control [Windows Forms]" +ms.assetid: 37c69803-5084-4347-b035-54cfbabdc310 +--- +# Panel Control (Windows Forms) +Windows Forms `Panel` controls are used to provide an identifiable grouping for other controls. Typically, you use panels to subdivide a form by function. The `Panel` control is similar to the control; however, only the `Panel` control can have scroll bars, and only the control displays a caption. + +## In This Section + [Panel Control Overview](panel-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Group Controls with the Windows Forms Panel Control Using the Designer](group-controls-with-wf-panel-control-using-the-designer.md) + Describes how to group controls with a panel using the designer. + + [How to: Set the Background of a Windows Forms Panel Using the Designer](how-to-set-the-background-of-a-windows-forms-panel-using-the-designer.md) + Describes how to display a background color and a background image on a panel using the designer. + + [How to: Set the Background of a Panel](how-to-set-the-background-of-a-windows-forms-panel.md) + Describes how to display a background color and a background image on a panel. + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [How to: Add to or Remove from a Collection of Controls at Run Time](how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time.md) + Describes how to add controls to and remove controls from any container control on your forms. diff --git a/dotnet-desktop-guide/framework/winforms/controls/perform-a-custom-action-based-on-changes-in-a-cell-of-a-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/perform-a-custom-action-based-on-changes-in-a-cell-of-a-datagrid.md new file mode 100644 index 0000000000..a2ca03629c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/perform-a-custom-action-based-on-changes-in-a-cell-of-a-datagrid.md @@ -0,0 +1,43 @@ +--- +title: Perform Custom Action Based on Changes in Cell of DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "cells [Windows Forms], detecting changes" + - "DataGridView control [Windows Forms], detecting changes in cells" + - "data grids [Windows Forms], detecting changes in cells" +ms.assetid: 7fa44d01-97f4-4ccb-a149-bc72628d2c36 +--- +# How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control +The control has a number of events you can use to detect changes in the state of cells. Two of the most commonly used are the and events. + +### To detect changes in the values of DataGridView cells + +- Write a handler for the event. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#130](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#130)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#130](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#130)] + +### To detect changes in the states of DataGridView cells + +- Write a handler for the event. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#135](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#135)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#135](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#135)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. For C#, the event handlers must be connected to the corresponding events. + +- References to the and assemblies. + +## See also + +- +- +- +- [Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control](programming-with-cells-rows-and-columns-in-the-datagrid.md) +- [Walkthrough: Validating Data in the Windows Forms DataGridView Control](walkthrough-validating-data-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/perform-common-tasks-design-actions.md b/dotnet-desktop-guide/framework/winforms/controls/perform-common-tasks-design-actions.md new file mode 100644 index 0000000000..404b0d5934 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/perform-common-tasks-design-actions.md @@ -0,0 +1,52 @@ +--- +title: Perform common tasks using designer actions on controls +ms.date: "02/13/2019" +helpviewer_keywords: + - "designer actions" +ms.assetid: cac337e6-00f6-4584-80f4-75728f5ea113 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Perform common tasks using designer actions + +As you construct forms and controls for your Windows Forms application, there are many tasks you'll perform repeatedly. The following list shows some of the commonly performed tasks you'll come across: + +- Adding or removing a tab on a . +- Docking a control to its parent. +- Changing the orientation of a control. + +To speed development, many controls offer designer actions, which are context-sensitive menus that allow you to perform common tasks like these in a single gesture at design time. These tasks are called *designer actions verbs*. + +Designer actions remain attached to a control instance for its lifetime in the designer and are always available. + +## Create the project + +The first step is to create the project and set up the form. + +1. In Visual Studio, create a Windows-based application project called **DesignerActionsExample**. + +2. Select the form in the **Windows Forms Designer**. + +## Use designer actions + +Designer actions are always available at design time on controls that offer them. + +1. Drag a from the **Toolbox** onto your form. Note the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) that appears on the side of the . + +2. Click the designer actions glyph. In the shortcut menu that appears next to the glyph, select the **Add Tab** item. Observe that a new tab page is added to the . + +3. Drag a control from the **Toolbox** onto your form. + +4. Click the designer actions glyph. In the shortcut menu that appears next to the glyph, select the **Add Column** item. Observe that a new column is added to the control. + +5. Drag a control from the **Toolbox** onto your form. + +6. Click the designer actions glyph. In the shortcut menu that appears next to the glyph, select the **Horizontal Splitter Orientation** item. Observe that the control's splitter bar is now oriented horizontally. + +## See also + +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/performance-tuning-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/performance-tuning-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..613bac50d8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/performance-tuning-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,36 @@ +--- +title: Performance Tuning in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], performance tuning" + - "performance [Windows Forms], DataGridView control" + - "performance tuning [Windows Forms], data grids" +ms.assetid: 6ccbff28-a0ff-41e4-b601-61b31b61851d +--- +# Performance Tuning in the Windows Forms DataGridView Control +When working with large amounts of data, the `DataGridView` control can consume a large amount of memory in overhead, unless you use it carefully. On clients with limited memory, you can avoid some of this overhead by avoiding features that have a high memory cost. You can also manage some or all of the data maintenance and retrieval tasks yourself using virtual mode in order to customize the memory usage for your scenario. + +## In This Section + [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) + Describes how to use the `DataGridView` control in a way that avoids unnecessary memory usage and performance penalties when working with large amounts of data. + + [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md) + Describes how to use virtual mode to supplement or replace the standard data-binding mechanism. + + [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md) + Describes how to implement handlers for several virtual-mode events. Also demonstrates how to implement row-level rollback and commit for user edits. + + [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md) + Describes how to load data on demand, which is useful when you have more data to display than the available client memory can store. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the property. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/picturebox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/picturebox-control-overview-windows-forms.md new file mode 100644 index 0000000000..0f5b34419f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/picturebox-control-overview-windows-forms.md @@ -0,0 +1,24 @@ +--- +title: "PictureBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "PictureBox" +helpviewer_keywords: + - "PictureBox control [Windows Forms], about PictureBox controls" + - "picture controls [Windows Forms], about picture controls" + - "image controls [Windows Forms], about image controls" +ms.assetid: e5befee7-dc29-4888-a7c4-3b177e394112 +--- +# PictureBox Control Overview (Windows Forms) +The Windows Forms control is used to display graphics in bitmap, GIF, JPEG, metafile, or icon format. + +## Key Properties and Methods + The picture that is displayed is determined by the property, which can be set at run time or at design time. You can alternatively specify the image by setting the property and then load the image synchronously using the method or asynchronously using the method. The property controls how the image and control fit with each other. For more information, see [How to: Modify the Size or Placement of a Picture at Run Time](how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md). + +## See also + +- +- [How to: Load a Picture Using the Designer](how-to-load-a-picture-using-the-designer-windows-forms.md) +- [How to: Modify the Size or Placement of a Picture at Run Time](how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md) +- [How to: Set Pictures at Run Time](how-to-set-pictures-at-run-time-windows-forms.md) +- [PictureBox Control](picturebox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/picturebox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/picturebox-control-windows-forms.md new file mode 100644 index 0000000000..70e2b1379f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/picturebox-control-windows-forms.md @@ -0,0 +1,32 @@ +--- +title: "PictureBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "PictureBox control [Windows Forms]" + - "image controls [Windows Forms]" + - "images [Windows Forms], adding to PictureBox control" +ms.assetid: f900eb93-25d5-40e5-b5df-b3cea0e831b6 +--- +# PictureBox Control (Windows Forms) +The Windows Forms `PictureBox` control is used to display graphics in bitmap, GIF, JPEG, metafile, or icon format. + +## In This Section + [PictureBox Control Overview](picturebox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Modify the Size or Placement of a Picture at Run Time](how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md) + Explains what the property does and how to set it. + + [How to: Set Pictures at Run Time](how-to-set-pictures-at-run-time-windows-forms.md) + Describes how to display and clear a picture at run time. + + [How to: Load a Picture Using the Designer](how-to-load-a-picture-using-the-designer-windows-forms.md) + Describes how to load and display a picture on a form at design time. + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/prevent-row-addition-and-deletion-datagridview.md b/dotnet-desktop-guide/framework/winforms/controls/prevent-row-addition-and-deletion-datagridview.md new file mode 100644 index 0000000000..d867717ca1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/prevent-row-addition-and-deletion-datagridview.md @@ -0,0 +1,36 @@ +--- +title: Prevent Row Addition and Deletion in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], disabling data entry" + - "data entry [Windows Forms], disabling in grids" + - "data grids [Windows Forms], disabling data entry" +ms.assetid: ef9539ce-539b-404e-84b6-ac282b64b88c +--- +# How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control +Sometimes you will want to prevent users from entering new rows of data or deleting existing rows in your control. The property indicates whether the row for new records is present at the bottom of the control, while the property indicates whether rows can be removed. The following code example uses these properties and also sets the property to make the control entirely read-only. + + There is support for this task in Visual Studio. Also see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer](prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#090](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#090)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#090](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#090)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- +- +- +- +- [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..5595d1c064 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md @@ -0,0 +1,25 @@ +--- +title: Prevent Row Addition and Deletion in DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], preventing row addition or deletion" +ms.assetid: a17722bd-9400-41e6-8dcc-c9c151f0a749 +--- +# How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer +Sometimes you will want to prevent users from entering new rows of data or deleting existing rows in your control. New rows are entered in the special row for new records at the bottom of the control. When you disable row addition, the row for new records is not displayed. You can then make the control entirely read-only by disabling row deletion and cell editing. + + The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +## To prevent row addition and deletion + +- Click the designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) on the upper-right corner of the control, and then clear the **Enable Adding** and **Enable Deleting** check boxes. + + > [!NOTE] + > To make the control entirely read-only, clear the **Enable Editing** check box as well. + +## See also + +- +- +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/printdialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printdialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..56232d8445 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printdialog-component-overview-windows-forms.md @@ -0,0 +1,24 @@ +--- +title: "PrintDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "PrintDialog" +helpviewer_keywords: + - "Print dialog box [Windows Forms], displaying" + - "PrintDialog component [Windows Forms], about PrintDialog component" +ms.assetid: 8327b8ac-1017-4b5e-a88b-fea9dd56999c +--- +# PrintDialog Component Overview (Windows Forms) + +The Windows Forms [PrintDialog](printdialog-component-windows-forms.md) component is a pre-configured dialog box used to select a printer, choose the pages to print, and determine other print-related settings in Windows-based applications. Use it as a simple solution for printer and print-related settings selection in lieu of configuring your own dialog box. You can enable users to print many parts of their documents: print all, print a selected page range, or print a selection. By relying on standard Windows dialog boxes, you create applications whose basic functionality is immediately familiar to users. The component inherits from the class. + +## Working with the Component + +Use the method to display the dialog box at run time. This component has properties that relate to either a single print job ( class) or the settings of an individual printer ( class). Either of these, in turn, may be shared by multiple printers. + +When it is added to a form, the component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio. + +## See also + +- +- [PrintDialog Component](printdialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/printdialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printdialog-component-windows-forms.md new file mode 100644 index 0000000000..9297b16e45 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printdialog-component-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "PrintDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "print options [Windows Forms], PrintDialog component (using designer)" + - "PrintDialog component [Windows Forms]" + - "Print dialog box (using designer)" + - "printing [Windows Forms], PrintDialog component (using designer)" + - "printing [Windows Forms], print options" +ms.assetid: 09b54db1-d7c7-42fa-b98a-840e6b80a9ad +--- +# PrintDialog Component (Windows Forms) +The Windows Forms `PrintDialog` component is a pre-configured dialog box used to select a printer, choose the pages to print, and determine other print-related settings in Windows-based applications. Use it as a simple solution for printer and print-related settings selection in lieu of configuring your own dialog box. You can enable users to print many parts of their documents: print all, print a specified page range, or print a selection. By relying on standard Windows dialog boxes, you create applications whose basic functionality is immediately familiar to users. + +## In This Section + [PrintDialog Component Overview](printdialog-component-overview-windows-forms.md) + Introduces the general concepts of the `PrintDialog` component, which allows you to display a pre-configured dialog box that users can use to select a printer, choose pages to print, and determine print-related settings. + + [How to: Display the PrintDialog Component](how-to-display-the-printdialog-component.md) + Explains how to display the dialog and where it saves properties. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/printdocument-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printdocument-component-overview-windows-forms.md new file mode 100644 index 0000000000..4ae01c2bcb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printdocument-component-overview-windows-forms.md @@ -0,0 +1,30 @@ +--- +title: "PrintDocument Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "PrintDocument" +helpviewer_keywords: + - "PrintDocument component [Windows Forms], about PrintDocument component" + - "printing [Windows Forms], PrintDocument component" +ms.assetid: b59b4b60-dce5-42ca-8421-3a54a2f7bab0 +--- +# PrintDocument Component Overview (Windows Forms) + +The Windows Forms [PrintDocument](printdocument-component-windows-forms.md) component is used to set the properties that describe what to print and the ability to print the document within Windows-based applications. It can be used in conjunction with the [PrintDialog](printdialog-component-windows-forms.md) component to be in control of all aspects of document printing. + +## Working with the PrintDocument Component + +Two of the main scenarios that involve the component are: + +- Simple print jobs, such as printing an individual text file. In such a case you would add the component to a Windows Form, then add programming logic that prints a file in the event handler. The programming logic should culminate with the method to print the document. This method sends a object, contained in the property of the class, to the printer. For an example that shows how to print a text document using the component, see [How to: Print a Multi-Page Text File in Windows Forms](../advanced/how-to-print-a-multi-page-text-file-in-windows-forms.md). + +- More complex print jobs, such as a situation where you will want to reuse printing logic you have written. In such a case you would derive a new component from the component and override (see [Overrides](https://docs.microsoft.com/dotnet/visual-basic/language-reference/modifiers/overrides) for Visual Basic or [override](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/override) for C#) the event. + +When it is added to a form, the component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio. + +## See also + +- +- +- [Windows Forms Print Support](../advanced/windows-forms-print-support.md) +- [PrintDocument Component](printdocument-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/printdocument-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printdocument-component-windows-forms.md new file mode 100644 index 0000000000..9ad8607114 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printdocument-component-windows-forms.md @@ -0,0 +1,31 @@ +--- +title: "PrintDocument Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "PrintDocument component [Windows Forms]" + - "printing [Windows Forms], documents" +ms.assetid: 5af6a51d-66f6-43cd-a8cd-d64eb18fe7e7 +--- +# PrintDocument Component (Windows Forms) +The Windows Forms `PrintDocument` component is used to set the properties that describe what to print and then to print the document within Windows-based applications. It can be used in conjunction with the component to be in command of all aspects of document printing. + +## In This Section + [PrintDocument Component Overview](printdocument-component-overview-windows-forms.md) + Introduces the general concepts of the `PrintDocument` component, which allows you to set properties describing what to print and launches printing in a Windows-based application. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Windows Forms Print Support](../advanced/windows-forms-print-support.md) + Presents a list of printing topics related to Windows Forms. + + [PrintDialog Component](printdialog-component-windows-forms.md) + Introduces the general concepts of the component, which allows you to display a pre-configured dialog box that users can use to select a printer, choose pages to print, and determine print-related settings. + + [PrintPreviewControl Control](printpreviewcontrol-control-windows-forms.md) + Introduces the general concepts of the , which you can use to design your own print preview dialog box or component. + + [PrintPreviewDialog Control](printpreviewdialog-control-windows-forms.md) + Introduces the general concepts of the control, which allows you to display a pre-configured dialog box that users can use to see a version of their document as it will look when it prints. diff --git a/dotnet-desktop-guide/framework/winforms/controls/printpreviewcontrol-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printpreviewcontrol-control-overview-windows-forms.md new file mode 100644 index 0000000000..387e7f52ec --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printpreviewcontrol-control-overview-windows-forms.md @@ -0,0 +1,22 @@ +--- +title: "PrintPreviewControl Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "PrintPreviewControl" +helpviewer_keywords: + - "print preview" + - "PrintPreviewControl control" +ms.assetid: 4513c6c7-5e9b-4f4c-82ca-00f993a26955 +--- +# PrintPreviewControl Control Overview (Windows Forms) +The Windows Forms is used to display a [PrintDocument](printdocument-component-windows-forms.md) as it will appear when printed. This control has no buttons or other user interface elements, so typically you use the only if you wish to write your own print-preview user interface. If you want the standard user interface, use a control; see [PrintPreviewDialog Control Overview](printpreviewdialog-control-overview-windows-forms.md) for an overview. + +## Key Properties + The control's key property is , which sets the document to be previewed. The document must be a object. For an overview of creating documents for printing, see [PrintDocument Component Overview](printdocument-component-overview-windows-forms.md) and [Windows Forms Print Support](../advanced/windows-forms-print-support.md). The and properties determine the number of pages displayed horizontally and vertically on the control. Antialiasing can make the text appear smoother, but it can also make the display slower; to use it, set the property to `true`. + +## See also + +- +- [PrintPreviewDialog Control Overview](printpreviewdialog-control-overview-windows-forms.md) +- [PrintPreviewControl Control](printpreviewcontrol-control-windows-forms.md) +- [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/printpreviewcontrol-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printpreviewcontrol-control-windows-forms.md new file mode 100644 index 0000000000..e33b4486bd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printpreviewcontrol-control-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "PrintPreviewControl Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "printing [Windows Forms], print preview" + - "PrintPreviewControl control (using designer)" + - "PrintPreview control (using designer)" + - "print preview [Windows Forms], custom interface (using designer)" +ms.assetid: 3fdb2e46-92a3-4e26-bb8d-63a89087b337 +--- +# PrintPreviewControl Control (Windows Forms) +The Windows Forms `PrintPreviewControl` is used to display a document as it will appear when printed. This control has no buttons or other user interface elements, so typically you use the `PrintPreviewControl` only if you wish to write your own print-preview user interface. If you want the standard user interface, use a control. + +## In This Section + [PrintPreviewControl Control Overview](printpreviewcontrol-control-overview-windows-forms.md) + Introduces the general concepts of the `PrintPreviewControl`, which you can use to design your own print preview dialog or component. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [PrintPreviewDialog Control](printpreviewdialog-control-windows-forms.md) + Describes an alternate way to create print preview functionality. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/printpreviewdialog-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printpreviewdialog-control-overview-windows-forms.md new file mode 100644 index 0000000000..527f6e05a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printpreviewdialog-control-overview-windows-forms.md @@ -0,0 +1,55 @@ +--- +title: "PrintPreviewDialog Control Overview" +ms.date: "01/08/2018" +f1_keywords: + - "PrintPreviewDialog" +helpviewer_keywords: + - "PrintPreviewDialog control (using designer), about PrintPreviewDialog" +ms.assetid: efd4ee8d-6edd-47ec-88e4-4a4759bd2384 +--- +# PrintPreviewDialog control overview (Windows Forms) + +The Windows Forms control is a pre-configured dialog box used to display how a [PrintDocument](printdocument-component-windows-forms.md) will appear when printed. Use it within your Windows-based application as a simple solution instead of configuring your own dialog box. The control contains buttons for printing, zooming in, displaying one or multiple pages, and closing the dialog box. + +## Key properties and methods + +The control's key property is , which sets the document to be previewed. The document must be a object. In order to display the dialog box, you must call its method. Anti-aliasing can make the text appear smoother, but it can also make the display slower; to use it, set the property to `true`. + +Certain properties are available through the that the contains. (You do not have to add this to the form; it is automatically contained within the when you add the dialog to your form.) Examples of properties available through the are the and properties, which determine the number of pages displayed horizontally and vertically on the control. You can access the property as `PrintPreviewDialog1.PrintPreviewControl.Columns` in Visual Basic, `printPreviewDialog1.PrintPreviewControl.Columns` in Visual C#, or `printPreviewDialog1->PrintPreviewControl->Columns` in Visual C++. + +## PrintPreviewDialog performance + +Under the following conditions, the control initializes very slowly: + +- A network printer is used. +- User preferences for this printer, such as duplex settings, are modified. + +For apps running on the .NET Framework 4.5.2, you can add the following key to the \ section of your configuration file to improve the performance of control initialization: + +```xml + + + +``` + +If the `EnablePrintPreviewOptimization` key is set to any other value, or if the key is not present, the optimization is not applied. + +For apps running on the .NET Framework 4.6 or later versions, you can add the following switch to the [\](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element) element in the [\](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/runtime/index) section of your app config file: + +```xml + + + +``` + +If the switch is not present or if it is set to any other value, the optimization is not applied. + +If you use the event to modify printer settings, the performance of the control will not improve even if an optimization configuration switch is set. + +## See also + +- +- [PrintPreviewControl Control Overview](printpreviewcontrol-control-overview-windows-forms.md) +- [PrintPreviewDialog Control](printpreviewdialog-control-windows-forms.md) +- [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/printpreviewdialog-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/printpreviewdialog-control-windows-forms.md new file mode 100644 index 0000000000..0ba8d4e56d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/printpreviewdialog-control-windows-forms.md @@ -0,0 +1,33 @@ +--- +title: "PrintPreviewDialog Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "PrintPreviewDialog control (using designer)" + - "PrintPreview control (using designer)" + - "printing [Windows Forms], print preview (using designer)" + - "print preview [Windows Forms], default interface (using designer)" +ms.assetid: bfb5a3d7-021e-44f4-90f3-d435467f51d6 +--- +# PrintPreviewDialog Control (Windows Forms) +The Windows Forms `PrintPreviewDialog` control is a pre-configured dialog box used to display how a document will appear when printed. Use it within your Windows-based application as a simple solution in lieu of configuring your own dialog box. The control contains buttons for printing, zooming in, displaying one or multiple pages, and closing the dialog box. + +## In This Section + [PrintPreviewDialog Control Overview](printpreviewdialog-control-overview-windows-forms.md) + Introduces the general concepts of the `PrintPreviewDialog` control, which allows you to display a pre-configured dialog box that users can use to see a version of their document as it will look when it prints. + + [How to: Display Print Preview in Windows Forms Applications](how-to-display-print-preview-in-windows-forms-applications.md) + Explains how to view a page that is to be printed by using an instance of the `PrintPreviewDialog` control at run time. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Lists the different dialog-box controls for Windows Forms. + + [Dialog Boxes in Windows Forms](../dialog-boxes-in-windows-forms.md) + Describes how to create a dialog box for a Windows Form. diff --git a/dotnet-desktop-guide/framework/winforms/controls/programmatically-resize-cells-to-fit-content-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/programmatically-resize-cells-to-fit-content-in-the-datagrid.md new file mode 100644 index 0000000000..0829274f2b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/programmatically-resize-cells-to-fit-content-in-the-datagrid.md @@ -0,0 +1,49 @@ +--- +title: Programmatically Resize Cells to Fit Content in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data grids [Windows Forms], resizing cells to fit content" + - "cells [Windows Forms], resizing to fit contents" + - "DataGridView control [Windows Forms], resizing cells" + - "grids [Windows Forms], resizing cells to fit content" +ms.assetid: 63d770dc-b3f5-462b-901a-3125b2753792 +--- +# How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control +You can use the control methods to resize rows, columns, and headers so that they display their entire values without truncation. You can use these methods to resize elements at times of your choosing. Alternately, you can configure the control to resize these elements automatically whenever content changes. This can be inefficient, however, when you are working with large data sets or when your data changes frequently. For more information, see [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md). + + Typically, you will programmatically adjust elements to fit their content only when you load new data from a data source or when the user has edited a value. This is useful to optimize performance, but it is also useful when you want to enable your users to manually resize rows and columns with the mouse. + + The following code example demonstrates the options available to you for programmatic resizing. + +## Example + [!code-cpp[System.Windows.Forms.DataGridView.ProgrammaticResizing#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CPP/programmaticsizing.cpp#0)] + [!code-csharp[System.Windows.Forms.DataGridView.ProgrammaticResizing#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CS/programmaticsizing.cs#0)] + [!code-vb[System.Windows.Forms.DataGridView.ProgrammaticResizing#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/VB/programmaticsizing.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- +- +- [Resizing Columns and Rows in the Windows Forms DataGridView Control](resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md) +- [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md) +- [How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control](automatically-resize-cells-when-content-changes-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/programming-with-cells-rows-and-columns-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/programming-with-cells-rows-and-columns-in-the-datagrid.md new file mode 100644 index 0000000000..458600138d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/programming-with-cells-rows-and-columns-in-the-datagrid.md @@ -0,0 +1,54 @@ +--- +title: Programming with Cells, Rows, and Columns in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "data grids [Windows Forms], elements" + - "columns [Windows Forms], data grids" + - "cells [Windows Forms], data grids" + - "DataGridView control [Windows Forms], programming with grid elements" + - "rows [Windows Forms], data grids" +ms.assetid: 0d76f7e4-4149-42c6-9118-bb37d6669dc5 +--- +# Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control +This section provides topics that demonstrate various programming tasks involving cell, row, and column objects. + +## In This Section + [How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control](add-tooltips-to-individual-cells-in-a-wf-datagridview-control.md) + Describes how to handle the event to provide different ToolTips for individual cells. + + [How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control](perform-a-custom-action-based-on-changes-in-a-cell-of-a-datagrid.md) + Describes how to handle the and events. + + [How to: Manipulate Bands in the Windows Forms DataGridView Control](how-to-manipulate-bands-in-the-windows-forms-datagridview-control.md) + Describes how to program with objects of type , which is the base type for rows and columns. + + [How to: Manipulate Rows in the Windows Forms DataGridView Control](how-to-manipulate-rows-in-the-windows-forms-datagridview-control.md) + Describes how to program with objects of type `DataGridViewRow`. + + [How to: Manipulate Columns in the Windows Forms DataGridView Control](how-to-manipulate-columns-in-the-windows-forms-datagridview-control.md) + Describes how to program with objects of type `DataGridViewColumn`. + + [How to: Work with Image Columns in the Windows Forms DataGridView Control](how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md) + Describes how to program with the `DataGridViewImageColumn` class. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the class. + + + Provides reference documentation for the class. + + + Provides reference documentation for the class. + +## Related Sections + [Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control](basic-column-row-and-cell-features-wf-datagridview-control.md) + Provides topics that describe commonly used cell, row, and column properties. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/progressbar-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/progressbar-control-overview-windows-forms.md new file mode 100644 index 0000000000..9b9bf0a4b2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/progressbar-control-overview-windows-forms.md @@ -0,0 +1,35 @@ +--- +title: "ProgressBar Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ProgressBar" +helpviewer_keywords: + - "ProgressBar control [Windows Forms], about ProgressBar control" + - "progress controls [Windows Forms], about progress controls" +ms.assetid: a05d9cba-3a6a-4f8f-94b8-8ec12799fb80 +--- +# ProgressBar Control Overview (Windows Forms) +> [!IMPORTANT] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + The Windows Forms control indicates the progress of a process by displaying an appropriate number of rectangles arranged in a horizontal bar. When the process is complete, the bar is filled. Progress bars are commonly used to give the user an idea of how long to wait for a process to complete; for instance, when a large file is being loaded. + +> [!NOTE] +> The control can only be oriented horizontally on the form. + +## Key Properties and Methods + The key properties of the control are , , and . The and properties set the maximum and minimum values the progress bar can display. The property represents the progress that has been made toward completing the operation. Because the bar displayed in the control is composed of blocks, the value displayed by the control only approximates the property's current value. Based on the size of the control, the property determines when to display the next block. + + The most common way to update the current progress value is to write code to set the property. In the example of loading a large file, you might set the maximum to the size of the file in kilobytes. For example, if the property is set to 100, the property is set to 10, and the property is set to 50, 5 rectangles will be displayed. This is half of the number that can be displayed. + + However, there are other ways to modify the value displayed by the control, aside from setting the property directly. The property can be used to specify a value to increment the property by. Then, calling the method will increment the value. To vary the increment value, you can use the method and specify a value with which to increment the property. + + Another control that graphically informs the user about a current action is the control. + +> [!IMPORTANT] +> The and controls replace and add functionality to the and controls; however, the and controls are retained for both backward compatibility and future use, if you choose. + +## See also + +- +- [ProgressBar Control](progressbar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/progressbar-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/progressbar-control-windows-forms.md new file mode 100644 index 0000000000..b1cbd183db --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/progressbar-control-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "ProgressBar Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "progress controls" + - "ProgressBar control [Windows Forms]" +ms.assetid: 5be6b642-e8a6-4565-8ebd-ae73c7b10dc9 +--- +# ProgressBar Control (Windows Forms) +> [!IMPORTANT] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + The Windows Forms control indicates the progress of an action by displaying an appropriate number of rectangles arranged in a horizontal bar. When the action is complete, the bar is filled. Progress bars are commonly used to give the user an indication of how long to wait for a protracted action to complete—for instance, when a large file is being loaded. + +## In This Section + [ProgressBar Control Overview](progressbar-control-overview-windows-forms.md) + Introduces the general concepts of the control, which enables you to graphically display the progress of an operation. + + [How to: Set the Value Displayed by the Windows Forms ProgressBar Control](how-to-set-the-value-displayed-by-the-windows-forms-progressbar-control.md) + Discusses a number of different ways to increase the value displayed by the control. + +## Reference + + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/properties-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/controls/properties-in-windows-forms-controls.md new file mode 100644 index 0000000000..295a100252 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/properties-in-windows-forms-controls.md @@ -0,0 +1,49 @@ +--- +title: Properties of controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], properties overview (using code)" + - "controls [Windows Forms], properties" + - "properties [Windows Forms]" +ms.assetid: 2785279b-fb57-4937-8f6b-2050e475db6f +--- +# Properties in Windows Forms Controls +A Windows Forms control inherits many properties form the base class . These include properties such as , , , , , , , , , , , , and many others. For details about inherited properties, see . + + You can override inherited properties in your control as well as define new properties. + +## In This Section + [Defining a Property](defining-a-property-in-windows-forms-controls.md) + Shows how to implement a property for a custom control or component and shows how to integrate the property into the design environment. + + [Defining Default Values with the ShouldSerialize and Reset Methods](defining-default-values-with-the-shouldserialize-and-reset-methods.md) + Shows how to define default property values for a custom control or component. + + [Property-Changed Events](property-changed-events.md) + Describes how to enable property-change notifications when a property value changes. + + [How to: Expose Properties of Constituent Controls](how-to-expose-properties-of-constituent-controls.md) + Shows how to expose properties of constituent controls in a custom composite control. + + [Method Implementation in Custom Controls](method-implementation-in-custom-controls.md) + Describes how to implement methods in custom controls and components. + +## Reference + + Documents the base class for implementing composite controls. + + + Documents the attribute that specifies the to use for a custom property type. + + + Documents the attribute that specifies the to use for a custom property. + +## Related Sections + [Attributes in Windows Forms Controls](attributes-in-windows-forms-controls.md) + Describes the attributes you can apply to properties or other members of your custom controls and components. + + [Design-Time Attributes for Components](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/tk67c2t8(v=vs.120)) + Lists metadata attributes to apply to components and controls so that they are displayed correctly at design time in visual designers. + + [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)) + Describes how to implement classes such as editors and designers that provide design-time support. diff --git a/dotnet-desktop-guide/framework/winforms/controls/property-changed-events.md b/dotnet-desktop-guide/framework/winforms/controls/property-changed-events.md new file mode 100644 index 0000000000..b3ea87b2ba --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/property-changed-events.md @@ -0,0 +1,26 @@ +--- +title: "Property-Changed Events" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], property changes (using code)" + - "properties [Windows Forms], changes" +ms.assetid: 268039ec-5aaa-4d76-b902-acccb036c850 +--- +# Property-Changed Events +If you want your control to send notifications when a property named *PropertyName* changes, define an event named *PropertyName*`Changed` and a method named `On`*PropertyName*`Changed` that raises the event. The naming convention in Windows Forms is to append the word *Changed* to the name of the property. The associated event delegate type for property-changed events is , and the event data type is . The base class defines many property-changed events, such as , , , , and others. For background information about events, see [Events](https://docs.microsoft.com/dotnet/standard/events/index) and [Events in Windows Forms Controls](events-in-windows-forms-controls.md). + + Property-changed events are useful because they allow consumers of a control to attach event handlers that respond to the change. If your control needs to respond to a property-changed event that it raises, override the corresponding `On`*PropertyName*`Changed` method instead of attaching a delegate to the event. A control typically responds to a property-changed event by updating other properties or by redrawing some or all of its drawing surface. + + The following example shows how the `FlashTrackBar` custom control responds to some of the property-changed events that it inherits from . For the complete sample, see [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + + [!code-csharp[System.Windows.Forms.FlashTrackBar#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#2)] + [!code-vb[System.Windows.Forms.FlashTrackBar#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#2)] + +## See also + +- [Events](https://docs.microsoft.com/dotnet/standard/events/index) +- [Events in Windows Forms Controls](events-in-windows-forms-controls.md) +- [Properties in Windows Forms Controls](properties-in-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/providing-accessibility-information-for-controls-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/controls/providing-accessibility-information-for-controls-on-a-windows-form.md new file mode 100644 index 0000000000..8a8353b98b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/providing-accessibility-information-for-controls-on-a-windows-form.md @@ -0,0 +1,101 @@ +--- +title: "Providing Accessibility Information for Controls on a Windows Form" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, accessibility" + - "controls [Windows Forms], accessibility" + - "accessibility [Windows Forms], Windows Forms controls" +dev_langs: + - "csharp" + - "vb" + - "cpp" +ms.assetid: 887dee6f-5059-4d57-957d-7c6fcd4acb10 +--- +# Providing Accessibility Information for Controls on a Windows Form +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: + +- **AccessibilityObject** + +- **AccessibleDefaultActionDescription** + +- **AccessibleDescription** + +- **AccessibleName** + +- **AccessibleRole** + +## 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 this property for a button control: + +```vb +Button1.AccessibleDefaultActionDescription = _ + "Closes the application." +``` + +```csharp +Button1.AccessibleDefaultActionDescription = + "Closes the application."; +``` + +```cpp +button1->AccessibleDefaultActionDescription = + "Closes the application."; +``` + +## AccessibleDescription Property + This string describes the control. It 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'"; +``` + +```cpp +button1->AccessibleDescription = "A button with text 'Exit'"; +``` + +## AccessibleName Property + This is the name of a control reported to accessibility aids. It may be set in the Properties window, or in code as follows: + +```vb +Button1.AccessibleName = "Order" +``` + +```csharp +Button1.AccessibleName = "Order"; +``` + +```cpp +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; +``` + +```cpp +pictureBox1->AccessibleRole = AccessibleRole::Chart; +``` + +## See also + +- +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/putting-controls-on-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/putting-controls-on-windows-forms.md new file mode 100644 index 0000000000..0a903354fd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/putting-controls-on-windows-forms.md @@ -0,0 +1,37 @@ +--- +title: Put controls on forms +ms.date: "03/30/2017" +f1_keywords: + - "ENV.Window.Toolbox" +helpviewer_keywords: + - "Windows Forms controls, adding to form" +ms.assetid: 997508f2-87e5-4bec-a78e-9eec8f1fb15b +--- +# Putting Controls on Windows Forms +There are a wide variety of controls that you can put on Windows Forms, depending on the needs of your application. + +## In This Section + [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) + Gives directions for attaching controls to your form. + + [How to: Add Controls Without a User Interface to Windows Forms](how-to-add-controls-without-a-user-interface-to-windows-forms.md) + Gives directions for appending controls with no user interface to your application. + + [How to: Add to or Remove from a Collection of Controls at Run Time](how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time.md) + Explains how to add and remove controls on a panel at run time. + + [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md) + Demonstrates how you can make a custom component automatically appear in the **Toolbox** once the component is created. + + [How to: Add ActiveX Controls to Windows Forms](how-to-add-activex-controls-to-windows-forms.md) + Gives directions for working with legacy ActiveX controls. + + [Considerations When Hosting an ActiveX Control on a Windows Form](considerations-when-hosting-an-activex-control-on-a-windows-form.md) + Describes things to keep in mind when planning an application that uses ActiveX controls. + +## Related Sections + [Windows Forms Controls](index.md) + Provides links to introductory topics on controls and what you can do with them. + + [User Input Validation in Windows Forms](../user-input-validation-in-windows-forms.md) + Explains the basics of and theory behind validating the contents of Windows Forms controls. diff --git a/dotnet-desktop-guide/framework/winforms/controls/radiobutton-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/radiobutton-control-overview-windows-forms.md new file mode 100644 index 0000000000..ade21c232e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/radiobutton-control-overview-windows-forms.md @@ -0,0 +1,30 @@ +--- +title: "RadioButton Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "RadioButton" +helpviewer_keywords: + - "RadioButton control [Windows Forms], about RadioButton control" + - "RadioButton control [Windows Forms], determining state" + - "radio buttons [Windows Forms], determining state" + - "radio buttons [Windows Forms], about radio buttons" +ms.assetid: cd11f0c2-d098-4022-adf9-1455bc166a13 +--- +# RadioButton Control Overview (Windows Forms) +Windows Forms controls present a set of two or more mutually exclusive choices to the user. While radio buttons and check boxes may appear to function similarly, there is an important difference: when a user selects a radio button, the other radio buttons in the same group cannot be selected as well. In contrast, any number of check boxes can be selected. Defining a radio button group tells the user, "Here is a set of choices from which you can choose one and only one." + +## Using the Control + When a control is clicked, its property is set to `true` and the event handler is called. The event is raised when the value of the property changes. If the property is set to `true` (the default), when the radio button is selected all others in the group are automatically cleared. This property is usually only set to `false` when validation code is used to make sure the radio button selected is an allowable option. The text displayed within the control is set with the property, which can contain access key shortcuts. An access key enables a user to "click" the control by pressing the ALT key with the access key. For more information, see [How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md) and [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md). + + The control can appear like a command button, which appears to have been depressed if selected, if the property is set to . Radio buttons can also display images using the and properties. For more information, see [How to: Set the Image Displayed by a Windows Forms Control](how-to-set-the-image-displayed-by-a-windows-forms-control.md). + +## See also + +- +- [Panel Control Overview](panel-control-overview-windows-forms.md) +- [GroupBox Control Overview](groupbox-control-overview-windows-forms.md) +- [CheckBox Control Overview](checkbox-control-overview-windows-forms.md) +- [How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md) +- [How to: Set the Text Displayed by a Windows Forms Control](how-to-set-the-text-displayed-by-a-windows-forms-control.md) +- [How to: Group Windows Forms RadioButton Controls to Function as a Set](how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md) +- [RadioButton Control](radiobutton-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/radiobutton-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/radiobutton-control-windows-forms.md new file mode 100644 index 0000000000..c6a68af5f5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/radiobutton-control-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "RadioButton Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "checked list items [Windows Forms], Windows Forms controls" + - "list controls [Windows Forms], Windows Forms" + - "list items [Windows Forms], Windows Forms controls that display" + - "radio buttons" + - "RadioButton control [Windows Forms]" +ms.assetid: e895b2a5-9bcb-4486-b165-eaf4c3ea9644 +--- +# RadioButton Control (Windows Forms) +Windows Forms `RadioButton` controls present a set of two or more mutually exclusive choices to the user. While radio buttons and check boxes may appear to function similarly, there is an important difference: when a user selects a radio button, the other radio buttons in the same group cannot be selected as well. + +## In This Section + [RadioButton Control Overview](radiobutton-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Group Windows Forms RadioButton Controls to Function as a Set](how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md) + Explains how to group radio buttons as a set, of which only one may be selected. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/raise-change-notifications--bindingsource.md b/dotnet-desktop-guide/framework/winforms/controls/raise-change-notifications--bindingsource.md new file mode 100644 index 0000000000..b66aa82720 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/raise-change-notifications--bindingsource.md @@ -0,0 +1,40 @@ +--- +title: "How to: Raise Change Notifications Using a BindingSource and the INotifyPropertyChanged Interface" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "change notifications [Windows Forms], raising" + - "BindingSource component [Windows Forms], and IPropertyChange" + - "data sources [Windows Forms], detecting changes" + - "examples [Windows Forms], BindingSource component" + - "change notifications" + - "INotifyPropertyChanged interface [Windows Forms], using with BindingSource" + - "BindingSource component [Windows Forms], examples" +ms.assetid: 7fa2cf51-c09f-4375-adf0-e36c5617f099 +--- +# How to: Raise Change Notifications Using a BindingSource and the INotifyPropertyChanged Interface +The component automatically detects changes in a data source when the type contained in the data source implements and raises events when a property value is changed. This change detection is useful because controls bound to the automatically update as the data source values change. + +> [!NOTE] +> If your data source implements and you are performing asynchronous operations, you should not make changes to the data source on a background thread. Instead, you should read the data on a background thread and merge the data into a list on the UI thread. + +## Example + The following code example demonstrates a simple implementation of the interface. It also shows how the automatically passes a data source change to a bound control when the is bound to a list of the type. + + If you use the `CallerMemberName` attribute, calls to the `NotifyPropertyChanged` method don't have to specify the property name as a string argument. For more information, see [Caller Information (C#)](https://docs.microsoft.com/dotnet/csharp/language-reference/attributes/caller-information) or [Caller Information (Visual Basic)](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/concepts/caller-information). + + [!code-csharp[System.ComponentModel.IPropertyChangeExample#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/CS/Form1.cs#1)] + [!code-vb[System.ComponentModel.IPropertyChangeExample#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/VB/Form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- [BindingSource Component](bindingsource-component.md) +- [How to: Raise Change Notifications Using the BindingSource ResetItem Method](how-to-raise-change-notifications-using-the-bindingsource-resetitem-method.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md b/dotnet-desktop-guide/framework/winforms/controls/reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md new file mode 100644 index 0000000000..a5444a1e1c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md @@ -0,0 +1,37 @@ +--- +title: Reflect Data Source Updates in Control with BindingSource +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data binding [Windows Forms], updating" + - "BindingSource component [Windows Forms], updating data binding" + - "examples [Windows Forms], BindingSource component" + - "data sources [Windows Forms], updating" + - "BindingSource component [Windows Forms], examples" +ms.assetid: bd8bd9b2-af8a-4f11-a3d5-54eecbe2400b +--- +# How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource +When you use data-bound controls, you sometimes have to respond to changes in the data source when the data source does not raise list-changed events. When you use the component to bind your data source to a Windows Forms control, you can notify the control that your data source has changed by calling the method. + +## Example + The following code example demonstrates using the method to notify a bound control about an update in the data source. + + [!code-cpp[System.Windows.Forms.DataConnector.ResetBindings#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CPP/form1.cpp#1)] + [!code-csharp[System.Windows.Forms.DataConnector.ResetBindings#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnector.ResetBindings#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/VB/form1.vb#1)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [BindingSource Component](bindingsource-component.md) +- [How to: Bind a Windows Forms Control to a Type](how-to-bind-a-windows-forms-control-to-a-type.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/remove-autogenerated-columns-from-a-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/remove-autogenerated-columns-from-a-wf-datagridview-control.md new file mode 100644 index 0000000000..38180b34a0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/remove-autogenerated-columns-from-a-wf-datagridview-control.md @@ -0,0 +1,47 @@ +--- +title: Remove Autogenerated Columns from DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "DataGridView control [Windows Forms], removing columns" + - "columns [Windows Forms], removing" +ms.assetid: 92e28d98-95a3-446c-9150-41b7c7e5be15 +--- +# How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control +When your control is set to autogenerate its columns based on data from its data source, you can selectively omit certain columns. You can do this by calling the method on the collection. Alternatively, you can hide columns from view by setting the property to `false`. This technique is useful when you want to display the hidden columns in certain conditions, or when you need to access the data in the columns without displaying it. + +### To remove autogenerated columns + +- Call the method on the collection. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#111](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#111)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#111](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#111)] + +### To hide autogenerated columns + +- Set the column's property to `false`. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#112](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#112)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#112](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#112)] + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#110](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#110)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#110](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#110)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1` bound to a table that contains `Fax` and `CustomerID` columns, such as the `Customers` table in the Northwind sample database. + +- References to the and assemblies. + +## See also + +- +- +- +- +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/rendering-a-windows-forms-control.md b/dotnet-desktop-guide/framework/winforms/controls/rendering-a-windows-forms-control.md new file mode 100644 index 0000000000..6b0d8a274b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/rendering-a-windows-forms-control.md @@ -0,0 +1,116 @@ +--- +title: Render a control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], rendering" + - "OnPaintBackground method [Windows Forms], invoking in Windows Forms custom controls" + - "custom controls [Windows Forms], graphics resources" + - "custom controls [Windows Forms], invalidation and painting" +ms.assetid: aae8e1e6-4786-432b-a15e-f4c44760d302 +--- +# Rendering a Windows Forms Control +Rendering refers to the process of creating a visual representation on a user's screen. Windows Forms uses GDI (the new Windows graphics library) for rendering. The managed classes that provide access to GDI are in the namespace and its subnamespaces. + + 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 Functionality 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 Framework, see [Handling and Raising Events](https://docs.microsoft.com/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 object that represents the region to draw in. These objects are shown in bold in the following code fragment. + +```vb +Public Class PaintEventArgs + Inherits EventArgs + Implements IDisposable + + Public ReadOnly Property ClipRectangle() As System.Drawing.Rectangle + ... + End Property + + Public ReadOnly Property Graphics() As System.Drawing.Graphics + ... + End Property + ' Other properties and methods. + ... +End Class +``` + +```csharp +public class PaintEventArgs : EventArgs, IDisposable { +public System.Drawing.Rectangle ClipRectangle {get;} +public System.Drawing.Graphics Graphics {get;} +// Other properties and methods. +... +} +``` + + is a managed class that encapsulates drawing functionality, as described in the discussion of GDI later in this topic. 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 topic. + + 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. + +```vb +Protected Overridable Sub OnPaint(pe As PaintEventArgs) +``` + +```csharp +protected virtual void OnPaint(PaintEventArgs pe); +``` + + The method of the base class does not 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 should not invoke the base class's , as this introduces flicker. For an example of overriding the event, see the [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + +> [!NOTE] +> Do not 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`, a control redraws either some or all of its screen area. + + The base class defines another method that is useful for drawing — the method. + +```vb +Protected Overridable Sub OnPaintBackground(pevent As PaintEventArgs) +``` + +```csharp +protected virtual void OnPaintBackground(PaintEventArgs pevent); +``` + + paints the background (and thereby 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, is not a true event method. There is no `PaintBackground` event and does not invoke event delegates. When overriding the method, a derived class is not required to invoke the method of its base class. + +## GDI+ Basics + The class provides methods for drawing various shapes such as circles, triangles, arcs, and ellipses, as well as methods for displaying text. The namespace and its subnamespaces contain classes that encapsulate graphics elements such as shapes (circles, rectangles, arcs, and others), colors, fonts, brushes, and so on. For more information about GDI, see [Using Managed Graphics Classes](../advanced/using-managed-graphics-classes.md). The essentials of GDI are also described in the [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + +## 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 actually painted. (Remember that painting is done in the event method that takes a instance as its argument). 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 . + + The following code fragment shows how the `FlashTrackBar` custom control computes the rectangular area to draw in. The `client` variable denotes the property. For a complete sample, see [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + + [!code-csharp[System.Windows.Forms.FlashTrackBar#6](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#6)] + [!code-vb[System.Windows.Forms.FlashTrackBar#6](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#6)] + +## Freeing Graphics Resources + Graphics objects are expensive because they use system resources. Such objects include instances of the class as well as instances of , , and other graphics classes. It is important that you create a graphics resource only when you need it and release it soon as you are finished using it. If you create a type that implements the interface, call its method when you are finished with it in order to free resources. + + The following code fragment shows how the `FlashTrackBar` custom control creates and releases a resource. For the complete source code, see [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md). + + [!code-csharp[System.Windows.Forms.FlashTrackBar#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#5)] + [!code-vb[System.Windows.Forms.FlashTrackBar#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#5)] + + [!code-csharp[System.Windows.Forms.FlashTrackBar#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#4)] + [!code-vb[System.Windows.Forms.FlashTrackBar#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#4)] + + [!code-csharp[System.Windows.Forms.FlashTrackBar#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs#3)] + [!code-vb[System.Windows.Forms.FlashTrackBar#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb#3)] + +## See also + +- [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/rendering-controls-with-visual-styles.md b/dotnet-desktop-guide/framework/winforms/controls/rendering-controls-with-visual-styles.md new file mode 100644 index 0000000000..082e626176 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/rendering-controls-with-visual-styles.md @@ -0,0 +1,77 @@ +--- +title: "Rendering Controls with Visual Styles" +ms.date: "03/30/2017" +helpviewer_keywords: + - "professional appearance [Windows Forms], rendering Windows Forms controls" + - "themes [Windows Forms], XP visual styles in Window Forms" + - "custom controls [Windows Forms], rendering" + - "custom controls [Windows Forms], painting" + - "visual themes [Windows Forms], rendering Windows Forms controls" + - "user controls [Windows Forms], painting" + - "visual styles [Windows Forms], rendering Windows Forms controls" +ms.assetid: a5b178ba-610e-46c4-a6c0-509c0886a744 +--- +# Rendering Controls with Visual Styles +The .NET Framework provides support for rendering controls and other Windows user interface (UI) elements using visual styles in operating systems that support them. This topic discusses the several levels of support in the .NET Framework for rendering controls and other UI elements with the current visual style of the operating system. + +## Rendering Classes for Common Controls + Rendering a control refers to drawing the user interface of a control. The namespace provides the class for rendering some common Windows Forms controls. However, this class draws controls in the classic Windows style, which can make it difficult to maintain a consistent UI experience when drawing custom controls in applications with visual styles enabled. + + The .NET Framework 2.0 includes classes in the namespace that render the parts and states of common controls with visual styles. Each of these classes includes `static` methods for drawing the control or parts of the control in a particular state with the current visual style of the operating system. + + Some of these classes are designed to draw the related control regardless of whether visual styles are available. If visual styles are enabled, then the class members will draw the related control with visual styles; if visual styles are disabled, then the class members will draw the control in the classic Windows style. These classes include: + +- + +- + +- + +- + + Other classes can only draw the related control when visual styles are available, and their members will throw an exception if visual styles are disabled. These classes include: + +- + +- + +- + +- + +- + +- + + For more information on using these classes to draw a control, see [How to: Use a Control Rendering Class](how-to-use-a-control-rendering-class.md). + +## Visual Style Element and Rendering Classes + The namespace includes classes that can be used to draw and get information about any control or UI element that is supported by visual styles. Supported controls include common controls that have a rendering class in the namespace (see the previous section), as well as other controls, such as tab controls and rebar controls. Other supported UI elements include the parts of the **Start** menu, the taskbar, and the nonclient area of windows. + + The main classes of the namespace are and . is a foundation class for identifying any control or user interface element supported by visual styles. In addition to itself, the namespace includes many nested classes of with `static` properties that return a for every state of a control, control part, or other UI element supported by visual styles. + + provides the methods that draw and get information about each defined by the current visual style of the operating system. Information that can be retrieved about an element includes its default size, background type, and color definitions. wraps the functionality of the visual styles (UxTheme) API from the Windows Shell portion of the Windows Platform SDK. For more information, see [Enabling Visual Styles](/windows/desktop/controls/cookbook-overview). + + For more information about using and , see [How to: Render a Visual Style Element](how-to-render-a-visual-style-element.md). + +## Enabling Visual Styles + To enable visual styles for an application written for the .NET Framework version 1.0, programmers must include an application manifest that specifies that ComCtl32.dll version 6 or later will be used to draw controls. Applications built with the .NET Framework version 1.1 or later can use the method of the class. + +## Checking for Visual Styles Support + The property of the class indicates whether the current application is drawing controls with visual styles. When painting a custom control, you can check the value of to determine whether you should render your control with or without visual styles. The following table lists the four conditions that must exist for to return `true`. + +|Condition|Notes| +|---------------|-----------| +|The operating system supports visual styles.|To verify this condition separately, use the property of the class.| +|The user has enabled visual styles in the operating system.|To verify this condition separately, use the property of the class.| +|Visual styles are enabled in the application.|Visual styles can be enabled in an application by calling the method or by using an application manifest that specifies that ComCtl32.dll version 6 or later will be used to draw controls.| +|Visual styles are being used to draw the client area of application windows.|To verify this condition separately, use the property of the class and verify that it has the value or .| + + To determine when a user enables or disables visual styles, or switches from one visual style to another, check for the value in the handlers for the or events. + +> [!IMPORTANT] +> If you want to use to render a control or UI element when the user enables or switches visual styles, make sure that you do this when handling the event instead of the event. An exception will be thrown if you use the class when handling . + +## See also + +- [Custom Control Painting and Rendering](custom-control-painting-and-rendering.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..7d848bd77b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,39 @@ +--- +title: Resize columns and rows in DataGridView control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], sizing rows and columns" + - "columns [Windows Forms], resizing in grids" + - "data grids [Windows Forms], resizing columns and rows" +ms.assetid: 7532764d-e5c1-4943-a08b-6377a722d3b6 +--- +# Resizing Columns and Rows in the Windows Forms DataGridView Control +The `DataGridView` control provides numerous options for customizing the sizing behavior of its columns and rows. Typically, `DataGridView` cells do not resize based on their contents. Instead, they clip any display value that is larger than the cell. If the content can be displayed as a string, the cell displays it in a ToolTip. + + By default, users can drag row, column, and header dividers with the mouse to show more information. Users can also double-click a divider to automatically resize the associated row, column, or header band based on its contents. + + The `DataGridView` control provides properties, methods, and events that enable you to customize or disable all of these user-directed behaviors. Additionally, you can programmatically resize rows, columns, and headers to fit their contents, or you can configure them to automatically resize themselves whenever their contents change. You can also configure columns to automatically divide the available width of the control in proportions that you specify. + +## In This Section + [Sizing Options in the Windows Forms DataGridView Control](sizing-options-in-the-windows-forms-datagridview-control.md) + Describes the options for sizing rows, columns, and headers. Also provides details on sizing-related properties and methods, and describes common usage scenarios. + + [Column Fill Mode in the Windows Forms DataGridView Control](column-fill-mode-in-the-windows-forms-datagridview-control.md) + Describes column fill mode in detail, and provides demonstration code that you can use to experiment with column fill mode and other modes. + + [How to: Set the Sizing Modes of the Windows Forms DataGridView Control](how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md) + Describes how to configure the sizing modes for common purposes. + + [How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control](programmatically-resize-cells-to-fit-content-in-the-datagrid.md) + Provides demonstration code that you can use to experiment with programmatic resizing. + + [How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control](automatically-resize-cells-when-content-changes-in-the-datagrid.md) + Provides demonstration code that you can use to experiment with automatic sizing modes. + +## Reference + + Provides reference documentation for the control. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/richtextbox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/richtextbox-control-overview-windows-forms.md new file mode 100644 index 0000000000..e3140025f8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/richtextbox-control-overview-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "RichTextBox Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "RichTextBox" +helpviewer_keywords: + - "RichTextBox control [Windows Forms], about RichTextBox control" + - "text boxes [Windows Forms], about text boxes" +ms.assetid: 95081194-3dd4-4b84-9545-dd373e491eca +--- +# RichTextBox Control Overview (Windows Forms) +The Windows Forms control is used for displaying, entering, and manipulating text with formatting. The control does everything the control does, but it can also display fonts, colors, and links; load text and embedded images from a file; and find specified characters. The control is typically used to provide text manipulation and display features similar to word processing applications such as Microsoft Word. Like the control, the control can display scroll bars; but unlike the control, its default setting is to display both horizontal and vertical scrollbars as needed, and it has additional scrollbar settings. + +## Working with the RichTextBox Control + As with the control, the text displayed is set by the property. The control has numerous properties to format text. For details on these properties, see [How to: Set Font Attributes for the Windows Forms RichTextBox Control](how-to-set-font-attributes-for-the-windows-forms-richtextbox-control.md) and [How to: Set Indents, Hanging Indents, and Bulleted Paragraphs with the Windows Forms RichTextBox Control](set-indents-hanging-indents-bulleted-paragraphs-with-wf-richtextbox.md). To manipulate files, the and methods can display and write multiple file formats including plain text, Unicode plain text, and Rich Text Format (RTF). The possible file formats are listed in . You can use the method to find strings of text or specific characters. + + You can also use a control for Web-style links by setting the property to `true` and writing code to handle the event. For more information, see [How to: Display Web-Style Links with the Windows Forms RichTextBox Control](how-to-display-web-style-links-with-the-windows-forms-richtextbox-control.md). You can prevent the user from manipulating some or all of the text in the control by setting the property to `true`. + + You can undo and redo most edit operations in a control by calling the and methods. The method enables you to determine whether the last operation the user has undone can be reapplied to the control. + +## See also + +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [TextBox Control Overview](textbox-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/richtextbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/richtextbox-control-windows-forms.md new file mode 100644 index 0000000000..38ca99e753 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/richtextbox-control-windows-forms.md @@ -0,0 +1,50 @@ +--- +title: "RichTextBox Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "text boxes" + - "RichTextBox control [Windows Forms]" + - "rich edit controls" +ms.assetid: 3225f2ef-c6d9-4bd4-9d3e-2219e58edbf2 +--- +# RichTextBox Control (Windows Forms) +The Windows Forms `RichTextBox` control is used for displaying, entering, and manipulating text with formatting. The `RichTextBox` control does everything the control does, but it can also display fonts, colors, and links; load text and embedded images from a file; undo and redo editing operations; and find specified characters. The `RichTextBox` control is typically used to provide text manipulation and display features similar to word processing applications such as Microsoft Word. Like the control, the `RichTextBox` control can display scroll bars; but unlike the control, it displays both horizontal and vertical scrollbars by default and has additional scrollbar settings. + +## In This Section + [RichTextBox Control Overview](richtextbox-control-overview-windows-forms.md) + Introduces the general concepts of the `RichTextBox` control, which allows users to enter, display, and manipulate text with formatting options. + + [How to: Determine When Formatting Attributes Change in the Windows Forms RichTextBox Control](determine-when-formatting-attributes-change-wf-richtextbox-control.md) + Explains how to keep track of changes in font and paragraph formatting in the `RichTextBox` control. + + [How to: Display Scroll Bars in the Windows Forms RichTextBox Control](how-to-display-scroll-bars-in-the-windows-forms-richtextbox-control.md) + Describes the many choices available for scroll bars in the `RichTextBox` control. + + [How to: Display Web-Style Links with the Windows Forms RichTextBox Control](how-to-display-web-style-links-with-the-windows-forms-richtextbox-control.md) + Explains how to link to Web sites from the `RichTextBox` control. + + [How to: Enable Drag-and-Drop Operations with the Windows Forms RichTextBox Control](enable-drag-and-drop-operations-with-wf-richtextbox-control.md) + Provides instructions for dragging data into the `RichTextBox` control. + + [How to: Load Files into the Windows Forms RichTextBox Control](how-to-load-files-into-the-windows-forms-richtextbox-control.md) + Provides instructions for loading an existing file into the `RichTextBox` control. + + [How to: Save Files with the Windows Forms RichTextBox Control](how-to-save-files-with-the-windows-forms-richtextbox-control.md) + Provides instructions for saving the contents of the `RichTextBox` control to a file. + + [How to: Set Font Attributes for the Windows Forms RichTextBox Control](how-to-set-font-attributes-for-the-windows-forms-richtextbox-control.md) + Describes how to set the font family, size, style, and color of text in the `RichTextBox` control. + + [How to: Set Indents, Hanging Indents, and Bulleted Paragraphs with the Windows Forms RichTextBox Control](set-indents-hanging-indents-bulleted-paragraphs-with-wf-richtextbox.md) + Describes how to format paragraphs in the `RichTextBox` control. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [TextBox Control](textbox-control-windows-forms.md) + Introduces the general concepts of the control, which allows editable, multiline input from the user. diff --git a/dotnet-desktop-guide/framework/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component.md b/dotnet-desktop-guide/framework/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component.md new file mode 100644 index 0000000000..787228ab1a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/run-procedures-at-set-intervals-with-wf-timer-component.md @@ -0,0 +1,244 @@ +--- +title: Run Procedures at Set Intervals with Timer Component +description: Learn how use the Windows Form Timer component to run procedures at set intervals or when a set time interval has elapsed. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "examples [Windows Forms], timers" + - "timers [Windows Forms], event intervals" + - "initialization [Windows Forms], Timer components" + - "timers [Windows Forms], Windows-based" + - "Timer component [Windows Forms], initializing" + - "procedures [Windows Forms], specific time intervals" +ms.assetid: 8025247a-2de4-4d86-b8ab-a8cb8aeab2ea +--- +# How to: Run Procedures at Set Intervals with the Windows Forms Timer Component +You might sometimes want to create a procedure that runs at specific time intervals until a loop has finished or that runs when a set time interval has elapsed. The component makes such a procedure possible. + + This component is designed for a Windows Forms environment. If you need a timer that is suitable for a server environment, see [Introduction to Server-Based Timers](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/tb9yt5e6(v=vs.90)). + +> [!NOTE] +> There are some limitations when using the component. For more information, see [Limitations of the Windows Forms Timer Component's Interval Property](limitations-of-the-timer-component-interval-property.md). + +## To run a procedure at set intervals with the Timer component + +1. Add a to your form. See the following Example section for an illustration of how to do this programmatically. Visual Studio also has support for adding components to a form. Also see [How to: Add Controls Without a User Interface to Windows Forms](how-to-add-controls-without-a-user-interface-to-windows-forms.md). + +2. Set the property (in milliseconds) for the timer. This property determines how much time will pass before the procedure is run again. + + > [!NOTE] + > The more often a timer event occurs, the more processor time is used in responding to the event. This can slow down overall performance. Do not set a smaller interval than you need. + +3. Write appropriate code in the event handler. The code you write in this event will run at the interval specified in the property. + +4. Set the property to `true` to start the timer. The event will begin to occur, running your procedure at the set interval. + +5. At the appropriate time, set the property to `false` to stop the procedure from running again. Setting the interval to `0` does not cause the timer to stop. + +## Example + This first code example tracks the time of day in one-second increments. It uses a , a , and a component on a form. The property is set to 1000 (equal to one second). In the event, the label's caption is set to the current time. When the button is clicked, the property is set to `false`, stopping the timer from updating the label's caption. The following code example requires that you have a form with a control named `Button1`, a control named `Timer1`, and a control named `Label1`. + +```vb +Private Sub InitializeTimer() + ' Run this procedure in an appropriate event. + ' Set to 1 second. + Timer1.Interval = 1000 + ' Enable timer. + Timer1.Enabled = True + Button1.Text = "Enabled" +End Sub +x +Private Sub Timer1_Tick(ByVal Sender As Object, ByVal e As EventArgs) Handles Timer1.Tick +' Set the caption to the current time. + Label1.Text = DateTime.Now +End Sub + +Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + If Button1.Text = "Stop" Then + Button1.Text = "Start" + Timer1.Enabled = False + Else + Button1.Text = "Stop" + Timer1.Enabled = True + End If +End Sub +``` + +```csharp +private void InitializeTimer() +{ + // Call this procedure when the application starts. + // Set to 1 second. + Timer1.Interval = 1000; + Timer1.Tick += new EventHandler(Timer1_Tick); + + // Enable timer. + Timer1.Enabled = true; + + Button1.Text = "Stop"; + Button1.Click += new EventHandler(Button1_Click); +} + +private void Timer1_Tick(object Sender, EventArgs e) +{ + // Set the caption to the current time. + Label1.Text = DateTime.Now.ToString(); +} + +private void Button1_Click(object sender, EventArgs e) +{ + if ( Button1.Text == "Stop" ) + { + Button1.Text = "Start"; + Timer1.Enabled = false; + } + else + { + Button1.Text = "Stop"; + Timer1.Enabled = true; + } +} +``` + +```cpp +private: + void InitializeTimer() + { + // Run this procedure in an appropriate event. + // Set to 1 second. + timer1->Interval = 1000; + // Enable timer. + timer1->Enabled = true; + this->timer1->Tick += gcnew System::EventHandler(this, + &Form1::timer1_Tick); + + button1->Text = S"Stop"; + this->button1->Click += gcnew System::EventHandler(this, + &Form1::button1_Click); + } + + void timer1_Tick(System::Object ^ sender, + System::EventArgs ^ e) + { + // Set the caption to the current time. + label1->Text = DateTime::Now.ToString(); + } + + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + if ( button1->Text == "Stop" ) + { + button1->Text = "Start"; + timer1->Enabled = false; + } + else + { + button1->Text = "Stop"; + timer1->Enabled = true; + } + } +``` + +## Example + This second code example runs a procedure every 600 milliseconds until a loop has finished. The following code example requires that you have a form with a control named `Button1`, a control named `Timer1`, and a control named `Label1`. + +```vb +' This variable will be the loop counter. +Private counter As Integer + +Private Sub InitializeTimer() + ' Run this procedure in an appropriate event. + counter = 0 + Timer1.Interval = 600 + Timer1.Enabled = True +End Sub + +Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick + If counter => 10 Then + ' Exit loop code. + Timer1.Enabled = False + counter = 0 + Else + ' Run your procedure here. + ' Increment counter. + counter = counter + 1 + Label1.Text = "Procedures Run: " & counter.ToString + End If +End Sub +``` + +```csharp +// This variable will be the loop counter. +private int counter; + +private void InitializeTimer() +{ + // Run this procedure in an appropriate event. + counter = 0; + timer1.Interval = 600; + timer1.Enabled = true; + // Hook up timer's tick event handler. + this.timer1.Tick += new System.EventHandler(this.timer1_Tick); +} + +private void timer1_Tick(object sender, System.EventArgs e) +{ + if (counter >= 10) + { + // Exit loop code. + timer1.Enabled = false; + counter = 0; + } + else + { + // Run your procedure here. + // Increment counter. + counter = counter + 1; + label1.Text = "Procedures Run: " + counter.ToString(); + } +} +``` + +```cpp +private: + int counter; + + void InitializeTimer() + { + // Run this procedure in an appropriate event. + counter = 0; + timer1->Interval = 600; + timer1->Enabled = true; + // Hook up timer's tick event handler. + this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick); + } + + void timer1_Tick(System::Object ^ sender, + System::EventArgs ^ e) + { + if (counter >= 10) + { + // Exit loop code. + timer1->Enabled = false; + counter = 0; + } + else + { + // Run your procedure here. + // Increment counter. + counter = counter + 1; + label1->Text = String::Concat("Procedures Run: ", + counter.ToString()); + } + } +``` + +## See also + +- +- [Timer Component](timer-component-windows-forms.md) +- [Timer Component Overview](timer-component-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/savefiledialog-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/savefiledialog-component-overview-windows-forms.md new file mode 100644 index 0000000000..075e1b21cb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/savefiledialog-component-overview-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "SaveFileDialog Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "SaveFileDialog" +helpviewer_keywords: + - "Save File dialog box [Windows Forms], displaying" + - "SaveFileDialog component [Windows Forms], about SaveFileDialog" +ms.assetid: be7a625f-46fd-4d06-9985-b613dcbf9bd2 +--- +# SaveFileDialog Component Overview (Windows Forms) + +The Windows Forms component is a pre-configured dialog box. It is the same as the standard **Save File** dialog box used by Windows. It inherits from the class. + +## Working with the SaveFileDialog Component + +Use it as a simple solution for enabling users to save files instead of configuring your own dialog box. By relying on standard Windows dialog boxes, the basic functionality of applications you create is immediately familiar to users. Be aware, however, that when using the component, you must write your own file-saving logic. + +You can use the method to display the dialog box at run time. You can open a file in read/write mode using the method. + +When it is added to a form, the component appears in the tray at the bottom of the Windows Forms Designer in Visual Studio. + +## See also + +- +- [SaveFileDialog Component](savefiledialog-component-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/savefiledialog-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/savefiledialog-component-windows-forms.md new file mode 100644 index 0000000000..2ddde5b6b8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/savefiledialog-component-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "SaveFileDialog Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Save File dialog box" + - "SaveFileDialog component" +ms.assetid: 6f5d9321-37d7-4448-ac4c-a33c42b2a766 +--- +# SaveFileDialog Component (Windows Forms) +The Windows Forms component is a pre-configured dialog box. It is the same as the standard Save File dialog box used by Windows. It inherits from the class. + +## In This Section + [SaveFileDialog Component Overview](savefiledialog-component-overview-windows-forms.md) + Introduces the general concepts of the component, which allows you to display a pre-configured dialog that users can use to save a file to a specified location. + + [How to: Save Files Using the SaveFileDialog Component](how-to-save-files-using-the-savefiledialog-component.md) + Explains how to save a file via an instance of the component at run time. + +## Reference + class + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [Dialog-Box Controls and Components](dialog-box-controls-and-components-windows-forms.md) + Describes a set of controls and components that allow users to perform standard interactions with the application or system. diff --git a/dotnet-desktop-guide/framework/winforms/controls/selected-cells-rows-and-columns-datagridview.md b/dotnet-desktop-guide/framework/winforms/controls/selected-cells-rows-and-columns-datagridview.md new file mode 100644 index 0000000000..bcae1ca495 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/selected-cells-rows-and-columns-datagridview.md @@ -0,0 +1,61 @@ +--- +title: Get the Selected Cells, Rows, and Columns in DataGridView Control +description: "Learn how to get the selected cells, rows, or columns from a DataGridView control by using corresponding properties." +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "selection [Windows Forms], DataGridView control [Windows Forms]" + - "DataGridView control [Windows Forms], getting selection" + - "getting selection [Windows Forms], DataGridView control [Windows Forms]" +ms.assetid: d93c4b5b-498e-49bc-982a-2229d61778e4 +--- +# How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control +You can get the selected cells, rows, or columns from a control by using the corresponding properties: , , and . In the following procedures, you will get the selected cells and display their row and column indexes in a . + +### To get the selected cells in a DataGridView control + +- Use the property. + + > [!NOTE] + > Use the method to avoid showing a potentially large number of cells. + + [!code-csharp[System.Windows.Forms.DataGridViewSelectedCollections#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/CS/DataGridViewSelectedCollections.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewSelectedCollections#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/VB/DataGridViewSelectedCollections.vb#10)] + +### To get the selected rows in a DataGridView control + +- Use the property. To enable users to select rows, you must set the property to or . + + [!code-csharp[System.Windows.Forms.DataGridViewSelectedCollections#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/CS/DataGridViewSelectedCollections.cs#20)] + [!code-vb[System.Windows.Forms.DataGridViewSelectedCollections#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/VB/DataGridViewSelectedCollections.vb#20)] + +### To get the selected columns in a DataGridView control + +- Use the property. To enable users to select columns, you must set the property to or . + + [!code-csharp[System.Windows.Forms.DataGridViewSelectedCollections#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/CS/DataGridViewSelectedCollections.cs#30)] + [!code-vb[System.Windows.Forms.DataGridViewSelectedCollections#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/VB/DataGridViewSelectedCollections.vb#30)] + +## Compiling the Code + This example requires: + +- controls named `selectedCellsButton`, `selectedRowsButton`, and `selectedColumnsButton`, each with handlers for the event attached. + +- A control named `dataGridView1`. + +- References to the , , and assemblies. + +## Robust Programming + The collections described in this topic do not perform efficiently when large numbers of cells, rows, or columns are selected. For more information about using these collections with large amounts of data, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- +- +- +- +- [Selection and Clipboard Use with the Windows Forms DataGridView Control](selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..a1e297b12f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md @@ -0,0 +1,51 @@ +--- +title: Selection and Clipboard Use with DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], Clipboard use" + - "cells [Windows Forms], selecting in grids" + - "Clipboard [Windows Forms], in DataGridView control" + - "selection [Windows Forms], in DataGridView control" + - "data grids [Windows Forms], selecting cells" + - "DataGridView control [Windows Forms], selecting cells" +ms.assetid: 82cffcad-8b30-4897-bddb-c3a79d751b83 +--- +# Selection and Clipboard Use with the Windows Forms DataGridView Control +The `DataGridView` control provides you with a variety of options for configuring how users can select cells, rows, and columns. For example, you can enable single or multiple selection, selection of whole rows or columns when users click cells, or selection of whole rows or columns only when users click their headers, which enables cell selection as well. If you want to provide your own user interface for selection, you can disable ordinary selection and handle all selection programmatically. Additionally, you can enable users to copy the selected values to the Clipboard. + +## In This Section + [Selection Modes in the Windows Forms DataGridView Control](selection-modes-in-the-windows-forms-datagridview-control.md) + Describes the options for user and programmatic selection in the control. + + [How to: Set the Selection Mode of the Windows Forms DataGridView Control](how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md) + Describes how to configure the control for single-row selection when a user clicks a cell. + + [How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control](selected-cells-rows-and-columns-datagridview.md) + Describes how to work with the selected cell, row, and column collections. + + [How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control](enable-users-to-copy-multiple-cells-to-the-clipboard-datagridview.md) + Describes how to enable Clipboard support in the control. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the property. + + + Provides reference documentation for the property. + + + Provides reference documentation for the class. + + + Provides reference documentation for the class. + + + Provides reference documentation for the class. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control](default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/selection-modes-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/selection-modes-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..c966a87851 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/selection-modes-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,50 @@ +--- +title: Selection Modes in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "selection [Windows Forms], modes in DataGridView control" + - "DataGridView control [Windows Forms], selection mode" +ms.assetid: a3ebfd3d-0525-479d-9d96-d9e017289b36 +--- +# Selection Modes in the Windows Forms DataGridView Control + +Sometimes you want your application to perform actions based on user selections within a control. Depending on the actions, you may want to restrict the kinds of selection that are possible. For example, suppose your application can print a report for the currently selected record. In this case, you may want to configure the control so that clicking anywhere within a row always selects the entire row, and so that only one row at a time can be selected. + +You can specify the selections allowed by setting the property to one of the following enumeration values. + +|DataGridViewSelectionMode value|Description| +|-------------------------------------|-----------------| +||Clicking a cell selects it. Row and column headers cannot be used for selection.| +||Clicking a cell selects it. Clicking a column header selects the entire column. Column headers cannot be used for sorting.| +||Clicking a cell or a column header selects the entire column. Column headers cannot be used for sorting.| +||Clicking a cell or a row header selects the entire row.| +||Default selection mode. Clicking a cell selects it. Clicking a row header selects the entire row.| + +> [!NOTE] +> Changing the selection mode at run time automatically clears the current selection. + +By default, users can select multiple rows, columns, or cells by dragging with the mouse, pressing CTRL or SHIFT while selecting to extend or modify a selection, or clicking the top-left header cell to select all cells in the control. To prevent this behavior, set the property to `false`. + +The and modes allow users to delete rows by selecting them and pressing the DELETE key. Users can delete rows only when the current cell is not in edit mode, the property is set to `true`, and the underlying data source supports user-driven row deletion. Note that these settings do not prevent programmatic row deletion. + +## Programmatic Selection + +The current selection mode restricts the behavior of programmatic selection as well as user selection. You can change the current selection programmatically by setting the `Selected` property of any cells, rows, or columns present in the control. You can also select all cells in the control through the method, depending on the selection mode. To clear the selection, use the method. + +If the property is set to `true`, you can add elements to or remove them from the selection by changing the `Selected` property of the element. Otherwise, setting the `Selected` property to `true` for one element automatically removes other elements from the selection. + +Note that changing the value of the property does not alter the current selection. + +You can retrieve a collection of the currently selected cells, rows, or columns through the , , and properties of the control. Accessing these properties is inefficient when every cell in the control is selected. To avoid a performance penalty in this case, use the method first. Additionally, accessing these collections to determine the number of selected cells, rows, or columns can be inefficient. Instead, you should use the , , or method, passing in the value. + +> [!TIP] +> Example code that demonstrates the programmatic use of selected cells can be found in the class overview. + +## See also + +- +- +- +- +- [Selection and Clipboard Use with the Windows Forms DataGridView Control](selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md) +- [How to: Set the Selection Mode of the Windows Forms DataGridView Control](how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/serializing-collections-designerserializationvisibilityattribute.md b/dotnet-desktop-guide/framework/winforms/controls/serializing-collections-designerserializationvisibilityattribute.md new file mode 100644 index 0000000000..0898755369 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/serializing-collections-designerserializationvisibilityattribute.md @@ -0,0 +1,137 @@ +--- +title: "Walkthrough: Serializing Collections of Standard Types with the DesignerSerializationVisibilityAttribute" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "serialization [Windows Forms], collections" + - "standard types [Windows Forms], collections" + - "collections [Windows Forms], serializing" + - "collections [Windows Forms], standard types" +ms.assetid: 020c9df4-fdc5-4dae-815a-963ecae5668c +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Serialize collections of standard types + +Your custom controls will sometimes expose a collection as a property. This walkthrough demonstrates how to use the class to control how a collection is serialized at design time. Applying the value to your collection property ensures that the property will be serialized. + +To copy the code in this topic as a single listing, see [How to: Serialize Collections of Standard Types with the DesignerSerializationVisibilityAttribute](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/ms171833(v=vs.120)). + +## Prerequisites + +You need Visual Studio to complete this walkthrough. + +## Create a control with a serializable collection + +The first step is to create a control that has a serializable collection as a property. You can edit the contents of this collection using the **Collection Editor**, which you can access from the **Properties** window. + +1. In Visual Studio, create a Windows Control Library project, and name it **SerializationDemoControlLib**. + +2. Rename `UserControl1` to `SerializationDemoControl`. For more information, see [Rename a code symbol refactoring](/visualstudio/ide/reference/rename). + +3. In the **Properties** window, set the value of the property to **10**. + +4. Place a control in the `SerializationDemoControl`. + +5. Select the control. In the **Properties** window, set the following properties. + + |Property|Change to| + |--------------|---------------| + |**Multiline**|`true`| + |**Dock**|| + |**ScrollBars**|| + |**ReadOnly**|`true`| + +6. In the **Code Editor**, declare a string array field named `stringsValue` in `SerializationDemoControl`. + + [!code-cpp[System.ComponentModel.DesignerSerializationVisibilityAttribute#4](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/form1.cpp#4)] + [!code-csharp[System.ComponentModel.DesignerSerializationVisibilityAttribute#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/CS/form1.cs#4)] + [!code-vb[System.ComponentModel.DesignerSerializationVisibilityAttribute#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/VB/form1.vb#4)] + +7. Define the `Strings` property on the `SerializationDemoControl`. + + > [!NOTE] + > The value is used to enable serialization of the collection. + + [!code-cpp[System.ComponentModel.DesignerSerializationVisibilityAttribute#5](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/form1.cpp#5)] + [!code-csharp[System.ComponentModel.DesignerSerializationVisibilityAttribute#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/CS/form1.cs#5)] + [!code-vb[System.ComponentModel.DesignerSerializationVisibilityAttribute#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/VB/form1.vb#5)] + +8. Press **F5** to build the project and run your control in the **UserControl Test Container**. + +9. Find the **Strings** property in the of the **UserControl Test Container**. Select the **Strings** property, then select the ellipsis (![The Ellipsis button (...) in the Properties window of Visual Studio](./media/visual-studio-ellipsis-button.png)) button to open the **String Collection Editor**. + +10. Enter several strings in the **String Collection Editor**. Separate them by pressing the **Enter** key at the end of each string. Click **OK** when you are finished entering strings. + + > [!NOTE] + > The strings you typed appear in the of the `SerializationDemoControl`. + +## Serialize a collection property + +To test the serialization behavior of your control, you will place it on a form and change the contents of the collection with the **Collection Editor**. You can see the serialized collection state by looking at a special designer file into which the **Windows Forms Designer** emits code. + +1. Add a Windows Application project to the solution. Name the project `SerializationDemoControlTest`. + +2. In the **Toolbox**, find the tab named **SerializationDemoControlLib Components**. In this tab, you will find the `SerializationDemoControl`. For more information, see [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md). + +3. Place a `SerializationDemoControl` on your form. + +4. Find the `Strings` property in the **Properties** window. Click the `Strings` property, then click the ellipsis (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button to open the **String Collection Editor**. + +5. Type several strings in the **String Collection Editor**. Separate them by pressing **Enter** at the end of each string. Click **OK** when you are finished entering strings. + + > [!NOTE] + > The strings you typed appear in the of the `SerializationDemoControl`. + +6. In **Solution Explorer**, click the **Show All Files** button. + +7. Open the **Form1** node. Beneath it is a file called **Form1.Designer.cs** or **Form1.Designer.vb**. This is the file into which the **Windows Forms Designer** emits code representing the design-time state of your form and its child controls. Open this file in the **Code Editor**. + +8. Open the region called **Windows Form Designer generated code** and find the section labeled **serializationDemoControl1**. Beneath this label is the code representing the serialized state of your control. The strings you typed in step 5 appear in an assignment to the `Strings` property. The following code examples in C# and Visual Basic, show code similar to what you will see if you typed the strings "red", "orange", and "yellow". + + ```csharp + this.serializationDemoControl1.Strings = new string[] { + "red", + "orange", + "yellow"}; + ``` + + ```vb + Me.serializationDemoControl1.Strings = New String() {"red", "orange", "yellow"} + ``` + +9. In the **Code Editor**, change the value of the on the `Strings` property to . + + ```csharp + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + ``` + + ```vb + _ + ``` + +10. Rebuild the solution and repeat steps 3 and 4. + +> [!NOTE] +> In this case, the **Windows Forms Designer** emits no assignment to the `Strings` property. + +## Next steps + +Once you know how to serialize a collection of standard types, consider integrating your custom controls more deeply into the design-time environment. The following topics describe how to enhance the design-time integration of your custom controls: + +- [Design-Time Architecture](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/c5z9s1h4(v=vs.120)) + +- [Attributes in Windows Forms Controls](attributes-in-windows-forms-controls.md) + +- [Designer Serialization Overview](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/ms171834(v=vs.120)) + +- [Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md) + +## See also + +- +- [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/set-alternating-row-styles-for-the-datagrid-using-the-designer.md b/dotnet-desktop-guide/framework/winforms/controls/set-alternating-row-styles-for-the-datagrid-using-the-designer.md new file mode 100644 index 0000000000..06e843c788 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/set-alternating-row-styles-for-the-datagrid-using-the-designer.md @@ -0,0 +1,40 @@ +--- +title: Set Alternating Row Styles for DataGridView Control Using the Designer +ms.date: "03/30/2017" +helpviewer_keywords: + - "ledger-like formats" + - "DataGridView control [Windows Forms], row style alternation" + - "Windows Forms, rows" + - "rows [Windows Forms], alternating" + - "data [Windows Forms], displaying" +ms.assetid: 02373442-bf94-4470-9f8a-e44c4a9d5b88 +--- +# How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer + +Tabular data is often presented in a ledger-like format where alternating rows have different background colors. This format makes it easier for users to tell which cells are in each row, especially with wide tables that have many columns. + +With the control, you can specify complete style information for alternating rows. You can use style characteristics like foreground color and font, in addition to background color, to differentiate alternating rows. For more information, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + +The following procedure requires a **Windows Application** project with a form containing a control. For information about setting up such a project, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) and [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +### Define styles for alternating rows + +1. Select the control in the designer. + +2. In the **Properties** window, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) next to the property. + +3. In the **CellStyle Builder** dialog box, define the style by setting the properties, and use the **Preview** pane to confirm your choices. The styles you specify are used for every other row displayed in the control, starting with the second one. + +4. To define styles for the remaining rows, repeat steps 2 and 3 using the property. + + > [!NOTE] + > Cells are displayed using styles inherited from multiple properties. For more information about style inheritance, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + +## See also + +- +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [Using the Designer with the Windows Forms DataGridView Control](using-the-designer-with-the-windows-forms-datagridview-control.md) +- [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) +- [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/set-and-return-numeric-values-with-wf-numericupdown-control.md b/dotnet-desktop-guide/framework/winforms/controls/set-and-return-numeric-values-with-wf-numericupdown-control.md new file mode 100644 index 0000000000..2a7fb3a853 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/set-and-return-numeric-values-with-wf-numericupdown-control.md @@ -0,0 +1,94 @@ +--- +title: Set and Return Numeric Values with NumericUpDown Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "numeric values [Windows Forms], Windows Forms" + - "Windows Forms, numeric values" + - "Windows Forms controls, NumericUpDown" + - "NumericUpDown control [Windows Forms], setting and returning values" +ms.assetid: 5bd8f8cd-4c12-49ea-9cc3-2a647d064689 +--- +# How to: Set and Return Numeric Values with the Windows Forms NumericUpDown Control +The numeric value of the Windows Forms control is determined by its property. You can write conditional tests for the control's value just as with any other property. Once the property is set, you can adjust it directly by writing code to perform operations on it, or you can call the and methods. + +### To set the numeric value + +1. Assign a value to the property in code or in the Properties window. + + ```vb + NumericUpDown1.Value = 55 + ``` + + ```csharp + numericUpDown1.Value = 55; + ``` + + ```cpp + numericUpDown1->Value = 55; + ``` + + -or- + +2. Call the or method to increase or decrease the value by the amount specified in the property. + + ```vb + NumericUpDown1.UpButton() + ``` + + ```csharp + numericUpDown1.UpButton(); + ``` + + ```cpp + numericUpDown1->UpButton(); + ``` + +### To return the numeric value + +- Access the property in code. + + ```vb + If NumericUpDown1.Value >= 65 Then + MessageBox.Show("Age is: " & NumericUpDown1.Value.ToString) + Else + MessageBox.Show("The customer is ineligible for a senior citizen discount.") + End If + ``` + + ```csharp + if(numericUpDown1.Value >= 65) + { + MessageBox.Show("Age is: " + numericUpDown1.Value.ToString()); + } + else + { + MessageBox.Show("The customer is ineligible for a senior citizen discount."); + } + ``` + + ```cpp + if(numericUpDown1->Value >= 65) + { + MessageBox::Show(String::Concat("Age is: ", + numericUpDown1->Value.ToString())); + } + else + { + MessageBox::Show + ("The customer is ineligible for a senior citizen discount."); + } + ``` + +## See also + +- +- +- +- +- +- [NumericUpDown Control](numericupdown-control-windows-forms.md) +- [NumericUpDown Control Overview](numericupdown-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/set-indents-hanging-indents-bulleted-paragraphs-with-wf-richtextbox.md b/dotnet-desktop-guide/framework/winforms/controls/set-indents-hanging-indents-bulleted-paragraphs-with-wf-richtextbox.md new file mode 100644 index 0000000000..7226d00ef4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/set-indents-hanging-indents-bulleted-paragraphs-with-wf-richtextbox.md @@ -0,0 +1,69 @@ +--- +title: Set Indents, Hanging Indents, and Bulleted Paragraphs with RichTextBox Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "text boxes [Windows Forms], setting indents" + - ".rtf files [Windows Forms], formatting in RichTextBox control" + - "examples [Windows Forms], text boxes" + - "RTF files [Windows Forms], formatting in RichTextBox control" + - "RichTextBox control [Windows Forms], setting indents and bullets" + - "text boxes [Windows Forms], bullets" +ms.assetid: abfb40e6-5642-4691-8ec1-9d9ae91688dc +--- +# How to: Set Indents, Hanging Indents, and Bulleted Paragraphs with the Windows Forms RichTextBox Control +The Windows Forms control has numerous options for formatting the text it displays. You can format selected paragraphs as bulleted lists by setting the property. You can also use the , , and properties to set the indentation of paragraphs relative to the left and right edges of the control, and the left edge of other lines of text. + +### To format a paragraph as a bulleted list + +1. Set the property to `true`. + + ```vb + RichTextBox1.SelectionBullet = True + ``` + + ```csharp + richTextBox1.SelectionBullet = true; + ``` + + ```cpp + richTextBox1->SelectionBullet = true; + ``` + +### To indent a paragraph + +1. Set the property to an integer representing the distance in pixels between the left edge of the control and the left edge of the text. + +2. Set the property to an integer representing the distance in pixels between the left edge of the first line of text in the paragraph and the left edge of subsequent lines in the same paragraph. The value of the property only applies to lines in a paragraph that have wrapped below the first line. + +3. Set the property to an integer representing the distance in pixels between the right edge of the control and the right edge of the text. + + ```vb + RichTextBox1.SelectionIndent = 8 + RichTextBox1.SelectionHangingIndent = 3 + RichTextBox1.SelectionRightIndent = 12 + ``` + + ```csharp + richTextBox1.SelectionIndent = 8; + richTextBox1.SelectionHangingIndent = 3; + richTextBox1.SelectionRightIndent = 12; + ``` + + ```cpp + richTextBox1->SelectionIndent = 8; + richTextBox1->SelectionHangingIndent = 3; + richTextBox1->SelectionRightIndent = 12; + ``` + + > [!NOTE] + > All these properties affect any paragraphs that contain selected text, and also the text that is typed after the current insertion point. For example, when a user selects a word within a paragraph and then adjusts the indentation, the new settings will apply to the entire paragraph that contains that word, and also to any paragraphs subsequently entered after the selected paragraph. For information about selecting text programmatically, see . + +## See also + +- +- [RichTextBox Control](richtextbox-control-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/set-the-sort-modes-for-columns-wf-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/set-the-sort-modes-for-columns-wf-datagridview-control.md new file mode 100644 index 0000000000..ef222c3c76 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/set-the-sort-modes-for-columns-wf-datagridview-control.md @@ -0,0 +1,40 @@ +--- +title: Set the Sort Modes for Columns in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sorting [Windows Forms], data grids" + - "DataGridView control [Windows Forms], sort mode" + - "data grids [Windows Forms], sorting data" +ms.assetid: 57dfed60-a608-40d5-86f9-d65686ffb325 +--- +# How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control +In the control, text box columns use automatic sorting by default, while other column types are not sorted automatically. Sometimes you will want to override these defaults. For example, you can display images in place of text, numbers, or enumeration cell values. While the images cannot be sorted, the underlying values that they represent can be sorted. + + In the control, the property value of a column determines its sorting behavior. + + The following procedure shows the `Priority` column from [How to: Customize Data Formatting in the Windows Forms DataGridView Control](how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md). This column is an image column and is not sortable by default. It contains actual cell values that are strings, however, so it can be sorted automatically. + +### To set the sort mode for a column + +- Set the property. + + [!code-csharp[System.Windows.Forms.DataGridViewMisc#066](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#066)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#066](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#066)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1` that contains a column named `Priority`. + +- References to the and assemblies. + +## See also + +- +- +- [Sorting Data in the Windows Forms DataGridView Control](sorting-data-in-the-windows-forms-datagridview-control.md) +- [Column Sort Modes in the Windows Forms DataGridView Control](column-sort-modes-in-the-windows-forms-datagridview-control.md) +- [How to: Customize Sorting in the Windows Forms DataGridView Control](how-to-customize-sorting-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/sizing-options-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/sizing-options-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..f9e4f1ed96 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/sizing-options-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,155 @@ +--- +title: Sizing Options in DataGridView Control +description: Learn about sizing options in the Windows Forms DataGridView control. DataGridView rows, columns, and headers change size as a result of different occurrences. +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], row sizing" + - "data grids [Windows Forms], column sizing" + - "DataGridView control [Windows Forms], column sizing" + - "DataGridView control [Windows Forms], sizing options" + - "data grids [Windows Forms], row sizing" + - "data grids [Windows Forms], sizing options" +ms.assetid: a5620a9c-0d06-41e3-8934-c25ddb16c9e6 +--- +# Sizing Options in the Windows Forms DataGridView Control + rows, columns, and headers can change size as a result of many different occurrences. The following table shows these occurrences. + +|Occurrence|Description| +|----------------|-----------------| +|User resize|Users can make size adjustments by dragging or double-clicking row, column, or header dividers.| +|Control resize|In column fill mode, column widths change when the control width changes; for example, when the control is docked to its parent form and the user resizes the form.| +|Cell value change|In content-based automatic sizing modes, sizes change to fit new display values.| +|Method call|Programmatic content-based resizing lets you make opportunistic size adjustments based on cell values at the time of the method call.| +|Property setting|You can also set specific height and width values.| + + By default, user resizing is enabled, automatic sizing is disabled, and cell values that are wider than their columns are clipped. + + The following table shows scenarios that you can use to adjust the default behavior or to use specific sizing options to achieve particular effects. + +|Scenario|Implementation| +|--------------|--------------------| +|Use column fill mode for displaying similarly sized data in a relatively small number of columns that occupy the entire width of the control without displaying the horizontal scroll bar.|Set the property to .| +|Use column fill mode with display values of varying sizes.|Set the property to . Initialize relative column widths by setting the column properties or by calling the control method after filling the control with data.| +|Use column fill mode with values of varying importance.|Set the property to . Set large values for columns that must always display some of their data or use a sizing option other than fill mode for specific columns.| +|Use column fill mode to avoid displaying the control background.|Set the property of the last column to and use other sizing options for the other columns. If the other columns use too much of the available space, set the property of the last column.| +|Display a fixed-width column, such as an icon or ID column.|Set to and to for the column. Initialize its width by setting the property or by calling the control method after filling the control with data.| +|Adjust sizes automatically whenever cell contents change to avoid clipping and to optimize the use of space.|Set an automatic sizing property to a value that represents a content-based sizing mode. To avoid a performance penalty when working with large amounts of data, use a sizing mode that calculates displayed rows only.| +|Adjust sizes to fit values in displayed rows to avoid performance penalties when working with many rows.|Use the appropriate sizing-mode enumeration values with automatic or programmatic resizing. To adjust sizes to fit values in newly displayed rows while scrolling, call a resizing method in a event handler. To customize user double-click resizing so that only values in displayed rows determine the new sizes, call a resizing method in a or event handler.| +|Adjust sizes to fit cell contents only at specific times to avoid performance penalties or to enable user resizing.|Call a content-based resizing method in an event handler. For example, use the event to initialize sizes after binding, and handle the or event to adjust sizes to compensate for user edits or changes in a bound data source.| +|Adjust row heights for multiline cell contents.|Ensure that column widths are appropriate for displaying paragraphs of text and use automatic or programmatic content-based row sizing to adjust the heights. Also ensure that cells with multiline content are displayed using a cell style value of .

Typically, you will use an automatic column sizing mode to maintain column widths or set them to specific widths before row heights are adjusted.| + +## Resizing with the Mouse + By default, users can resize rows, columns, and headers that do not use an automatic sizing mode based on cell values. To prevent users from resizing with other modes, such as column fill mode, set one or more of the following properties: + +- + +- + +- + +- + + You can also prevent users from resizing individual rows or columns by setting their properties. By default, the property value is based on the property value for columns and the property value for rows. If you explicitly set to or , however, the specified value overrides the control value is for that row or column. Set to to restore the inheritance. + + Because restores the value inheritance, the property will never return a value unless the row or column has not been added to a control. If you need to determine whether the property value of a row or column is inherited, examine its property. If the value includes the flag, the property value is not inherited. + +## Automatic Sizing + There are two kinds of automatic sizing in the control: column fill mode and content-based automatic sizing. + + Column fill mode causes the visible columns in the control to fill the width of the control's display area. For more information about this mode, see [Column Fill Mode in the Windows Forms DataGridView Control](column-fill-mode-in-the-windows-forms-datagridview-control.md). + + You can also configure rows, columns, and headers to automatically adjust their sizes to fit their cell contents. In this case, size adjustment occurs whenever cell contents change. + +> [!NOTE] +> If you maintain cell values in a custom data cache using virtual mode, automatic sizing occurs when the user edits a cell value but does not occur when you alter a cached value outside of a event handler. In this case, call the method to force the control to update the cell display and apply the current automatic sizing modes. + + If content-based automatic sizing is enabled for one dimension only—that is, for rows but not columns, or for columns but not rows—and is also enabled, size adjustment also occurs whenever the other dimension changes. For example, if rows but not columns are configured for automatic sizing and is enabled, users can drag column dividers to change the width of a column and row heights will automatically adjust so that cell contents are still fully displayed. + + If you configure both rows and columns for content-based automatic sizing and is enabled, the control will adjust sizes whenever cell contents changed and will use an ideal cell height-to-width ratio when calculating new sizes. + + To configure the sizing mode for headers and rows and for columns that do not override the control value, set one or more of the following properties: + +- + +- + +- + +- + + To override the control's column sizing mode for an individual column, set its property to a value other than . The sizing mode for a column is actually determined by its property. The value of this property is based on the column's property value unless that value is , in which case the control's value is inherited. + + Use content-based automatic resizing with caution when working with large amounts of data. To avoid performance penalties, use the automatic sizing modes that calculate sizes based only on the displayed rows rather than analyzing every row in the control. For maximum performance, use programmatic resizing instead so that you can resize at specific times, such as immediately after new data is loaded. + + Content-based automatic sizing modes do not affect rows, columns, or headers that you have hidden by setting the row or column property or the control or properties to `false`. For example, if a column is hidden after it is automatically sized to fit a large cell value, the hidden column will not change its size if the row containing the large cell value is deleted. Automatic sizing does not occur when visibility changes, so changing the column property back to `true` will not force it to recalculate its size based on its current contents. + + Programmatic content-based resizing affects rows, columns, and headers regardless of their visibility. + +## Programmatic Resizing + When automatic sizing is disabled, you can programmatically set the exact width or height of rows, columns, or headers through the following properties: + +- + +- + +- + +- + + You can also programmatically resize rows, columns, and headers to fit their contents using the following methods: + +- + +- + +- + +- + +- + +- + + These methods will resize rows, columns, or headers once rather than configuring them for continuous resizing. The new sizes are automatically calculated to display all cell contents without clipping. When you programmatically resize columns that have property values of , however, the calculated content-based widths are used to proportionally adjust the column property values, and the actually column widths are then calculated according to these new proportions so that all columns fill the available display area of the control. + + Programmatic resizing is useful to avoid performance penalties with continuous resizing. It is also useful to provide initial sizes for user-resizable rows, columns, and headers, and for column fill mode. + + You will typically call the programmatic resizing methods at specific times. For example, you might programmatically resize all columns immediately after loading data, or you might programmatically resize a specific row after a particular cell value has been modified. + +## Customizing Content-based Sizing Behavior + You can customize sizing behaviors when working with derived cell, row, and column types by overriding the , , or methods or by calling protected resizing method overloads in a derived control. The protected resizing method overloads are designed to work in pairs to achieve an ideal cell height-to-width ratio, avoiding overly wide or tall cells. For example, if you call the `AutoResizeRows(DataGridViewAutoSizeRowsMode,Boolean)` overload of the method and pass in a value of `false` for the parameter, the overload will calculate the ideal heights and widths for cells in the row, but it will adjust the row heights only. You must then call the method to adjust the column widths to the calculated ideal. + +## Content-based Sizing Options + The enumerations used by sizing properties and methods have similar values for content-based sizing. With these values, you can limit which cells are used to calculate the preferred sizes. For all sizing enumerations, values with names that refer to displayed cells limit their calculations to cells in displayed rows. Excluding rows is useful to avoid a performance penalty when you are working with a large quantity of rows. You can also restrict calculations to cell values in header or nonheader cells. + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- [Resizing Columns and Rows in the Windows Forms DataGridView Control](resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md) +- [Column Fill Mode in the Windows Forms DataGridView Control](column-fill-mode-in-the-windows-forms-datagridview-control.md) +- [How to: Set the Sizing Modes of the Windows Forms DataGridView Control](how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/sort-and-filter-ado-net-data-with-wf-bindingsource-component.md b/dotnet-desktop-guide/framework/winforms/controls/sort-and-filter-ado-net-data-with-wf-bindingsource-component.md new file mode 100644 index 0000000000..8cb808b6dd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/sort-and-filter-ado-net-data-with-wf-bindingsource-component.md @@ -0,0 +1,55 @@ +--- +title: Sort and Filter ADO.NET Data with BindingSource Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "sorting data" + - "data sorting [Windows Forms], ADO.NET" + - "data [Windows Forms], filtering" + - "BindingSource component [Windows Forms], sorting and filtering data" + - "filtering [Windows Forms], ADO.NET" + - "data [Windows Forms], sorting" + - "ADO.NET [Windows Forms]" +ms.assetid: 6c206daf-d706-4602-9dbe-435343052063 +--- +# How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component +You can expose the sorting and filtering capability of control through the and properties. You can apply simple sorting when the underlying data source is an , and you can apply filtering and advanced sorting when the data source is an . The property requires standard ADO.NET syntax: a string representing the name of a column of data in the data source followed by `ASC` or `DESC` to indicate whether the list should be sorted in ascending or descending order. You can set advanced sorting or multiple-column sorting by separating each column with a comma separator. The property takes a string expression. + +> [!NOTE] +> Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + +### To filter data with the BindingSource + +- Set the property to expression that you want. + + In the following code example, the expression is a column name followed by value that you want for the column. + + [!code-csharp[System.Windows.Forms.DataConnectorFilterAndSort#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/CS/form1.cs#11)] + [!code-vb[System.Windows.Forms.DataConnectorFilterAndSort#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/VB/form1.vb#11)] + +### To sort data with the BindingSource + +1. Set the property to the column name that you want followed by `ASC` or `DESC` to indicate the ascending or descending order. + +2. Separate multiple columns with a comma. + + [!code-csharp[System.Windows.Forms.DataConnectorFilterAndSort#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/CS/form1.cs#12)] + [!code-vb[System.Windows.Forms.DataConnectorFilterAndSort#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/VB/form1.vb#12)] + +## Example + The following code example loads data from the Customers table of the Northwind sample database into a control, and filters and sorts the displayed data. + + [!code-csharp[System.Windows.Forms.DataConnectorFilterAndSort#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/CS/form1.cs#1)] + [!code-vb[System.Windows.Forms.DataConnectorFilterAndSort#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/VB/form1.vb#1)] + +## Compiling the Code + To run this example, paste the code into a form that contains a named `BindingSource1` and a named `dataGridView1`. Handle the event for the form and call `InitializeSortedFilteredBindingSource` in the load event handler method. + +## See also + +- +- +- [How to: Install Sample Databases](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/8b6y4c7s(v=vs.120)) +- [BindingSource Component](bindingsource-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md new file mode 100644 index 0000000000..8211a4dae4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md @@ -0,0 +1,31 @@ +--- +title: Sort the Contents of ComboBox, ListBox, or CheckedListBox Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "CheckedListBox control [Windows Forms], sorting" + - "ComboBox control [Windows Forms], sorting contents" + - "combo boxes [Windows Forms], sorting contents" + - "list boxes [Windows Forms], sorting contents" + - "ListBox control [Windows Forms], sorting contents" +ms.assetid: c268e387-3d1d-4d86-a940-19f6673c8d06 +--- +# How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control +Windows Forms controls do not sort when they are data-bound. To display sorted data, use a data source that supports sorting and then have the data source sort it. Data sources that support sorting are data views, data view managers, and sorted arrays. + + If the control is not data-bound, you can sort it. + +### To sort the list + +1. Set the `Sorted` property to `true`. + + This setting repositions all existing list items in sorted order. + +## See also + +- +- +- +- [Windows Forms Data Binding](../windows-forms-data-binding.md) +- [How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control](add-and-remove-items-from-a-wf-combobox.md) +- [When to Use a Windows Forms ComboBox Instead of a ListBox](when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/sorting-data-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/sorting-data-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..4405b30c61 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/sorting-data-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,42 @@ +--- +title: Sorting data in DataGridView control +ms.date: "02/13/2018" +helpviewer_keywords: + - "data [Windows Forms], sorting in grids" + - "data grids [Windows Forms], sorting data" + - "DataGridView control [Windows Forms], sorting data" +ms.assetid: c1d4f24c-d961-4181-809d-5a5caa6122e4 +--- +# Sorting data in the Windows Forms DataGridView control + +By default, users can sort the data in a control by clicking the header of a text box column (or by pressing F3 when a text box cell is focused on .NET Framework 4.7.2 and later versions). You can modify the property of specific columns to allow users to sort by other column types when it makes sense to do so. You can also sort the data programmatically by any column, or by multiple columns. + +## In this section + +[Column Sort Modes in the Windows Forms DataGridView Control](column-sort-modes-in-the-windows-forms-datagridview-control.md) +Describes the options for sorting data in the control. + +[How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control](set-the-sort-modes-for-columns-wf-datagridview-control.md) +Describes how to enable users to sort by columns that are not sortable by default. + +[How to: Customize Sorting in the Windows Forms DataGridView Control](how-to-customize-sorting-in-the-windows-forms-datagridview-control.md) +Describes how to sort data programmatically and how to customize sorting by using the event or by implementing the interface. + +## Reference + + +Provides reference documentation for the control. + + +Provides reference documentation for the method. + + +Provides reference documentation for the property. + + +Provides reference documentation for the enumeration. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) +- [Column Types in the Windows Forms DataGridView Control](column-types-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/soundplayer-class-overview.md b/dotnet-desktop-guide/framework/winforms/controls/soundplayer-class-overview.md new file mode 100644 index 0000000000..01b4386327 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/soundplayer-class-overview.md @@ -0,0 +1,34 @@ +--- +title: "SoundPlayer Class Overview" +ms.date: "03/30/2017" +helpviewer_keywords: + - "playing sounds [Windows Forms], SoundPlayer class" + - "SoundPlayer class [Windows Forms], about SoundPlayer class" + - "sounds [Windows Forms], playing" +ms.assetid: fcebb938-62b9-4677-9cbe-6465bc863e22 +--- +# SoundPlayer Class Overview +The class enables you to easily include sounds in your applications. + + The class can play sound files in the .wav format, either from a resource or from UNC or HTTP locations. Additionally, the class enables you to load or play sounds asynchronously. + + You can also use the class to play common system sounds, including a beep. + +## Commonly Used Properties, Methods, and Events + +|Name|Description| +|----------|-----------------| +| property|The file path or Web address of the sound. Acceptable values can be UNC or HTTP.| +| property|The number of milliseconds your program will wait to load a sound before it throws an exception. The default is 10 seconds.| +| property|A Boolean value indicating whether the sound has finished loading.| +| method|Loads a sound synchronously.| +| method|Begins to load a sound asynchronously. When loading is complete, it raises the event.| +| method|Plays the sound specified in the or property in a new thread.| +| method|Plays the sound specified in the or property in the current thread.| +| method|Stops any sound currently playing.| +| event|Raised after the load of a sound is attempted.| + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/soundplayer-class.md b/dotnet-desktop-guide/framework/winforms/controls/soundplayer-class.md new file mode 100644 index 0000000000..e1af07425a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/soundplayer-class.md @@ -0,0 +1,50 @@ +--- +title: "SoundPlayer Class" +ms.date: "03/30/2017" +f1_keywords: + - "SoundPlayer" +helpviewer_keywords: + - "sounds [Windows Forms], playing" +ms.assetid: f3945af9-045c-4e2d-b251-377c37ca2d77 +--- +# SoundPlayer Class +The `SoundPlayer` class enables you to easily include sounds in your applications. + + You can also use the class to play common system sounds, including a beep. + +## In This Section + [SoundPlayer Class Overview](soundplayer-class-overview.md) + Introduces the class and its commonly used properties, methods, and events. + + [How to: Play a Sound from a Windows Form](how-to-play-a-sound-from-a-windows-form.md) + Provides code to play a sound specified via a file path, UNC path, or HTTP path. + + [How to: Play a Beep from a Windows Form](how-to-play-a-beep-from-a-windows-form.md) + Provides code to play the computer's beep sound. + + [How to: Play a Sound Embedded in a Resource from a Windows Form](how-to-play-a-sound-embedded-in-a-resource-from-a-windows-form.md) + Provides code to play a sound from a resource. + + [How to: Play a System Sound from a Windows Form](how-to-play-a-system-sound-from-a-windows-form.md) + Provides code to play the one of the system sounds. + + [How to: Load a Sound Asynchronously within a Windows Form](how-to-load-a-sound-asynchronously-within-a-windows-form.md) + Provides code to load a sound asynchronously from a URL and play it. + + [How to: Loop a Sound Playing on a Windows Form](how-to-loop-a-sound-playing-on-a-windows-form.md) + Provides code that plays a sound repeatedly. + +## Reference + + Describes this class and has links to all its members. + +## Related Sections + [Windows Forms Controls](index.md) + Provides links to topics about the controls designed specifically to work with Windows Forms. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + +## See also + +- [My.Computer Object](https://docs.microsoft.com/dotnet/visual-basic/language-reference/objects/my-computer-object) diff --git a/dotnet-desktop-guide/framework/winforms/controls/specify-default-values-for-new-rows-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/specify-default-values-for-new-rows-in-the-datagrid.md new file mode 100644 index 0000000000..a0248e6771 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/specify-default-values-for-new-rows-in-the-datagrid.md @@ -0,0 +1,37 @@ +--- +title: Specify Default Values for New Rows in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data grids [Windows Forms], default values for new rows" + - "DataGridView control [Windows Forms], data entry" + - "rows [Windows Forms], specifying default values" + - "DataGridView control [Windows Forms], default values for new rows" +ms.assetid: 8d127963-d9f8-4e4e-9f7f-beb66688f1f2 +--- +# How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control +You can make data entry more convenient when the application fills in default values for newly added rows. With the class, you can fill in default values with the event. This event is raised when the user enters the row for new records. When your code handles this event, you can populate desired cells with values of your choosing. + + The following code example demonstrates how to specify default values for new rows using the event. + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#120](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#120)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#120](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#120)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- A `NewCustomerId` function for generating unique `CustomerID` values. + +- References to the and assemblies. + +## See also + +- +- +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) +- [Using the Row for New Records in the Windows Forms DataGridView Control](using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/splitcontainer-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/splitcontainer-control-overview-windows-forms.md new file mode 100644 index 0000000000..20ec08c5d0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/splitcontainer-control-overview-windows-forms.md @@ -0,0 +1,50 @@ +--- +title: "SplitContainer Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "SplitContainer" +helpviewer_keywords: + - "SplitContainer control [Windows Forms], about SplitContainer control" +ms.assetid: 6de5a5f7-97a5-402d-be6d-7e2785483db5 +--- +# SplitContainer Control Overview (Windows Forms) +The Windows Forms control can be thought of as a composite; it is 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. + +> [!IMPORTANT] +> In the **Toolbox**, control replaces the control that was there in the previous version of Visual Studio. The control is much preferred over the control. The class is still included in the .NET Framework for compatibility with existing applications, but we strongly encourage you to use the control for new projects. + + 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 very 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. + + More than one control can also be nested, with the second control oriented horizontally, to create top and bottom panels. + + Be aware that the control is keyboard-accessible by default; users can press the ARROW keys to move the splitter if the property is set to `false`. + + The property of the control determines the direction of the splitter, not of the control itself. Hence, when this property is set to , the splitter runs from top to bottom, creating left and right panels. + + Additionally, be aware that the value of the property varies depending on the value of the property. For more information, see property. + + You can also restrict the size and movement of the control. The property determines which panel will remain the same size after the control is resized, and the property determines if the splitter is movable by the keyboard or mouse. + +> [!NOTE] +> Even if the property is set to `true`, the splitter may still be moved programmatically; for example, by using the property. + + Finally, each panel of the control has properties to determine its individual size. + +## Commonly Used Properties, Methods, and Events + +|Name|Description| +|----------|-----------------| +| property|Determines which panel will remain the same size after the control is resized.| +| property|Determines if the splitter can be moved with the keyboard or mouse.| +| property|Determines if the splitter is arranged vertically or horizontally.| +| property|Determines the distance in pixels from the left or upper edge to the movable splitter bar.| +| property|Determines the minimum distance, in pixels, that the splitter can be moved by the user.| +| property|Determines the thickness, in pixels, of the splitter.| +| event|Occurs when the splitter is moving.| +| event|Occurs when the splitter has moved.| + +## See also + +- +- [SplitContainer Control](splitcontainer-control-windows-forms.md) +- [SplitContainer Control Sample](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/0ffz7d1b(v=vs.90)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/splitcontainer-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/splitcontainer-control-windows-forms.md new file mode 100644 index 0000000000..157dd29bc2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/splitcontainer-control-windows-forms.md @@ -0,0 +1,41 @@ +--- +title: "SplitContainer Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "splitter windows" + - "SplitContainer control [Windows Forms]" +ms.assetid: 2e36f17f-5c39-4fb4-bb09-7ce3ef823402 +--- +# SplitContainer Control (Windows Forms) +The Windows Forms `SplitContainer` control can be thought of as a composite; it is 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. + +> [!NOTE] +> In the **Toolbox**, this control replaces the control that was there in the previous version of Visual Studio. The `SplitContainer` control is much preferred over the control. The class is still included in the .NET Framework for compatibility with existing applications, but we strongly encourage you to use the `SplitContainer` control for new projects. + + The `SplitContainer` control lets you create complex user interfaces; often, a selection in one panel determines what objects are shown in the other panel. This arrangement is very effective for displaying and browsing information. Having two panels allow you to aggregate information in areas, and the bar, or "splitter," makes it easy for users to resize the panels. + +## In This Section + [SplitContainer Control Overview](splitcontainer-control-overview-windows-forms.md) + Introduces the `SplitContainer` control and describes the commonly used properties, methods, and events. + + [How to: Define Resize and Positioning Behavior in a Split Window](how-to-define-resize-and-positioning-behavior-in-a-split-window.md) + Describes how to control the splitter within the `SplitContainer` control. + + [How to: Split a Window Horizontally](how-to-split-a-window-horizontally.md) + Describes how to control the orientation of the splitter within the `SplitContainer` control. + + [How to: Create a Multipane User Interface with Windows Forms](how-to-create-a-multipane-user-interface-with-windows-forms.md) + Creates a multi-pane user interface that is similar to the one used in Microsoft Outlook. + + Also see [How to: Split a Window Horizontally Using the Designer](how-to-split-a-window-horizontally-using-the-designer.md), [How to: Create a Windows Explorer–Style Interface on a Windows Form](how-to-create-a-windows-explorer-style-interface-on-a-windows-form.md), [How to: Create a Multipane User Interface with Windows Forms Using the Designer](create-a-multipane-user-interface-with-wf-using-the-designer.md). + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Windows Forms Controls](index.md) + Provides links to topics about the controls designed specifically to work with Windows Forms. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/splitter-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/splitter-control-overview-windows-forms.md new file mode 100644 index 0000000000..cbf482ceab --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/splitter-control-overview-windows-forms.md @@ -0,0 +1,23 @@ +--- +title: "Splitter Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "Splitter" +helpviewer_keywords: + - "Splitter control [Windows Forms], about Splitter control" +ms.assetid: e2b6ab83-dfdd-40ec-9762-850702c82dcb +--- +# Splitter Control Overview (Windows Forms) +> [!IMPORTANT] +> Although replaces and adds functionality to the control of previous versions, is retained for both backward compatibility and future use if you choose. + + Windows Forms controls are used to resize docked controls at run time. The control is often used on forms with controls that have varying lengths of data to present, like Windows Explorer, whose data panes contain information of varying widths at different times. + +## Working with the Splitter Control + When the user points the mouse pointer at the undocked edge of a control that can be resized by a splitter control, the pointer changes its appearance to indicate that the control can be resized. With the splitter control, the user can resize the docked control that is immediately before it. Therefore, to enable the user to resize a docked control at run time, dock the control to be resized to an edge of a container, and then dock a splitter control to the same side of that container. + +## See also + +- +- [How to: Dock Controls on Windows Forms](how-to-dock-controls-on-windows-forms.md) +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/splitter-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/splitter-control-windows-forms.md new file mode 100644 index 0000000000..f83a5c22ef --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/splitter-control-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "Splitter Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "multiple views" + - "Splitter control [Windows Forms]" + - "views [Windows Forms], multiple per frame" +ms.assetid: 6f287407-e895-4b07-a46a-a5bff8388d46 +--- +# Splitter Control (Windows Forms) +Windows Forms `Splitter` controls are used to resize docked controls at run time. The `Splitter` control is often used on forms with controls that have varying lengths of data to present, like Windows Explorer, whose data panes contain information of varying widths at different times. + +> [!NOTE] +> Although replaces and adds functionality to the `Splitter` control of previous versions, `Splitter` is retained for both backward compatibility and future use if you choose. + +## In This Section + [Splitter Control Overview](splitter-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/statusbar-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/statusbar-control-overview-windows-forms.md new file mode 100644 index 0000000000..3a271d4add --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/statusbar-control-overview-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "StatusBar Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "StatusBar" +helpviewer_keywords: + - "StatusBar control [Windows Forms], about StatusBar control" + - "status bars" +ms.assetid: b7b9852c-633d-4416-bb2e-94852b989c6c +--- +# StatusBar Control Overview (Windows Forms) +> [!IMPORTANT] +> The and controls replace and add functionality to the and controls; however, the and controls are retained for both backward compatibility and future use, if you choose. + + The Windows Forms [StatusBar Control](statusbar-control-windows-forms.md) is used on forms as an area, usually displayed at the bottom of a window, in which an application can display various kinds of status information. controls can have status bar panels on them that display text or icons to indicate state, or a series of icons in an animation that indicate a process is working; for example, Microsoft Word indicating that the document is being saved. + +## Using the StatusBar Control + Internet Explorer uses a status bar to indicate the URL of a page when the mouse rolls over the hyperlink; Microsoft Word gives you information on page location, section location, and editing modes such as overtype and revision tracking; and Visual Studio uses the status bar to give context-sensitive information, such as telling you how to manipulate dockable windows as either docked or floating. + + You can display a single message on the status bar by setting the property to `false` (the default) and setting the property of the status bar to the text you want to appear in the status bar. You can divide the status bar into panels to display more than one type of information by setting the property to `true` and using the method of . + +## See also + +- +- +- [How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked](determine-which-panel-wf-statusbar-control-was-clicked.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/statusbar-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/statusbar-control-windows-forms.md new file mode 100644 index 0000000000..9ee4f253bd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/statusbar-control-windows-forms.md @@ -0,0 +1,40 @@ +--- +title: "StatusBar Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "StatusBar control [Windows Forms]" + - "status bars [Windows Forms], creating" +ms.assetid: 6f543e27-cf78-4b7f-b4d0-6a8030155d48 +--- +# StatusBar Control (Windows Forms) +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + The Windows Forms control is used on forms as an area, usually displayed at the bottom of a window, in which an application can display various kinds of status information. controls can have status-bar panels on them that display icons to indicate state, or a series of icons in an animation that indicate a process is working; for example, Microsoft Word indicating that the document is being saved. + +## In This Section + [StatusBar Control Overview](statusbar-control-overview-windows-forms.md) + Introduces the general concepts of the control, which enables users to see relevant information for the control that has focus. + + [How to: Add Panels to a StatusBar Control](how-to-add-panels-to-a-statusbar-control.md) + Explains how to add programmable panels to the control. + + [How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked](determine-which-panel-wf-statusbar-control-was-clicked.md) + Explains how to handle events raised from the control. + + [How to: Set the Size of Status-Bar Panels](how-to-set-the-size-of-status-bar-panels.md) + Gives details on the properties that control the width and resize behavior of status-bar panels at run time. + + [Walkthrough: Updating Status Bar Information at Run Time](walkthrough-updating-status-bar-information-at-run-time.md) + Explains how to programmatically control the data within status-bar panels. + +## Reference + + Provides reference information on the class and its members. + + + Replaces and adds functionality to the control. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/statusstrip-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/statusstrip-control-overview.md new file mode 100644 index 0000000000..d58f995f60 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/statusstrip-control-overview.md @@ -0,0 +1,42 @@ +--- +title: "StatusStrip Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "StatusStrip" +helpviewer_keywords: + - "StatusStrip control [Windows Forms], about StatusStrip control" + - "status bars [Windows Forms], about status bars" +ms.assetid: c0d9bcbb-f8b8-46ef-bae2-4146b8c8ce99 +--- +# StatusStrip Control Overview +A control displays information about an object being viewed on a , the object's components, or contextual information that relates to that object's operation within your application. Typically, a control consists of objects, each of which displays text, an icon, or both. The can also contain , , and controls. + + The default has no panels. To add panels to a , use the method. + + There is extensive support for handling items and common commands in Visual Studio. + + Also see [StatusStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233631(v=vs.100)) and [StatusStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233642(v=vs.100)). + + Although replaces and extends the control of previous versions, is retained for both backward compatibility and future use if you choose. + +### Important StatusStrip Members + +|Name|Description| +|----------|-----------------| +||Gets or sets a value indicating whether the supports overflow functionality.| +||Gets or sets a value indicating whether the stretches from end to end in its .| + +### Important StatusStrip Companion Classes + +|Name|Description| +|----------|-----------------| +||Represents a panel in a control.| +||Displays an associated from which the user can select a single item.| +||Represents a two-part control that is a standard button and a drop-down menu.| +||Displays the completion state of a process.| + +## See also + +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/statusstrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/statusstrip-control.md new file mode 100644 index 0000000000..5d29948447 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/statusstrip-control.md @@ -0,0 +1,30 @@ +--- +title: "StatusStrip Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "StatusStrip control [Windows Forms]" + - "status bars" +ms.assetid: eb1e59da-0a48-4ce5-af7d-13b8e75af4b1 +--- +# StatusStrip Control +The Windows Forms `StatusStrip` control is used on forms as an area, usually displayed at the bottom of a window, in which an application can display various kinds of status information. `StatusStrip` controls typically have `ToolStripStatusLabel` controls on them that display text or icons to indicate state, or a that graphically displays the completion state of a process. + +## In This Section + [StatusStrip Control Overview](statusstrip-control-overview.md) + Explains what this control is and its key features and properties. + + [How to: Use the Spring Property Interactively in a StatusStrip](how-to-use-the-spring-property-interactively-in-a-statusstrip.md) + Demonstrates using the `Spring` property to interactively center a `ToolStripStatusLabel` in a `StatusStrip`. + + Also see [StatusStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233631(v=vs.100)) and [StatusStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233642(v=vs.100)). + +## Reference + + Provides reference information on the class and its members. + + + Provides reference information on the class and its members. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/stretch-a-toolstriptextbox-to-fill-the-remaining-width-of-a-toolstrip-wf.md b/dotnet-desktop-guide/framework/winforms/controls/stretch-a-toolstriptextbox-to-fill-the-remaining-width-of-a-toolstrip-wf.md new file mode 100644 index 0000000000..a74aa505ae --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/stretch-a-toolstriptextbox-to-fill-the-remaining-width-of-a-toolstrip-wf.md @@ -0,0 +1,33 @@ +--- +title: "How to: Stretch a ToolStripTextBox to Fill the Remaining Width of a ToolStrip" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "text boxes [Windows Forms], stretching in ToolStrip control [Windows Forms]" + - "ToolStrip control [Windows Forms], stretching a text box" +ms.assetid: 0e610fbf-85fe-414c-900c-9704a5dd5cc6 +--- +# How to: Stretch a ToolStripTextBox to Fill the Remaining Width of a ToolStrip (Windows Forms) +When you set the property of a control to `true`, the control fills its container from end to end, and resizes when its container resizes. In this configuration, you may find it useful to stretch an item in the control, such as a , to fill the available space and to resize when the control resizes. This stretching is useful, for example, if you want to achieve appearance and behavior similar to the address bar in Microsoft® Internet Explorer. + +## Example + The following code example provides a class derived from called `ToolStripSpringTextBox`. This class overrides the method to calculate the available width of the parent control after the combined width of all other items has been subtracted. This code example also provides a class and a `Program` class to demonstrate the new behavior. + + [!code-csharp[ToolStripSpringTextBox#00](~/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripSpringTextBox/cs/ToolStripSpringTextBox.cs#00)] + [!code-vb[ToolStripSpringTextBox#00](~/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripSpringTextBox/vb/ToolStripSpringTextBox.vb#00)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) +- [How to: Use the Spring Property Interactively in a StatusStrip](how-to-use-the-spring-property-interactively-in-a-statusstrip.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/tabcontrol-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/tabcontrol-control-overview-windows-forms.md new file mode 100644 index 0000000000..4f72d5502c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/tabcontrol-control-overview-windows-forms.md @@ -0,0 +1,27 @@ +--- +title: "TabControl Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "TabControl" +helpviewer_keywords: + - "TabControl control [Windows Forms], about TabControl control" + - "tab pages [Windows Forms], about tab pages" + - "property pages [Windows Forms], Windows Forms" + - "Windows Forms dialog boxes [Windows Forms], tabs" +ms.assetid: 2b4ea784-a39d-463c-81d8-af74ce068476 +--- +# TabControl Control Overview (Windows Forms) +The Windows Forms 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. You can 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 Display Properties. Additionally, the can be used to create property pages, which are used to set a group of related properties. + +## Working with TabControl + The most important property of the is , which contains the individual tabs. Each individual tab is a object. When a tab is clicked, it raises the event for that object. + +## See also + +- +- [TabControl Control](tabcontrol-control-windows-forms.md) +- [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) +- [How to: Add a Control to a Tab Page](how-to-add-a-control-to-a-tab-page.md) +- [How to: Add and Remove Tabs with the Windows Forms TabControl](how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md) +- [How to: Disable Tab Pages](how-to-disable-tab-pages.md) +- [Dialog Boxes in Windows Forms](../dialog-boxes-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/tabcontrol-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/tabcontrol-control-windows-forms.md new file mode 100644 index 0000000000..2b36876a09 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/tabcontrol-control-windows-forms.md @@ -0,0 +1,44 @@ +--- +title: "TabControl Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "TabControl control [Windows Forms]" + - "tab controls" + - "tab controls [Windows Forms], creating" + - "multipage dialog boxes" + - "dialog boxes [Windows Forms], creating multipage" + - "property pages [Windows Forms], creating" + - "tab dialog boxes" +ms.assetid: 915091af-93ac-4d3d-8283-738dd2d21ea7 +--- +# TabControl Control (Windows Forms) +The Windows Forms `TabControl` 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 `TabControl` to create property pages. + +## In This Section + [TabControl Control Overview](tabcontrol-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Add a Control to a Tab Page](how-to-add-a-control-to-a-tab-page.md) + Gives directions for displaying controls on tab pages. + + [How to: Add and Remove Tabs with the Windows Forms TabControl](how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md) + Gives directions for adding and removing tabs in the designer or in code. + + [How to: Change the Appearance of the Windows Forms TabControl](how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md) + Gives directions for adjusting properties that affect the appearance of individual tabs. + + [How to: Disable Tab Pages](how-to-disable-tab-pages.md) + Explains how to restrict access to a tab page, possibly based on user credentials. + + Also see [How to: Add and Remove Tabs with the Windows Forms TabControl Using the Designer](add-and-remove-tabs-with-wf-tabcontrol-using-the-designer.md), [How to: Add a Control to a Tab Page Using the Designer](how-to-add-a-control-to-a-tab-page-using-the-designer.md) + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Dialog Boxes in Windows Forms](../dialog-boxes-in-windows-forms.md) + Provides a list of tasks for dialog boxes, which often display tabs. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/tablelayoutpanel-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/tablelayoutpanel-control-overview.md new file mode 100644 index 0000000000..f657ae9100 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/tablelayoutpanel-control-overview.md @@ -0,0 +1,44 @@ +--- +title: "TableLayoutPanel Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "TableLayoutPanel" +helpviewer_keywords: + - "controls [Windows Forms], resizing" + - "resizable controls [Windows Forms]" + - "Windows Forms controls, proportional resizing" + - "Windows Forms, proportional resizing of controls" + - "layout [Windows Forms], TableLayoutPanel control" + - "TableLayoutPanel control [Windows Forms], about TableLayoutPanel control" +ms.assetid: 337661c8-61cb-44ee-93e0-3662bddec327 +--- +# TableLayoutPanel Control Overview +The control arranges its contents in a grid. Because the layout is performed 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 proportionally resize, so they can respond to changes such as the parent control resizing or text length changing due to 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. + + The control can expand to accommodate new controls when they are added, depending on the value of the , , and properties. Setting either the or property to a value of 0 specifies that the will be unbound in the corresponding direction. + + 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. + + If you want rows and columns that behave differently from the default behavior, you can control the properties of 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`. + + You can merge cells in the control by setting the `ColumnSpan` or `RowSpan` properties on a child control. + +1. [How to: Align and Stretch a Control in a TableLayoutPanel Control](how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md) + +2. [How to: Span Rows and Columns in a TableLayoutPanel Control](how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md) + +3. [How to: Edit Columns and Rows in a TableLayoutPanel Control](how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md) + +4. [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) + +## See also + +- +- +- [How to: Design a Windows Forms Layout that Responds Well to Localization](how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md) +- [How to: Create a Resizable Windows Form for Data Entry](how-to-create-a-resizable-windows-form-for-data-entry.md) +- [Best Practices for the TableLayoutPanel Control](best-practices-for-the-tablelayoutpanel-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/tablelayoutpanel-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/tablelayoutpanel-control-windows-forms.md new file mode 100644 index 0000000000..a463c50804 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/tablelayoutpanel-control-windows-forms.md @@ -0,0 +1,57 @@ +--- +title: "TableLayoutPanel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "TableLayoutPanel control [Windows Forms]" + - "layout [Windows Forms]" + - "controls [Windows Forms], sizing" + - "sizing [Windows Forms], automatic" + - "layout [Windows Forms], TableLayoutPanel control" + - "automatic sizing" +ms.assetid: f55175c6-424e-4782-a86e-3f79c1550235 +--- +# TableLayoutPanel Control (Windows Forms) +The control arranges its contents in a grid. Because the layout is performed 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 proportionally resize, so it can respond to changes such as the parent control resizing or text length changing due to localization. + +## In This Section + [TableLayoutPanel Control Overview](tablelayoutpanel-control-overview.md) + Introduces the general concepts of the control, which allows you to create a layout with rows and columns. + + [Best Practices for the TableLayoutPanel Control](best-practices-for-the-tablelayoutpanel-control.md) + Outlines recommendations to help you get the most out of the layout features of the control. + + [AutoSize Behavior in the TableLayoutPanel Control](autosize-behavior-in-the-tablelayoutpanel-control.md) + Explains the ways in which the control supports automatic sizing behavior. + + [How to: Anchor and Dock Child Controls in a TableLayoutPanel Control](how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md) + Shows how to anchor and dock child controls in a control. + + [How to: Design a Windows Forms Layout that Responds Well to Localization](how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md) + Demonstrates using a control to build a form that responds well to localization. + + [How to: Create a Resizable Windows Form for Data Entry](how-to-create-a-resizable-windows-form-for-data-entry.md) + Demonstrates using a control to build a form that responds well to resizing. + +1. [How to: Align and Stretch a Control in a TableLayoutPanel Control](how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md) + +2. [How to: Span Rows and Columns in a TableLayoutPanel Control](how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md) + +3. [How to: Edit Columns and Rows in a TableLayoutPanel Control](how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md) + +4. [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the type. + + + Provides reference documentation for the control. + +## Related Sections + [Localization](https://docs.microsoft.com/dotnet/standard/globalization-localization/localization) + Provides an overview of topics relating to localization. + + Also see [Localizing Applications](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/z68135h5(v=vs.120)). diff --git a/dotnet-desktop-guide/framework/winforms/controls/textbox-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/textbox-control-overview-windows-forms.md new file mode 100644 index 0000000000..910ef7501d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/textbox-control-overview-windows-forms.md @@ -0,0 +1,55 @@ +--- +title: "TextBox Control Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +f1_keywords: + - "TextBox" +helpviewer_keywords: + - "TextBox control [Windows Forms], about TextBox controls" + - "text boxes [Windows Forms], adding" +ms.assetid: d1a9c7f5-fa53-480a-a75c-158f8649ea2f +--- +# TextBox Control Overview (Windows Forms) +Windows Forms text boxes are used to get input from the user or to display text. The control is generally used for editable text, although it can also be made read-only. Text boxes can display multiple lines, wrap text to the size of the control, and add basic formatting. The control provides a single format style for text displayed or entered into the control. To display multiple types of formatted text, use the control. For more information, see [RichTextBox Control Overview](richtextbox-control-overview-windows-forms.md). + +## Working with the TextBox Control + The text displayed by the control is contained in the property. By default, you can enter up to 2048 characters in a text box. If you set the property to `true`, you can enter up to 32 KB of text. The property can be set at design time with the Properties Window, at run time in code, or by user input at run time. The current contents of a text box can be retrieved at run time by reading the property. + + The following code example sets text in the control at run time. The `InitializeMyControl` procedure will not execute automatically; it must be called. + +```vb +Private Sub InitializeMyControl() + ' Put some text into the control first. + TextBox1.Text = "This is a TextBox control." +End Sub +``` + +```csharp +private void InitializeMyControl() { + // Put some text into the control first. + textBox1.Text = "This is a TextBox control."; +} +``` + +```cpp +private: + void InitializeMyControl() + { + // Put some text into the control first. + textBox1->Text = "This is a TextBox control."; + } +``` + +## See also + +- +- [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) +- [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) +- [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) +- [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) +- [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) +- [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) +- [TextBox Control](textbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/textbox-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/textbox-control-windows-forms.md new file mode 100644 index 0000000000..0be5b693ee --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/textbox-control-windows-forms.md @@ -0,0 +1,41 @@ +--- +title: "TextBox Control" +description: Learn about various aspects of the Windows Forms TextBox control including using it for editable text and making it read-only. +ms.date: "03/30/2017" +helpviewer_keywords: + - "text boxes" + - "TextBox control [Windows Forms]" +ms.assetid: e5a06987-8aec-4271-b196-2245ba992d62 +--- +# TextBox Control (Windows Forms) +Windows Forms text boxes are used to get input from the user or to display text. The `TextBox` control is generally used for editable text, although it can also be made read-only. Text boxes can display multiple lines, wrap text to the size of the control, and add basic formatting. The `TextBox` control allows a single format for text displayed or entered in the control. + +## In This Section + [TextBox Control Overview](textbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Control the Insertion Point in a Windows Forms TextBox Control](how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md) + Gives directions for specifying where the insertion point appears when an edit control first gets the focus. + + [How to: Create a Password Text Box with the Windows Forms TextBox Control](how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md) + Explains how to conceal what is typed into a text box. + + [How to: Create a Read-Only Text Box](how-to-create-a-read-only-text-box-windows-forms.md) + Describes how to prevent the contents of a text box from being changed. + + [How to: Put Quotation Marks in a String](how-to-put-quotation-marks-in-a-string-windows-forms.md) + Explains adding quotation marks to a string in a text box. + + [How to: Select Text in the Windows Forms TextBox Control](how-to-select-text-in-the-windows-forms-textbox-control.md) + Explains how to highlight text in a text box. + + [How to: View Multiple Lines in the Windows Forms TextBox Control](how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md) + Describes how to make a text box scrollable. + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/timer-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/timer-component-overview-windows-forms.md new file mode 100644 index 0000000000..b18479d56b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/timer-component-overview-windows-forms.md @@ -0,0 +1,21 @@ +--- +title: "Timer Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "Timer" +helpviewer_keywords: + - "Timer component [Windows Forms], about Timer components" + - "timers [Windows Forms], about timers" +ms.assetid: e672c05b-a8b6-4b26-9e4d-9223aa9e3873 +--- +# Timer Component Overview (Windows Forms) +The Windows Forms is a component that raises an event at regular intervals. This component is designed for a Windows Forms environment. If you need a timer that is suitable for a server environment, see [Introduction to Server-Based Timers](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/tb9yt5e6(v=vs.90)). + +## Key Properties, Methods, and Events + The length of the intervals is defined by the property, whose value is in milliseconds. When the component is enabled, the event is raised every interval. This is where you would add code to be executed. For more information, see [How to: Run Procedures at Set Intervals with the Windows Forms Timer Component](run-procedures-at-set-intervals-with-wf-timer-component.md). The key methods of the component are and , which turn the timer on and off. When the timer is switched off, it resets; there is no way to pause a component. + +## See also + +- +- [Timer Component](timer-component-windows-forms.md) +- [Limitations of the Windows Forms Timer Component's Interval Property](limitations-of-the-timer-component-interval-property.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/timer-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/timer-component-windows-forms.md new file mode 100644 index 0000000000..ba0c036df0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/timer-component-windows-forms.md @@ -0,0 +1,32 @@ +--- +title: "Timer Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Timer component [Windows Forms]" + - "timers" + - "timers [Windows Forms], creating" +ms.assetid: 6700e534-6382-43d5-98ed-14205435fff7 +--- +# Timer Component (Windows Forms) +The Windows Forms is a component that raises an event at regular intervals. This component is designed for a Windows Forms environment. + +## In This Section + [Timer Component Overview](timer-component-overview-windows-forms.md) + Introduces the general concepts of the component, which allows you to set up your application to respond to periodic events. + + [Limitations of the Windows Forms Timer Component's Interval Property](limitations-of-the-timer-component-interval-property.md) + Describes known limitations of the timer's interval that may affect how you can use it. + + [How to: Run Procedures at Set Intervals with the Windows Forms Timer Component](run-procedures-at-set-intervals-with-wf-timer-component.md) + Describes how to react to timed intervals in your Windows-based applications. + +## Reference + class + Provides reference information on the class, used for Windows Forms timers, and its members. + + class + Provides reference information on the class that is used by server-based timers. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/toc.yml b/dotnet-desktop-guide/framework/winforms/controls/toc.yml new file mode 100644 index 0000000000..87c948d46a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toc.yml @@ -0,0 +1,1213 @@ +- name: Controls + href: index.md + items: + - name: Arrange controls on Windows Forms + items: + - name: "How to: Align Multiple Controls" + href: how-to-align-multiple-controls-on-windows-forms.md + - name: "How to: Anchor Controls" + href: how-to-anchor-controls-on-windows-forms.md + - name: "How to: Dock Controls" + href: how-to-dock-controls-on-windows-forms.md + - name: "How to: Layer Objects" + href: how-to-layer-objects-on-windows-forms.md + - name: "How to: Lock Controls" + href: how-to-lock-controls-to-windows-forms.md + - name: "How to: Position Controls" + href: how-to-position-controls-on-windows-forms.md + - name: "How to: Resize Controls" + href: how-to-resize-controls-on-windows-forms.md + - name: "How to: Set Grid Options for All Windows Forms" + href: how-to-set-grid-options-for-all-windows-forms.md + - name: "How to: Set the Tab Order" + href: how-to-set-the-tab-order-on-windows-forms.md + - name: "Walkthrough: Arrange Controls Using Snaplines" + href: walkthrough-arranging-controls-on-windows-forms-using-snaplines.md + - name: "How to: Reassign Existing Controls to a Different Parent" + href: how-to-reassign-existing-controls-to-a-different-parent.md + - name: "Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property" + href: windows-forms-controls-padding-autosize.md + - name: Putting Controls on Windows Forms + href: putting-controls-on-windows-forms.md + items: + - name: "How to: Add Controls" + href: how-to-add-controls-to-windows-forms.md + - name: "How to: Add Controls Without a User Interface" + href: how-to-add-controls-without-a-user-interface-to-windows-forms.md + - name: "How to: Add to or Remove from a Collection of Controls at Run Time" + href: how-to-add-to-or-remove-from-a-collection-of-controls-at-run-time.md + - name: "Walkthrough: Automatically Populating the Toolbox with Custom Components" + href: walkthrough-automatically-populating-the-toolbox-with-custom-components.md + - name: "How to: Add ActiveX Controls" + href: how-to-add-activex-controls-to-windows-forms.md + - name: Considerations When Hosting an ActiveX Control on a Windows Form + href: considerations-when-hosting-an-activex-control-on-a-windows-form.md + - name: Label controls and provide shortcuts + items: + - name: Overview + href: labeling-individual-windows-forms-controls-and-providing-shortcuts-to-them.md + - name: Create access keys for controls + href: how-to-create-access-keys-for-windows-forms-controls.md + - name: Set the text displayed by a control + href: how-to-set-the-text-displayed-by-a-windows-forms-control.md + - name: Set the image displayed by a control + href: how-to-set-the-image-displayed-by-a-windows-forms-control.md + - name: Provide accessibility information for controls + href: providing-accessibility-information-for-controls-on-a-windows-form.md + - name: Controls to Use on Windows Forms + href: controls-to-use-on-windows-forms.md + items: + - name: Windows Forms Controls by Function + href: windows-forms-controls-by-function.md + - name: Controls with Built-In Owner-Drawing Support + href: controls-with-built-in-owner-drawing-support.md + - name: BackgroundWorker Component + href: backgroundworker-component.md + items: + - name: BackgroundWorker Component Overview + href: backgroundworker-component-overview.md + - name: "How to: Run an Operation in the Background" + href: how-to-run-an-operation-in-the-background.md + - name: "How to: Download a File in the Background" + href: how-to-download-a-file-in-the-background.md + - name: "How to: Implement a Form That Uses a Background Operation" + href: how-to-implement-a-form-that-uses-a-background-operation.md + - name: "Walkthrough: Running an Operation in the Background" + href: walkthrough-running-an-operation-in-the-background.md + - name: "Walkthrough: Implementing a Form That Uses a Background Operation" + href: walkthrough-implementing-a-form-that-uses-a-background-operation.md + - name: BindingNavigator Control + href: bindingnavigator-control-windows-forms.md + items: + - name: BindingNavigator Control Overview + href: bindingnavigator-control-overview-windows-forms.md + - name: "How to: Navigate Data with the Windows Forms BindingNavigator Control" + href: how-to-navigate-data-with-the-windows-forms-bindingnavigator-control.md + - name: "How to: Move Through a DataSet with the Windows Forms BindingNavigator Control" + href: move-through-a-dataset-with-wf-bindingnavigator-control.md + - name: "How to: Add Load, Save, and Cancel Buttons to the Windows Forms BindingNavigator Control" + href: load-save-and-cancel-bindingnavigator.md + - name: BindingSource Component + href: bindingsource-component.md + items: + - name: BindingSource Component Overview + href: bindingsource-component-overview.md + - name: BindingSource Component Architecture + href: bindingsource-component-architecture.md + - name: "How to: Bind a Windows Forms Control to a Factory Object" + href: how-to-bind-a-windows-forms-control-to-a-factory-object.md + - name: "How to: Bind a Windows Forms Control to a Type" + href: how-to-bind-a-windows-forms-control-to-a-type.md + - name: "How to: Bind a Windows Forms Control to a Type Using the Designer" + href: how-to-bind-a-windows-forms-control-to-a-type-using-the-designer.md + - name: "How to: Bind to a Web Service Using the Windows Forms BindingSource" + href: how-to-bind-to-a-web-service-using-the-windows-forms-bindingsource.md + - name: "How to: Bind Windows Forms Controls to DBNull Database Values" + href: how-to-bind-windows-forms-controls-to-dbnull-database-values.md + - name: "How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer" + href: bind-wf-controls-with-the-bindingsource.md + - name: "How to: Create a Lookup Table with the Windows Forms BindingSource Component" + href: how-to-create-a-lookup-table-with-the-windows-forms-bindingsource-component.md + - name: "How to: Customize Item Addition with the Windows Forms BindingSource" + href: how-to-customize-item-addition-with-the-windows-forms-bindingsource.md + - name: "How to: Handle Errors and Exceptions that Occur with Databinding" + href: how-to-handle-errors-and-exceptions-that-occur-with-databinding.md + - name: "How to: Raise Change Notifications Using a BindingSource and the INotifyPropertyChanged Interface" + href: raise-change-notifications--bindingsource.md + - name: "How to: Raise Change Notifications Using the BindingSource ResetItem Method" + href: how-to-raise-change-notifications-using-the-bindingsource-resetitem-method.md + - name: "How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource" + href: reflect-data-source-updates-in-a-wf-control-with-the-bindingsource.md + - name: "How to: Share Bound Data Across Forms Using the BindingSource Component" + href: how-to-share-bound-data-across-forms-using-the-bindingsource-component.md + - name: "How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component" + href: sort-and-filter-ado-net-data-with-wf-bindingsource-component.md + - name: Button Control + href: button-control-windows-forms.md + items: + - name: Button Control Overview + href: button-control-overview-windows-forms.md + - name: "How to: Designate a Windows Forms Button as the Accept Button" + href: how-to-designate-a-windows-forms-button-as-the-accept-button.md + - name: "How to: Designate a Windows Forms Button as the Accept Button Using the Designer" + href: designate-a-wf-button-as-the-accept-button-using-the-designer.md + - name: "How to: Designate a Windows Forms Button as the Cancel Button" + href: how-to-designate-a-windows-forms-button-as-the-cancel-button.md + - name: "How to: Designate a Windows Forms Button as the Cancel Button Using the Designer" + href: designate-a-wf-button-as-the-cancel-button-using-the-designer.md + - name: "How to: Respond to Button Clicks" + href: how-to-respond-to-windows-forms-button-clicks.md + - name: Ways to Select a Windows Forms Button Control + href: ways-to-select-a-windows-forms-button-control.md + - name: CheckBox Control + href: checkbox-control-windows-forms.md + items: + - name: CheckBox Control Overview + href: checkbox-control-overview-windows-forms.md + - name: "How to: Respond to CheckBox Clicks" + href: how-to-respond-to-windows-forms-checkbox-clicks.md + - name: "How to: Set Options with CheckBox Controls" + href: how-to-set-options-with-windows-forms-checkbox-controls.md + - name: CheckedListBox Control + href: checkedlistbox-control-windows-forms.md + items: + - name: CheckedListBox Control Overview + href: checkedlistbox-control-overview-windows-forms.md + - name: "How to: Determine Checked Items in the Windows Forms CheckedListBox Control" + href: how-to-determine-checked-items-in-the-windows-forms-checkedlistbox-control.md + - name: ColorDialog Component + href: colordialog-component-windows-forms.md + items: + - name: ColorDialog Component Overview + href: colordialog-component-overview-windows-forms.md + - name: "How to: Change the Appearance of the Windows Forms ColorDialog Component" + href: how-to-change-the-appearance-of-the-windows-forms-colordialog-component.md + - name: "How to: Show a Color Palette with the ColorDialog Component" + href: how-to-show-a-color-palette-with-the-colordialog-component.md + - name: ComboBox Control + href: combobox-control-windows-forms.md + items: + - name: ComboBox Control Overview + href: combobox-control-overview-windows-forms.md + - name: "How to: Create Variable Sized Text in a ComboBox Control" + href: how-to-create-variable-sized-text-in-a-combobox-control.md + - name: ContextMenu Component + href: contextmenu-component-windows-forms.md + items: + - name: ContextMenu Component Overview + href: contextmenu-component-overview-windows-forms.md + - name: "How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component" + href: add-and-remove-menu-items-with-wf-contextmenu-component.md + - name: ContextMenuStrip Control + href: contextmenustrip-control.md + items: + - name: ContextMenuStrip Control Overview + href: contextmenustrip-control-overview.md + - name: "How to: Associate a ContextMenuStrip with a Control" + href: how-to-associate-a-contextmenustrip-with-a-control.md + - name: "How to: Add Menu Items to a ContextMenuStrip" + href: how-to-add-menu-items-to-a-contextmenustrip.md + - name: "How to: Configure ContextMenuStrip Check Margins and Image Margins" + href: how-to-configure-contextmenustrip-check-margins-and-image-margins.md + - name: "How to: Enable Check Margins and Image Margins in ContextMenuStrip Controls" + href: how-to-enable-check-margins-and-image-margins-in-contextmenustrip-controls.md + - name: "How to: Handle the ContextMenuStrip Opening Event" + href: how-to-handle-the-contextmenustrip-opening-event.md + - name: DataGrid Control + href: datagrid-control-windows-forms.md + items: + - name: DataGrid Control Overview + href: datagrid-control-overview-windows-forms.md + - name: "How to: Add Tables and Columns to the Windows Forms DataGrid Control" + href: how-to-add-tables-and-columns-to-the-windows-forms-datagrid-control.md + - name: "How to: Add Tables and Columns to the Windows Forms DataGrid Control Using the Designer" + href: add-tables-and-columns-to-wf-datagrid-control-using-the-designer.md + - name: "How to: Bind the Windows Forms DataGrid Control to a Data Source" + href: how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md + - name: "How to: Bind the Windows Forms DataGrid Control to a Data Source Using the Designer" + href: bind-wf-datagrid-control-to-a-data-source-using-the-designer.md + - name: "How to: Change Displayed Data at Run Time in the Windows Forms DataGrid Control" + href: change-displayed-data-at-run-time-wf-datagrid-control.md + - name: "How to: Create Master/Detail Lists with the Windows Forms DataGrid Control" + href: how-to-create-master-detail-lists-with-the-windows-forms-datagrid-control.md + - name: "How to: Create Master-Details Lists with the Windows Forms DataGrid Control Using the Designer" + href: create-master-details-lists-with-wf-datagrid-control-using-the-designer.md + - name: "How to: Delete or Hide Columns in the Windows Forms DataGrid Control" + href: how-to-delete-or-hide-columns-in-the-windows-forms-datagrid-control.md + - name: "How to: Format the Windows Forms DataGrid Control" + href: how-to-format-the-windows-forms-datagrid-control.md + - name: "How to: Format the Windows Forms DataGrid Control Using the Designer" + href: how-to-format-the-windows-forms-datagrid-control-using-the-designer.md + - name: "How to: Respond to Clicks in the Windows Forms DataGrid Control" + href: how-to-respond-to-clicks-in-the-windows-forms-datagrid-control.md + - name: "How to: Validate Input with the Windows Forms DataGrid Control" + href: how-to-validate-input-with-the-windows-forms-datagrid-control.md + - name: Keyboard Shortcuts for the Windows Forms DataGrid Control + href: keyboard-shortcuts-for-the-windows-forms-datagrid-control.md + - name: DataGridView Control + href: datagridview-control-windows-forms.md + items: + - name: Using the Designer with the Windows Forms DataGridView Control + href: using-the-designer-with-the-windows-forms-datagridview-control.md + items: + - name: "How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer" + href: add-and-remove-columns-in-the-datagrid-using-the-designer.md + - name: "How to: Bind Data to the Windows Forms DataGridView Control Using the Designer" + href: bind-data-to-the-datagrid-using-the-designer.md + - name: "How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer" + href: change-the-order-of-columns-in-the-datagrid-using-the-designer.md + - name: "How to: Change the Type of a Windows Forms DataGridView Column Using the Designer" + href: change-the-type-of-a-wf-datagridview-column-using-the-designer.md + - name: "How to: Enable Column Reordering in the Windows Forms DataGridView Control Using the Designer" + href: enable-column-reordering-in-the-datagrid-using-the-designer.md + - name: "How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer" + href: freeze-columns-in-the-datagrid-using-the-designer.md + - name: "How to: Hide Columns in the Windows Forms DataGridView Control Using the Designer" + href: hide-columns-in-the-datagrid-using-the-designer.md + - name: "How to: Make Columns Read-Only in the Windows Forms DataGridView Control Using the Designer" + href: make-columns-read-only-in-the-datagrid-using-the-designer.md + - name: "How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer" + href: prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md + - name: "How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer" + href: set-alternating-row-styles-for-the-datagrid-using-the-designer.md + - name: "How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer" + href: default-cell-styles-datagridview.md + - name: DataGridView Control Overview + href: datagridview-control-overview-windows-forms.md + items: + - name: DataGridView Control Technology Summary + href: datagridview-control-technology-summary-windows-forms.md + - name: DataGridView Control Architecture + href: datagridview-control-architecture-windows-forms.md + - name: DataGridView Control Scenarios + href: datagridview-control-scenarios-windows-forms.md + - name: DataGridView Control Code Directory + href: datagridview-control-code-directory-windows-forms.md + - name: Default Functionality in the Windows Forms DataGridView Control + href: default-functionality-in-the-windows-forms-datagridview-control.md + - name: Column Types in the Windows Forms DataGridView Control + href: column-types-in-the-windows-forms-datagridview-control.md + - name: Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control + href: basic-column-row-and-cell-features-wf-datagridview-control.md + items: + - name: "How to: Hide Columns in the Windows Forms DataGridView Control" + href: how-to-hide-columns-in-the-windows-forms-datagridview-control.md + - name: "How to: Hide Column Headers in the Windows Forms DataGridView Control" + href: how-to-hide-column-headers-in-the-windows-forms-datagridview-control.md + - name: "How to: Enable Column Reordering in the Windows Forms DataGridView Control" + href: how-to-enable-column-reordering-in-the-windows-forms-datagridview-control.md + - name: "How to: Freeze Columns in the Windows Forms DataGridView Control" + href: how-to-freeze-columns-in-the-windows-forms-datagridview-control.md + - name: "How to: Make Columns Read-Only in the Windows Forms DataGridView Control" + href: how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md + - name: "How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control" + href: prevent-row-addition-and-deletion-datagridview.md + - name: "How to: Get and Set the Current Cell in the Windows Forms DataGridView Control" + href: get-and-set-the-current-cell-wf-datagridview-control.md + - name: "How to: Display Images in Cells of the Windows Forms DataGridView Control" + href: how-to-display-images-in-cells-of-the-windows-forms-datagridview-control.md + - name: Basic Formatting and Styling in the Windows Forms DataGridView Control + href: basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md + items: + - name: "How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control" + href: change-the-border-and-gridline-styles-in-the-datagrid.md + - name: Cell Styles in the Windows Forms DataGridView Control + href: cell-styles-in-the-windows-forms-datagridview-control.md + - name: "How to: Set Default Cell Styles for the Windows Forms DataGridView Control" + href: how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md + - name: "How to: Format Data in the Windows Forms DataGridView Control" + href: how-to-format-data-in-the-windows-forms-datagridview-control.md + - name: "How to: Set Font and Color Styles in the Windows Forms DataGridView Control" + href: how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md + - name: "How to: Set Alternating Row Styles for the Windows Forms DataGridView Control" + href: how-to-set-alternating-row-styles-for-the-windows-forms-datagridview-control.md + - name: "How to: Use the Row Template to Customize Rows in the Windows Forms DataGridView Control" + href: use-the-row-template-to-customize-rows-in-the-datagrid.md + - name: Displaying Data in the Windows Forms DataGridView Control + href: displaying-data-in-the-windows-forms-datagridview-control.md + items: + - name: Data Display Modes in the Windows Forms DataGridView Control + href: data-display-modes-in-the-windows-forms-datagridview-control.md + - name: Data Formatting in the Windows Forms DataGridView Control + href: data-formatting-in-the-windows-forms-datagridview-control.md + - name: "Walkthrough: Creating an Unbound Windows Forms DataGridView Control" + href: walkthrough-creating-an-unbound-windows-forms-datagridview-control.md + items: + - name: "How to: Create an Unbound Windows Forms DataGridView Control" + href: how-to-create-an-unbound-windows-forms-datagridview-control.md + - name: "How to: Bind Data to the Windows Forms DataGridView Control" + href: how-to-bind-data-to-the-windows-forms-datagridview-control.md + - name: "How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control" + href: autogenerate-columns-in-a-data-bound-wf-datagridview-control.md + - name: "How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control" + href: remove-autogenerated-columns-from-a-wf-datagridview-control.md + - name: "How to: Change the Order of Columns in the Windows Forms DataGridView Control" + href: how-to-change-the-order-of-columns-in-the-windows-forms-datagridview-control.md + - name: "How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control" + href: unbound-column-to-a-data-bound-datagridview.md + - name: "How to: Bind Objects to DataGridView Controls" + href: how-to-bind-objects-to-windows-forms-datagridview-controls.md + - name: "How to: Access Objects Bound to DataGridView Rows" + href: how-to-access-objects-bound-to-windows-forms-datagridview-rows.md + - name: "How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List" + href: access-objects-in-a-wf-datagridviewcomboboxcell-drop-down-list.md + - name: "Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls" + href: creating-a-master-detail-form-using-two-datagridviews.md + items: + - name: "How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls" + href: create-a-master-detail-form-using-two-datagridviews.md + - name: "How to: Customize Data Formatting in the Windows Forms DataGridView Control" + href: how-to-customize-data-formatting-in-the-windows-forms-datagridview-control.md + - name: Resizing Columns and Rows in the Windows Forms DataGridView Control + href: resizing-columns-and-rows-in-the-windows-forms-datagridview-control.md + items: + - name: Sizing Options in the Windows Forms DataGridView Control + href: sizing-options-in-the-windows-forms-datagridview-control.md + - name: Column Fill Mode in the Windows Forms DataGridView Control + href: column-fill-mode-in-the-windows-forms-datagridview-control.md + - name: "How to: Set the Sizing Modes of the Windows Forms DataGridView Control" + href: how-to-set-the-sizing-modes-of-the-windows-forms-datagridview-control.md + - name: "How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control" + href: programmatically-resize-cells-to-fit-content-in-the-datagrid.md + - name: "How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control" + href: automatically-resize-cells-when-content-changes-in-the-datagrid.md + - name: Sorting Data in the Windows Forms DataGridView Control + href: sorting-data-in-the-windows-forms-datagridview-control.md + items: + - name: Column Sort Modes in the Windows Forms DataGridView Control + href: column-sort-modes-in-the-windows-forms-datagridview-control.md + - name: "How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control" + href: set-the-sort-modes-for-columns-wf-datagridview-control.md + - name: "How to: Customize Sorting in the Windows Forms DataGridView Control" + href: how-to-customize-sorting-in-the-windows-forms-datagridview-control.md + - name: Data Entry in the Windows Forms DataGridView Control + href: data-entry-in-the-windows-forms-datagridview-control.md + items: + - name: "How to: Specify the Edit Mode for the Windows Forms DataGridView Control" + href: how-to-specify-the-edit-mode-for-the-windows-forms-datagridview-control.md + - name: "How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control" + href: specify-default-values-for-new-rows-in-the-datagrid.md + - name: Using the Row for New Records in the Windows Forms DataGridView Control + href: using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md + - name: "Walkthrough: Validating Data in the Windows Forms DataGridView Control" + href: walkthrough-validating-data-in-the-windows-forms-datagridview-control.md + items: + - name: "How to: Validate Data in the Windows Forms DataGridView Control" + href: how-to-validate-data-in-the-windows-forms-datagridview-control.md + - name: "Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control" + href: handling-errors-that-occur-during-data-entry-in-the-datagrid.md + items: + - name: "How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control" + href: handle-errors-that-occur-during-data-entry-in-the-datagrid.md + - name: Selection and Clipboard Use with the Windows Forms DataGridView Control + href: selection-and-clipboard-use-with-the-windows-forms-datagridview-control.md + items: + - name: Selection Modes in the Windows Forms DataGridView Control + href: selection-modes-in-the-windows-forms-datagridview-control.md + - name: "How to: Set the Selection Mode of the Windows Forms DataGridView Control" + href: how-to-set-the-selection-mode-of-the-windows-forms-datagridview-control.md + - name: "How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control" + href: selected-cells-rows-and-columns-datagridview.md + - name: "How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control" + href: enable-users-to-copy-multiple-cells-to-the-clipboard-datagridview.md + - name: Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control + href: programming-with-cells-rows-and-columns-in-the-datagrid.md + items: + - name: "How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control" + href: add-tooltips-to-individual-cells-in-a-wf-datagridview-control.md + - name: "How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control" + href: perform-a-custom-action-based-on-changes-in-a-cell-of-a-datagrid.md + - name: "How to: Manipulate Bands in the Windows Forms DataGridView Control" + href: how-to-manipulate-bands-in-the-windows-forms-datagridview-control.md + - name: "How to: Manipulate Rows in the Windows Forms DataGridView Control" + href: how-to-manipulate-rows-in-the-windows-forms-datagridview-control.md + - name: "How to: Manipulate Columns in the Windows Forms DataGridView Control" + href: how-to-manipulate-columns-in-the-windows-forms-datagridview-control.md + - name: "How to: Work with Image Columns in the Windows Forms DataGridView Control" + href: how-to-work-with-image-columns-in-the-windows-forms-datagridview-control.md + - name: Customizing the Windows Forms DataGridView Control + href: customizing-the-windows-forms-datagridview-control.md + items: + - name: "How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control" + href: customize-the-appearance-of-cells-in-the-datagrid.md + - name: "How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control" + href: customize-the-appearance-of-rows-in-the-datagrid.md + - name: "How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance" + href: customize-cells-and-columns-in-the-datagrid-by-extending-behavior.md + - name: "How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control" + href: disable-buttons-in-a-button-column-in-the-datagrid.md + - name: "How to: Host Controls in Windows Forms DataGridView Cells" + href: how-to-host-controls-in-windows-forms-datagridview-cells.md + - name: Performance Tuning in the Windows Forms DataGridView Control + href: performance-tuning-in-the-windows-forms-datagridview-control.md + items: + - name: Best Practices for Scaling the Windows Forms DataGridView Control + href: best-practices-for-scaling-the-windows-forms-datagridview-control.md + - name: Virtual Mode in the Windows Forms DataGridView Control + href: virtual-mode-in-the-windows-forms-datagridview-control.md + - name: "Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control" + href: implementing-virtual-mode-wf-datagridview-control.md + items: + - name: "How to: Implement Virtual Mode in the Windows Forms DataGridView Control" + href: how-to-implement-virtual-mode-in-the-windows-forms-datagridview-control.md + - name: Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control + href: implementing-virtual-mode-jit-data-loading-in-the-datagrid.md + items: + - name: "How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control" + href: virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md + - name: Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control + href: default-keyboard-and-mouse-handling-in-the-windows-forms-datagridview-control.md + - name: Differences Between the Windows Forms DataGridView and DataGrid Controls + href: differences-between-the-windows-forms-datagridview-and-datagrid-controls.md + - name: DateTimePicker Control + href: datetimepicker-control-windows-forms.md + items: + - name: DateTimePicker Control Overview + href: datetimepicker-control-overview-windows-forms.md + - name: "How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control" + href: display-a-date-in-a-custom-format-with-wf-datetimepicker-control.md + - name: "How to: Set and Return Dates with the Windows Forms DateTimePicker Control" + href: how-to-set-and-return-dates-with-the-windows-forms-datetimepicker-control.md + - name: "How to: Display Time with the DateTimePicker Control" + href: how-to-display-time-with-the-datetimepicker-control.md + - name: Dialog-Box Controls and Components + href: dialog-box-controls-and-components-windows-forms.md + - name: DomainUpDown Control + href: domainupdown-control-windows-forms.md + items: + - name: DomainUpDown Control Overview + href: domainupdown-control-overview-windows-forms.md + - name: "How to: Add Items to DomainUpDown Controls Programmatically" + href: how-to-add-items-to-windows-forms-domainupdown-controls-programmatically.md + - name: "How to: Remove Items from Windows Forms DomainUpDown Controls" + href: how-to-remove-items-from-windows-forms-domainupdown-controls.md + - name: ErrorProvider Component + href: errorprovider-component-windows-forms.md + items: + - name: ErrorProvider Component Overview + href: errorprovider-component-overview-windows-forms.md + - name: "How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component" + href: display-error-icons-for-form-validation-with-wf-errorprovider.md + - name: "How to: View Errors Within a DataSet with the Windows Forms ErrorProvider Component" + href: view-errors-within-a-dataset-with-wf-errorprovider-component.md + - name: FileDialog Class + href: filedialog-class.md + items: + - name: "How To: Opt Out of File Dialog Box Automatic Upgrade" + href: how-to-opt-out-of-file-dialog-box-automatic-upgrade.md + - name: "How To: Add a Custom Place to a File Dialog Box" + href: how-to-add-a-custom-place-to-a-file-dialog-box.md + - name: Known Folder GUIDs for File Dialog Custom Places + href: known-folder-guids-for-file-dialog-custom-places.md + - name: FlowLayoutPanel Control + href: flowlayoutpanel-control-windows-forms.md + items: + - name: FlowLayoutPanel Control Overview + href: flowlayoutpanel-control-overview.md + - name: "How to: Anchor and Dock Child Controls in a FlowLayoutPanel Control" + href: how-to-anchor-and-dock-child-controls-in-a-flowlayoutpanel-control.md + - name: "Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel" + href: walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md + - name: FolderBrowserDialog Component + href: folderbrowserdialog-component-windows-forms.md + items: + - name: FolderBrowserDialog Component Overview (Windows Forms) + href: folderbrowserdialog-component-overview-windows-forms.md + - name: "How to: Choose Folders with the Windows Forms FolderBrowserDialog Component" + href: how-to-choose-folders-with-the-windows-forms-folderbrowserdialog-component.md + - name: FontDialog Component + href: fontdialog-component-windows-forms.md + items: + - name: FontDialog Component Overview + href: fontdialog-component-overview-windows-forms.md + - name: "How to: Show a Font List with the FontDialog Component" + href: how-to-show-a-font-list-with-the-fontdialog-component.md + - name: GroupBox Control + href: groupbox-control-windows-forms.md + items: + - name: GroupBox Control Overview + href: groupbox-control-overview-windows-forms.md + - name: "How to: Group Controls with the Windows Forms GroupBox Control" + href: how-to-group-controls-with-the-windows-forms-groupbox-control.md + - name: HelpProvider Component + href: helpprovider-component-windows-forms.md + items: + - name: HelpProvider Component Overview + href: helpprovider-component-overview-windows-forms.md + - name: HScrollBar and VScrollBar Controls + href: hscrollbar-and-vscrollbar-controls-windows-forms.md + items: + - name: HScrollBar and VScrollBar Controls Overview + href: hscrollbar-and-vscrollbar-controls-overview-windows-forms.md + - name: ImageList Component + href: imagelist-component-windows-forms.md + items: + - name: ImageList Component Overview + href: imagelist-component-overview-windows-forms.md + - name: "How to: Add or Remove Images with the Windows Forms ImageList Component" + href: how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md + - name: "How to: Add or Remove ImageList Images with the Designer" + href: how-to-add-or-remove-imagelist-images-with-the-designer.md + - name: Label Control + href: label-control-windows-forms.md + items: + - name: Label Control Overview + href: label-control-overview-windows-forms.md + - name: "How to: Create Access Keys with Windows Forms Label Controls" + href: how-to-create-access-keys-with-windows-forms-label-controls.md + - name: "How to: Size a Windows Forms Label Control to Fit Its Contents" + href: how-to-size-a-windows-forms-label-control-to-fit-its-contents.md + - name: LinkLabel Control + href: linklabel-control-windows-forms.md + items: + - name: LinkLabel Control Overview + href: linklabel-control-overview-windows-forms.md + - name: "How to: Change the Appearance of the Windows Forms LinkLabel Control" + href: how-to-change-the-appearance-of-the-windows-forms-linklabel-control.md + - name: "How to: Link to an Object or Web Page with the Windows Forms LinkLabel Control" + href: link-to-an-object-or-web-page-with-wf-linklabel-control.md + - name: "How to: Display a Web Page from a Windows Forms LinkLabel Control (Visual Basic)" + href: display-a-web-page-from-a-wf-linklabel-control-visual-basic.md + - name: ListBox Control + href: listbox-control-windows-forms.md + items: + - name: ListBox Control Overview + href: listbox-control-overview-windows-forms.md + - name: ListView Control + href: listview-control-windows-forms.md + items: + - name: ListView Control Overview + href: listview-control-overview-windows-forms.md + - name: "How to: Add and Remove Items with the Windows Forms ListView Control" + href: how-to-add-and-remove-items-with-the-windows-forms-listview-control.md + - name: "How to: Add and Remove Items with the Windows Forms ListView Control Using the Designer" + href: add-and-remove-items-with-wf-listview-control-using-the-designer.md + - name: "How to: Add Columns to the Windows Forms ListView Control" + href: how-to-add-columns-to-the-windows-forms-listview-control.md + - name: "How to: Add Columns to the Windows Forms ListView Control Using the Designer" + href: how-to-add-columns-to-the-windows-forms-listview-control-using-the-designer.md + - name: "How to: Add Search Capabilities to a ListView Control" + href: how-to-add-search-capabilities-to-a-listview-control.md + - name: "How to: Display Icons for the Windows Forms ListView Control" + href: how-to-display-icons-for-the-windows-forms-listview-control.md + - name: "How to: Display Subitems in Columns with the Windows Forms ListView Control" + href: how-to-display-subitems-in-columns-with-the-windows-forms-listview-control.md + - name: "How to: Enable Tile View in a Windows Forms ListView Control" + href: how-to-enable-tile-view-in-a-windows-forms-listview-control.md + - name: "How to: Enable Tile View in a Windows Forms ListView Control Using the Designer" + href: enable-tile-view-in-a-wf-listview-control-using-the-designer.md + - name: "How to: Group Items in a Windows Forms ListView Control" + href: how-to-group-items-in-a-windows-forms-listview-control.md + - name: "How to: Group Items in a Windows Forms ListView Control Using the Designer" + href: how-to-group-items-in-a-windows-forms-listview-control-using-the-designer.md + - name: "How to: Display an Insertion Mark in a Windows Forms ListView Control" + href: how-to-display-an-insertion-mark-in-a-windows-forms-listview-control.md + - name: "How to: Select an Item in the Windows Forms ListView Control" + href: how-to-select-an-item-in-the-windows-forms-listview-control.md + - name: "Walkthrough: Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer" + href: creating-an-explorer-style-interface-with-the-listview-and-treeview.md + - name: MainMenu Component + href: mainmenu-component-windows-forms.md + items: + - name: MainMenu Component Overview + href: mainmenu-component-overview-windows-forms.md + - name: MaskedTextBox Control + href: maskedtextbox-control-windows-forms.md + items: + - name: "Walkthrough: Working with the MaskedTextBox Control" + href: walkthrough-working-with-the-maskedtextbox-control.md + - name: "How to: Bind Data to the MaskedTextBox Control" + href: how-to-bind-data-to-the-maskedtextbox-control.md + - name: "How to: Set the Input Mask" + href: how-to-set-the-input-mask.md + - name: MenuStrip Control + href: menustrip-control-windows-forms.md + items: + - name: MenuStrip Control Overview + href: menustrip-control-overview-windows-forms.md + - name: "How to: Add Enhancements to ToolStripMenuItems" + href: how-to-add-enhancements-to-toolstripmenuitems.md + - name: "How to: Append a MenuStrip to an MDI Parent Window" + href: how-to-append-a-menustrip-to-an-mdi-parent-window-windows-forms.md + - name: "How to: Copy ToolStripMenuItems" + href: how-to-copy-toolstripmenuitems.md + - name: "How to: Create an MDI Window List with MenuStrip" + href: how-to-create-an-mdi-window-list-with-menustrip-windows-forms.md + - name: "How to: Disable ToolStripMenuItems" + href: how-to-disable-toolstripmenuitems.md + - name: "How to: Disable ToolStripMenuItems Using the Designer" + href: how-to-disable-toolstripmenuitems-using-the-designer.md + - name: "How to: Display Option Buttons in a MenuStrip" + href: how-to-display-option-buttons-in-a-menustrip-windows-forms.md + - name: "How to: Hide ToolStripMenuItems" + href: how-to-hide-toolstripmenuitems.md + - name: "How to: Hide ToolStripMenuItems Using the Designer" + href: how-to-hide-toolstripmenuitems-using-the-designer.md + - name: "How to: Insert a MenuStrip into an MDI Drop-Down Menu" + href: how-to-insert-a-menustrip-into-an-mdi-drop-down-menu-windows-forms.md + - name: "How to: Remove a ToolStripMenuItem from an MDI Drop-Down Menu" + href: how-to-remove-a-toolstripmenuitem-from-an-mdi-drop-down-menu-windows-forms.md + - name: "How to: Move ToolStripMenuItems" + href: how-to-move-toolstripmenuitems.md + - name: "How to: Configure MenuStrip Check Margins and Image Margins" + href: how-to-configure-menustrip-check-margins-and-image-margins.md + - name: "How to: Provide Standard Menu Items to a Form" + href: how-to-provide-standard-menu-items-to-a-form.md + - name: "How to: Set Up Automatic Menu Merging for MDI Applications" + href: how-to-set-up-automatic-menu-merging-for-mdi-applications.md + - name: Merging Menu Items in the Windows Forms MenuStrip Control + href: merging-menu-items-in-the-windows-forms-menustrip-control.md + - name: "Walkthrough: Providing Standard Menu Items to a Form" + href: walkthrough-providing-standard-menu-items-to-a-form.md + - name: MonthCalendar Control + href: monthcalendar-control-windows-forms.md + items: + - name: MonthCalendar Control Overview + href: monthcalendar-control-overview-windows-forms.md + - name: "How to: Change the Windows Forms MonthCalendar Control's Appearance" + href: how-to-change-monthcalendar-control-appearance.md + - name: "How to: Display More than One Month in the Windows Forms MonthCalendar Control" + href: display-more-than-one-month-wf-monthcalendar-control.md + - name: "How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control" + href: display-specific-days-in-bold-with-wf-monthcalendar-control.md + - name: "How to: Select a Range of Dates in the Windows Forms MonthCalendar Control" + href: how-to-select-a-range-of-dates-in-the-windows-forms-monthcalendar-control.md + - name: NotifyIcon Component + href: notifyicon-component-windows-forms.md + items: + - name: NotifyIcon Component Overview + href: notifyicon-component-overview-windows-forms.md + - name: "How to: Add Application Icons to the TaskBar with the Windows Forms NotifyIcon Component" + href: app-icons-to-the-taskbar-with-wf-notifyicon.md + - name: "How to: Associate a Shortcut Menu with a Windows Forms NotifyIcon Component" + href: how-to-associate-a-shortcut-menu-with-a-windows-forms-notifyicon-component.md + - name: NumericUpDown Control + href: numericupdown-control-windows-forms.md + items: + - name: NumericUpDown Control Overview + href: numericupdown-control-overview-windows-forms.md + - name: "How to: Set and Return Numeric Values with the Windows Forms NumericUpDown Control" + href: set-and-return-numeric-values-with-wf-numericupdown-control.md + - name: "How to: Set the Format for the Windows Forms NumericUpDown Control" + href: how-to-set-the-format-for-the-windows-forms-numericupdown-control.md + - name: OpenFileDialog Component + href: openfiledialog-component-windows-forms.md + items: + - name: OpenFileDialog Component Overview + href: openfiledialog-component-overview-windows-forms.md + - name: "How to: Open Files Using the OpenFileDialog Component" + href: how-to-open-files-using-the-openfiledialog-component.md + - name: PageSetupDialog Component + href: pagesetupdialog-component-windows-forms.md + items: + - name: PageSetupDialog Component Overview + href: pagesetupdialog-component-overview-windows-forms.md + - name: "How to: Determine Page Properties Using the PageSetupDialog Component" + href: how-to-determine-page-properties-using-the-pagesetupdialog-component.md + - name: Panel Control + href: panel-control-windows-forms.md + items: + - name: Panel Control Overview + href: panel-control-overview-windows-forms.md + - name: "How to: Group Controls with the Windows Forms Panel Control Using the Designer" + href: group-controls-with-wf-panel-control-using-the-designer.md + - name: "How to: Set the Background of a Panel" + href: how-to-set-the-background-of-a-windows-forms-panel.md + - name: "How to: Set the Background of a Windows Forms Panel Using the Designer" + href: how-to-set-the-background-of-a-windows-forms-panel-using-the-designer.md + - name: PictureBox Control + href: picturebox-control-windows-forms.md + items: + - name: PictureBox Control Overview + href: picturebox-control-overview-windows-forms.md + - name: "How to: Load a Picture Using the Designer" + href: how-to-load-a-picture-using-the-designer-windows-forms.md + - name: "How to: Modify the Size or Placement of a Picture at Run Time" + href: how-to-modify-the-size-or-placement-of-a-picture-at-run-time-windows-forms.md + - name: "How to: Set Pictures at Run Time" + href: how-to-set-pictures-at-run-time-windows-forms.md + - name: PrintDialog Component + href: printdialog-component-windows-forms.md + items: + - name: PrintDialog Component Overview + href: printdialog-component-overview-windows-forms.md + - name: "How to: Display the PrintDialog Component" + href: how-to-display-the-printdialog-component.md + - name: PrintDocument Component + href: printdocument-component-windows-forms.md + items: + - name: PrintDocument Component Overview + href: printdocument-component-overview-windows-forms.md + - name: PrintPreviewControl Control + href: printpreviewcontrol-control-windows-forms.md + items: + - name: PrintPreviewControl Control Overview + href: printpreviewcontrol-control-overview-windows-forms.md + - name: PrintPreviewDialog Control + href: printpreviewdialog-control-windows-forms.md + items: + - name: PrintPreviewDialog Control Overview + href: printpreviewdialog-control-overview-windows-forms.md + - name: "How to: Display Print Preview in Windows Forms Applications" + href: how-to-display-print-preview-in-windows-forms-applications.md + - name: ProgressBar Control + href: progressbar-control-windows-forms.md + items: + - name: ProgressBar Control Overview + href: progressbar-control-overview-windows-forms.md + - name: "How to: Set the Value Displayed by the Windows Forms ProgressBar Control" + href: how-to-set-the-value-displayed-by-the-windows-forms-progressbar-control.md + - name: RadioButton Control + href: radiobutton-control-windows-forms.md + items: + - name: RadioButton Control Overview + href: radiobutton-control-overview-windows-forms.md + - name: "How to: Group Windows Forms RadioButton Controls to Function as a Set" + href: how-to-group-windows-forms-radiobutton-controls-to-function-as-a-set.md + - name: RichTextBox Control + href: richtextbox-control-windows-forms.md + items: + - name: RichTextBox Control Overview + href: richtextbox-control-overview-windows-forms.md + - name: "How to: Determine When Formatting Attributes Change in the Windows Forms RichTextBox Control" + href: determine-when-formatting-attributes-change-wf-richtextbox-control.md + - name: "How to: Display Scroll Bars in the Windows Forms RichTextBox Control" + href: how-to-display-scroll-bars-in-the-windows-forms-richtextbox-control.md + - name: "How to: Display Web-Style Links with the Windows Forms RichTextBox Control" + href: how-to-display-web-style-links-with-the-windows-forms-richtextbox-control.md + - name: "How to: Enable Drag-and-Drop Operations with the Windows Forms RichTextBox Control" + href: enable-drag-and-drop-operations-with-wf-richtextbox-control.md + - name: "How to: Load Files into the Windows Forms RichTextBox Control" + href: how-to-load-files-into-the-windows-forms-richtextbox-control.md + - name: "How to: Save Files with the Windows Forms RichTextBox Control" + href: how-to-save-files-with-the-windows-forms-richtextbox-control.md + - name: "How to: Set Font Attributes for the Windows Forms RichTextBox Control" + href: how-to-set-font-attributes-for-the-windows-forms-richtextbox-control.md + - name: "How to: Set Indents, Hanging Indents, and Bulleted Paragraphs with the Windows Forms RichTextBox Control" + href: set-indents-hanging-indents-bulleted-paragraphs-with-wf-richtextbox.md + - name: SaveFileDialog Component + href: savefiledialog-component-windows-forms.md + items: + - name: SaveFileDialog Component Overview + href: savefiledialog-component-overview-windows-forms.md + - name: "How to: Save Files Using the SaveFileDialog Component" + href: how-to-save-files-using-the-savefiledialog-component.md + - name: SoundPlayer Class + href: soundplayer-class.md + items: + - name: SoundPlayer Class Overview + href: soundplayer-class-overview.md + - name: "How to: Play a Sound from a Windows Form" + href: how-to-play-a-sound-from-a-windows-form.md + - name: "How to: Play a Beep from a Windows Form" + href: how-to-play-a-beep-from-a-windows-form.md + - name: "How to: Play a Sound Embedded in a Resource from a Windows Form" + href: how-to-play-a-sound-embedded-in-a-resource-from-a-windows-form.md + - name: "How to: Play a System Sound from a Windows Form" + href: how-to-play-a-system-sound-from-a-windows-form.md + - name: "How to: Load a Sound Asynchronously within a Windows Form" + href: how-to-load-a-sound-asynchronously-within-a-windows-form.md + - name: "How to: Loop a Sound Playing on a Windows Form" + href: how-to-loop-a-sound-playing-on-a-windows-form.md + - name: SplitContainer Control + href: splitcontainer-control-windows-forms.md + items: + - name: SplitContainer Control Overview + href: splitcontainer-control-overview-windows-forms.md + - name: "How to: Create a Multipane User Interface with Windows Forms" + href: how-to-create-a-multipane-user-interface-with-windows-forms.md + - name: "How to: Create a Multipane User Interface with Windows Forms Using the Designer" + href: create-a-multipane-user-interface-with-wf-using-the-designer.md + - name: "How to: Create a Windows Explorer–Style Interface on a Windows Form" + href: how-to-create-a-windows-explorer-style-interface-on-a-windows-form.md + - name: "How to: Define Resize and Positioning Behavior in a Split Window" + href: how-to-define-resize-and-positioning-behavior-in-a-split-window.md + - name: "How to: Split a Window Horizontally" + href: how-to-split-a-window-horizontally.md + - name: "How to: Split a Window Horizontally Using the Designer" + href: how-to-split-a-window-horizontally-using-the-designer.md + - name: Splitter Control + href: splitter-control-windows-forms.md + items: + - name: Splitter Control Overview + href: splitter-control-overview-windows-forms.md + - name: StatusBar Control + href: statusbar-control-windows-forms.md + items: + - name: StatusBar Control Overview + href: statusbar-control-overview-windows-forms.md + - name: "How to: Add Panels to a StatusBar Control" + href: how-to-add-panels-to-a-statusbar-control.md + - name: "How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked" + href: determine-which-panel-wf-statusbar-control-was-clicked.md + - name: "How to: Set the Size of Status-Bar Panels" + href: how-to-set-the-size-of-status-bar-panels.md + - name: "Walkthrough: Updating Status Bar Information at Run Time" + href: walkthrough-updating-status-bar-information-at-run-time.md + - name: StatusStrip Control + href: statusstrip-control.md + items: + - name: StatusStrip Control Overview + href: statusstrip-control-overview.md + - name: "How to: Use the Spring Property Interactively in a StatusStrip" + href: how-to-use-the-spring-property-interactively-in-a-statusstrip.md + - name: TabControl Control + href: tabcontrol-control-windows-forms.md + items: + - name: TabControl Control Overview + href: tabcontrol-control-overview-windows-forms.md + - name: "How to: Add a Control to a Tab Page" + href: how-to-add-a-control-to-a-tab-page.md + - name: "How to: Add a Control to a Tab Page Using the Designer" + href: how-to-add-a-control-to-a-tab-page-using-the-designer.md + - name: "How to: Add and Remove Tabs with the Windows Forms TabControl" + href: how-to-add-and-remove-tabs-with-the-windows-forms-tabcontrol.md + - name: "How to: Add and Remove Tabs with the Windows Forms TabControl Using the Designer" + href: add-and-remove-tabs-with-wf-tabcontrol-using-the-designer.md + - name: "How to: Change the Appearance of the Windows Forms TabControl" + href: how-to-change-the-appearance-of-the-windows-forms-tabcontrol.md + - name: "How to: Disable Tab Pages" + href: how-to-disable-tab-pages.md + - name: "How to: Display Side-Aligned Tabs with TabControl" + href: how-to-display-side-aligned-tabs-with-tabcontrol.md + - name: TableLayoutPanel Control + href: tablelayoutpanel-control-windows-forms.md + items: + - name: TableLayoutPanel Control Overview + href: tablelayoutpanel-control-overview.md + - name: AutoSize Behavior in the TableLayoutPanel Control + href: autosize-behavior-in-the-tablelayoutpanel-control.md + - name: Best Practices for the TableLayoutPanel Control + href: best-practices-for-the-tablelayoutpanel-control.md + - name: "How to: Align and Stretch a Control in a TableLayoutPanel Control" + href: how-to-align-and-stretch-a-control-in-a-tablelayoutpanel-control.md + - name: "How to: Anchor and Dock Child Controls in a TableLayoutPanel Control" + href: how-to-anchor-and-dock-child-controls-in-a-tablelayoutpanel-control.md + - name: "How to: Create a Resizable Windows Form for Data Entry" + href: how-to-create-a-resizable-windows-form-for-data-entry.md + - name: "How to: Design a Windows Forms Layout that Responds Well to Localization" + href: how-to-design-a-windows-forms-layout-that-responds-well-to-localization.md + - name: "How to: Edit Columns and Rows in a TableLayoutPanel Control" + href: how-to-edit-columns-and-rows-in-a-tablelayoutpanel-control.md + - name: "How to: Span Rows and Columns in a TableLayoutPanel Control" + href: how-to-span-rows-and-columns-in-a-tablelayoutpanel-control.md + - name: "Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel" + href: walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md + - name: TextBox Control + href: textbox-control-windows-forms.md + items: + - name: TextBox Control Overview + href: textbox-control-overview-windows-forms.md + - name: "How to: Control the Insertion Point in a Windows Forms TextBox Control" + href: how-to-control-the-insertion-point-in-a-windows-forms-textbox-control.md + - name: "How to: Create a Password Text Box with the Windows Forms TextBox Control" + href: how-to-create-a-password-text-box-with-the-windows-forms-textbox-control.md + - name: "How to: Create a Read-Only Text Box" + href: how-to-create-a-read-only-text-box-windows-forms.md + - name: "How to: Put Quotation Marks in a String" + href: how-to-put-quotation-marks-in-a-string-windows-forms.md + - name: "How to: Select Text in the Windows Forms TextBox Control" + href: how-to-select-text-in-the-windows-forms-textbox-control.md + - name: "How to: View Multiple Lines in the Windows Forms TextBox Control" + href: how-to-view-multiple-lines-in-the-windows-forms-textbox-control.md + - name: Timer Component + href: timer-component-windows-forms.md + items: + - name: Timer Component Overview + href: timer-component-overview-windows-forms.md + - name: Limitations of the Windows Forms Timer Component's Interval Property + href: limitations-of-the-timer-component-interval-property.md + - name: "How to: Run Procedures at Set Intervals with the Windows Forms Timer Component" + href: run-procedures-at-set-intervals-with-wf-timer-component.md + - name: ToolBar Control + href: toolbar-control-windows-forms.md + items: + - name: ToolBar Control Overview + href: toolbar-control-overview-windows-forms.md + - name: "How to: Add Buttons to a ToolBar Control" + href: how-to-add-buttons-to-a-toolbar-control.md + - name: "How to: Add Buttons to a ToolBar Control Using the Designer" + href: how-to-add-buttons-to-a-toolbar-control-using-the-designer.md + - name: "How to: Define an Icon for a ToolBar Button" + href: how-to-define-an-icon-for-a-toolbar-button.md + - name: "How to: Define an Icon for a ToolBar Button Using the Designer" + href: how-to-define-an-icon-for-a-toolbar-button-using-the-designer.md + - name: "How to: Trigger Menu Events for Toolbar Buttons" + href: how-to-trigger-menu-events-for-toolbar-buttons.md + - name: ToolStrip Control + href: toolstrip-control-windows-forms.md + items: + - name: ToolStrip Control Overview + href: toolstrip-control-overview-windows-forms.md + - name: ToolStrip Technology Summary + href: toolstrip-technology-summary.md + - name: ToolStrip Control Architecture + href: toolstrip-control-architecture.md + - name: "How to: Add ToolStrip Items Dynamically" + href: how-to-add-toolstrip-items-dynamically.md + - name: "How to: Create a Basic ToolStrip with Standard Items Using the Designer" + href: create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md + - name: "How to: Create a Professionally Styled ToolStrip Control" + href: how-to-create-a-professionally-styled-toolstrip-control.md + - name: "How to: Create an MDI Form with Menu Merging and ToolStrip Controls" + href: how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md + - name: "How to: Create an MDI Form with ToolStripPanel Controls" + href: how-to-create-an-mdi-form-with-toolstrippanel-controls.md + - name: "How to: Change the Appearance of ToolStrip Text and Images in Windows Forms" + href: how-to-change-the-appearance-of-toolstrip-text-and-images-in-windows-forms.md + - name: "How to: Change the Spacing and Alignment of ToolStrip Items in Windows Forms" + href: how-to-change-the-spacing-and-alignment-of-toolstrip-items-in-windows-forms.md + - name: "How to: Create and Set a Custom Renderer for the ToolStrip Control in Windows Forms" + href: create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md + - name: "How to: Create Toggle Buttons in ToolStrip Controls" + href: how-to-create-toggle-buttons-in-toolstrip-controls.md + - name: "How to: Custom Draw a ToolStrip Control" + href: how-to-custom-draw-a-toolstrip-control.md + - name: "How to: Customize Colors in ToolStrip Applications" + href: how-to-customize-colors-in-toolstrip-applications.md + - name: "How to: Define Z-Ordering of Docked ToolStrip Controls" + href: how-to-define-z-ordering-of-docked-toolstrip-controls.md + - name: "How to: Detect When the Mouse Pointer Is Over a ToolStripItem" + href: how-to-detect-when-the-mouse-pointer-is-over-a-toolstripitem.md + - name: "How to: Enable AutoComplete in ToolStrip Controls" + href: how-to-enable-autocomplete-in-toolstrip-controls-in-windows-forms.md + - name: "How to: Enable Reordering of ToolStrip Items at Run Time" + href: how-to-enable-reordering-of-toolstrip-items-at-run-time-in-windows-forms.md + - name: "How to: Enable the TAB Key to Move Out of a ToolStrip Control" + href: how-to-enable-the-tab-key-to-move-out-of-a-toolstrip-control.md + - name: "How to: Implement a Custom ToolStripRenderer" + href: how-to-implement-a-custom-toolstriprenderer.md + - name: "How to: Manage ToolStrip Overflow" + href: how-to-manage-toolstrip-overflow-in-windows-forms.md + - name: "How to: Move a ToolStrip Out of a ToolStripContainer onto a Form" + href: how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md + - name: "How to: Position a ToolStripItem on a ToolStrip" + href: how-to-position-a-toolstripitem-on-a-toolstrip.md + - name: "How to: Set the ToolStrip Renderer at Run Time" + href: how-to-set-the-toolstrip-renderer-at-run-time.md + - name: "How to: Set the ToolStrip Renderer for an Application" + href: how-to-set-the-toolstrip-renderer-for-an-application.md + - name: "How to: Stretch a ToolStripTextBox to Fill the Remaining Width of a ToolStrip" + href: stretch-a-toolstriptextbox-to-fill-the-remaining-width-of-a-toolstrip-wf.md + - name: "How to: Use ToolTips in ToolStrip Controls" + href: how-to-use-tooltips-in-toolstrip-controls.md + - name: "How to: Wrap a Windows Forms Control with ToolStripControlHost" + href: how-to-wrap-a-windows-forms-control-with-toolstripcontrolhost.md + - name: "Walkthrough: Creating a Professionally Styled ToolStrip Control" + href: walkthrough-creating-a-professionally-styled-toolstrip-control.md + - name: "Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls" + href: walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md + - name: ToolStripContainer Control + href: toolstripcontainer-control.md + items: + - name: ToolStripContainer Control Overview + href: toolstripcontainer-control-overview.md + - name: "How to: Add a ToolStripContainer to a Form" + href: how-to-add-a-toolstripcontainer-to-a-form.md + - name: "How to: Add a Control to a ToolStripContentPanel" + href: how-to-add-a-control-to-a-toolstripcontentpanel.md + - name: ToolStripPanel Control + href: toolstrippanel-control.md + items: + - name: ToolStripPanel Control Overview + href: toolstrippanel-control-overview.md + - name: "How to: Join ToolStripPanels" + href: how-to-join-toolstrippanels.md + - name: "How to: Use ToolStripPanels for MDI" + href: how-to-use-toolstrippanels-for-mdi.md + - name: ToolStripProgressBar Control + href: toolstripprogressbar-control.md + items: + - name: ToolStripProgressBar Control Overview + href: toolstripprogressbar-control-overview.md + - name: ToolStripStatusLabel Control + href: toolstripstatuslabel-control.md + items: + - name: ToolStripStatusLabel Control Overview + href: toolstripstatuslabel-control-overview.md + - name: ToolTip Component + href: tooltip-component-windows-forms.md + items: + - name: ToolTip Component Overview + href: tooltip-component-overview-windows-forms.md + - name: "How to: Set ToolTips for Controls on a Windows Form at Design Time" + href: how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md + - name: "How to: Change the Delay of the Windows Forms ToolTip Component" + href: how-to-change-the-delay-of-the-windows-forms-tooltip-component.md + - name: TrackBar Control + href: trackbar-control-windows-forms.md + items: + - name: TrackBar Control Overview + href: trackbar-control-overview-windows-forms.md + - name: TreeView Control + href: treeview-control-windows-forms.md + items: + - name: TreeView Control Overview + href: treeview-control-overview-windows-forms.md + - name: "How to: Add and Remove Nodes with the Windows Forms TreeView Control" + href: how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md + - name: "How to: Add and Remove Nodes with the Windows Forms TreeView Control Using the Designer" + href: add-and-remove-nodes-with-wf-treeview-control-using-the-designer.md + - name: "How to: Attach a ShortCut Menu to a TreeView Node" + href: how-to-attach-a-shortcut-menu-to-a-treeview-node.md + - name: "How to: Attach a Shortcut Menu to a TreeNode Using the Designer" + href: how-to-attach-a-shortcut-menu-to-a-treenode-using-the-designer.md + - name: "How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)" + href: add-custom-information-to-a-treeview-or-listview-control-wf.md + - name: "How to: Determine Which TreeView Node Was Clicked" + href: how-to-determine-which-treeview-node-was-clicked-windows-forms.md + - name: "How to: Iterate Through All Nodes of a Windows Forms TreeView Control" + href: how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md + - name: "How to: Set Icons for the Windows Forms TreeView Control" + href: how-to-set-icons-for-the-windows-forms-treeview-control.md + - name: WebBrowser Control + href: webbrowser-control-windows-forms.md + items: + - name: WebBrowser Control Overview + href: webbrowser-control-overview.md + - name: WebBrowser Security + href: webbrowser-security.md + - name: "How to: Navigate to a URL with the WebBrowser Control" + href: how-to-navigate-to-a-url-with-the-webbrowser-control.md + - name: "How to: Print with a WebBrowser Control" + href: how-to-print-with-a-webbrowser-control.md + - name: "How to: Add Web Browser Capabilities to a Windows Forms Application" + href: how-to-add-web-browser-capabilities-to-a-windows-forms-application.md + - name: "How to: Create an HTML Document Viewer in a Windows Forms Application" + href: how-to-create-an-html-document-viewer-in-a-windows-forms-application.md + - name: "How to: Implement Two-Way Communication Between DHTML Code and Client Application Code" + href: implement-two-way-com-between-dhtml-and-client.md + - name: Using the Managed HTML Document Object Model + href: using-the-managed-html-document-object-model.md + items: + - name: "How to: Access the Managed HTML Document Object Model" + href: how-to-access-the-managed-html-document-object-model.md + - name: "How to: Access the HTML Source in the Managed HTML Document Object Model" + href: how-to-access-the-html-source-in-the-managed-html-document-object-model.md + - name: "How to: Change Styles on an Element in the Managed HTML Document Object Model" + href: how-to-change-styles-on-an-element-in-the-managed-html-document-object-model.md + - name: Accessing Frames in the Managed HTML Document Object Model + href: accessing-frames-in-the-managed-html-document-object-model.md + - name: Accessing Unexposed Members on the Managed HTML Document Object Model + href: accessing-unexposed-members-on-the-managed-html-document-object-model.md + - name: Windows Forms Controls Used to List Options + href: windows-forms-controls-used-to-list-options.md + items: + - name: When to Use a Windows Forms ComboBox Instead of a ListBox + href: when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md + - name: "How to: Access Specific Items in a Windows Forms ComboBox, ListBox, or CheckedListBox Control" + href: access-specific-items-in-a-wf-combobox-listbox-or-checkedlistbox.md + - name: "How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control" + href: add-and-remove-items-from-a-wf-combobox.md + - name: "How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control" + href: create-a-lookup-table-for-a-wf-combobox-listbox.md + - name: "How to: Bind a Windows Forms ComboBox or ListBox Control to Data" + href: how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md + - name: "How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control" + href: sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md + - name: Developing Custom Windows Forms Controls with the .NET Framework + href: developing-custom-windows-forms-controls.md + items: + - name: Overview of Using Controls in Windows Forms + href: overview-of-using-controls-in-windows-forms.md + - name: Varieties of Custom Controls + href: varieties-of-custom-controls.md + items: + - name: Control Type Recommendations + href: control-type-recommendations.md + - name: Windows Forms Control Development Basics + href: windows-forms-control-development-basics.md + items: + - name: "How to: Develop a Simple Windows Forms Control" + href: how-to-develop-a-simple-windows-forms-control.md + - name: "How to: Create a Windows Forms Control That Shows Progress" + href: how-to-create-a-windows-forms-control-that-shows-progress.md + - name: Developing a Composite Windows Forms Control + href: developing-a-composite-windows-forms-control.md + - name: Properties in Windows Forms Controls + href: properties-in-windows-forms-controls.md + items: + - name: Defining a Property + href: defining-a-property-in-windows-forms-controls.md + - name: Defining Default Values with the ShouldSerialize and Reset Methods + href: defining-default-values-with-the-shouldserialize-and-reset-methods.md + - name: Property-Changed Events + href: property-changed-events.md + - name: "How to: Expose Properties of Constituent Controls" + href: how-to-expose-properties-of-constituent-controls.md + - name: Method Implementation in Custom Controls + href: method-implementation-in-custom-controls.md + - name: Events in Windows Forms Controls + href: events-in-windows-forms-controls.md + items: + - name: Overriding the OnPaint Method + href: overriding-the-onpaint-method.md + - name: Handling User Input + href: handling-user-input.md + - name: Defining an Event + href: defining-an-event-in-windows-forms-controls.md + - name: Attributes in Windows Forms Controls + href: attributes-in-windows-forms-controls.md + items: + - name: "How to: Apply Attributes in Windows Forms Controls" + href: how-to-apply-attributes-in-windows-forms-controls.md + - name: Custom Control Painting and Rendering + href: custom-control-painting-and-rendering.md + items: + - name: Rendering a Windows Forms Control + href: rendering-a-windows-forms-control.md + - name: User-Drawn Controls + href: user-drawn-controls.md + - name: Constituent Controls + href: constituent-controls.md + - name: "How to: Make Your Control Invisible at Run Time" + href: how-to-make-your-control-invisible-at-run-time.md + - name: "How to: Give Your Control a Transparent Background" + href: how-to-give-your-control-a-transparent-background.md + - name: Rendering Controls with Visual Styles + href: rendering-controls-with-visual-styles.md + items: + - name: "How to: Use a Control Rendering Class" + href: how-to-use-a-control-rendering-class.md + - name: "How to: Render a Visual Style Element" + href: how-to-render-a-visual-style-element.md + - name: Layout in Windows Forms Controls + href: layout-in-windows-forms-controls.md + items: + - name: AutoSize Property Overview + href: autosize-property-overview.md + - name: "How to: Align a Control to the Edges of Forms" + href: how-to-align-a-control-to-the-edges-of-forms.md + - name: Margin and Padding in Windows Forms Controls + href: margin-and-padding-in-windows-forms-controls.md + - name: "How to: Create a Border Around a Windows Forms Control Using Padding" + href: how-to-create-a-border-around-a-windows-forms-control-using-padding.md + - name: "How to: Implement a Custom Layout Engine" + href: how-to-implement-a-custom-layout-engine.md + - name: Multithreading in Windows Forms Controls + href: multithreading-in-windows-forms-controls.md + items: + - name: "How to: Make Thread-Safe Calls to Windows Forms Controls" + href: how-to-make-thread-safe-calls-to-windows-forms-controls.md + - name: "How to: Use a Background Thread to Search for Files" + href: how-to-use-a-background-thread-to-search-for-files.md + - name: Windows Forms Controls in the .NET Framework by Function + href: windows-forms-controls-by-function.md + - name: Develop Controls at Design Time + items: + - name: Overview + href: developing-windows-forms-controls-at-design-time.md + - name: "Walkthrough: Author a Composite Control" + href: walkthrough-authoring-a-composite-control-with-visual-csharp.md + - name: "Walkthrough: Inherit from a Control" + href: walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md + - name: "Walkthrough: Perform Common Tasks Using Design Actions" + href: perform-common-tasks-design-actions.md + - name: "Walkthrough: Serialize Collections of Standard Types" + href: serializing-collections-designerserializationvisibilityattribute.md + - name: "Walkthrough: Debug Custom Controls" + href: walkthrough-debugging-custom-windows-forms-controls-at-design-time.md + - name: "Walkthrough: Create a Control That Takes Advantage of Design-Time Features" + href: creating-a-wf-control-design-time-features.md + - name: "How to: Author Controls" + href: how-to-author-controls-for-windows-forms.md + - name: "How to: Author Composite Controls" + href: how-to-author-composite-controls.md + - name: "How to: Inherit from the UserControl Class" + href: how-to-inherit-from-the-usercontrol-class.md + - name: "How to: Inherit from Existing Controls" + href: how-to-inherit-from-existing-windows-forms-controls.md + - name: "How to: Inherit from the Control Class" + href: how-to-inherit-from-the-control-class.md + - name: "How to: Align a Control to the Edges of Forms" + href: how-to-align-a-control-to-the-edges-of-forms-at-design-time.md + - name: "How to: Display a Control in Choose Toolbox Items" + href: how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md + - name: "How to: Provide a Toolbox Bitmap for a Control" + href: how-to-provide-a-toolbox-bitmap-for-a-control.md + - name: "How to: Test the Run-Time Behavior of a UserControl" + href: how-to-test-the-run-time-behavior-of-a-usercontrol.md + - name: Design-Time Errors in the Windows Forms Designer + href: design-time-errors-in-the-windows-forms-designer.md + - name: Troubleshoot Control and Component Authoring + href: troubleshooting-control-and-component-authoring.md diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolbar-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/toolbar-control-overview-windows-forms.md new file mode 100644 index 0000000000..f0746485bc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolbar-control-overview-windows-forms.md @@ -0,0 +1,33 @@ +--- +title: "ToolBar Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ToolBar" +helpviewer_keywords: + - "toolbars [Windows Forms], about toolbars" + - "ToolBar control [Windows Forms], about ToolBar controls" +ms.assetid: d426b203-0216-4dbe-b834-1641e50a9c29 +--- +# ToolBar Control Overview (Windows Forms) +> [!NOTE] +> The control replaces and adds functionality to the control; however, the control is retained for both backward compatibility and future use, if you choose. + + The Windows Forms control is used on forms as a control bar that displays a row of drop-down menus and bitmapped buttons that activate commands. Thus, clicking a toolbar button can be an equivalent to choosing a menu command. The buttons can be configured to appear and behave as pushbuttons, drop-down menus, or separators. Typically, a toolbar contains buttons and menus that correspond to items in an application's menu structure, providing quick access to an application's most frequently used functions and commands. + +## Working with the ToolBar Control + A control is usually "docked" along the top of its parent window, but it can also be docked to any side of the window. A toolbar can display tooltips when the user points the mouse pointer at a toolbar button. A ToolTip is a small pop-up window that briefly describes the button or menu's purpose. To display ToolTips, the property must be set to `true`. + +> [!NOTE] +> Certain applications feature controls very similar to the toolbar that have the ability to "float" above the application window and be repositioned. The Windows Forms ToolBar control is not able to do these actions. + + When the property is set to , the toolbar buttons appear raised and three-dimensional. You can set the property of the toolbar to to give the toolbar and its buttons a flat appearance. When the mouse pointer moves over a flat button, the button's appearance changes to three-dimensional. Toolbar buttons can be divided into logical groups by using separators. A separator is a toolbar button with the property set to . It appears as empty space on the toolbar. When the toolbar has a flat appearance, button separators appear as lines rather than spaces between the buttons. + + The control allows you to create toolbars by adding objects to a collection. You can use the Collection Editor to add buttons to a control; each object should have text or an image assigned, although you can assign both. The image is supplied by an associated [ImageList](imagelist-component-windows-forms.md) component. At run time, you can add or remove buttons from the using the and methods. To program the buttons of a , add code to the events of the , using the property of the class to determine which button was clicked. + +## See also + +- +- [ToolBar Control](toolbar-control-windows-forms.md) +- [How to: Add Buttons to a ToolBar Control](how-to-add-buttons-to-a-toolbar-control.md) +- [How to: Define an Icon for a ToolBar Button](how-to-define-an-icon-for-a-toolbar-button.md) +- [How to: Trigger Menu Events for Toolbar Buttons](how-to-trigger-menu-events-for-toolbar-buttons.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolbar-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/toolbar-control-windows-forms.md new file mode 100644 index 0000000000..ee59b13a36 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolbar-control-windows-forms.md @@ -0,0 +1,42 @@ +--- +title: "ToolBar Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolBar control [Windows Forms]" +ms.assetid: 6b40e9ce-6a7a-4784-bfc9-7f1d36b7462e +--- +# ToolBar Control (Windows Forms) +> [!NOTE] +> The control replaces and adds functionality to the `ToolBar` control; however, the `ToolBar` control is retained for both backward compatibility and future use, if you choose. + + The Windows Forms `ToolBar` control is used on forms as a control bar that displays a row of drop-down menus and bitmapped buttons that activate commands. Thus, clicking a toolbar button is equivalent to choosing a menu command. The buttons can be configured to appear and behave as push buttons, drop-down menus, or separators. Typically, a toolbar contains buttons and menus that correspond to items in an application's menu structure, providing quick access to an application's most frequently used functions and commands. + +> [!NOTE] +> The `ToolBar` control's property takes an instance of the class as a reference. Carefully consider the reference you pass when implementing this sort of button on toolbars in your application, as the property will accept any object that inherits from the class. + +## In This Section + [ToolBar Control Overview](toolbar-control-overview-windows-forms.md) + Introduces the general concepts of the `ToolBar` control, which allows you to design custom toolbars that your users can work with. + + [How to: Add Buttons to a ToolBar Control](how-to-add-buttons-to-a-toolbar-control.md) + Describes how to add buttons to a `ToolBar` control. + + [How to: Define an Icon for a ToolBar Button](how-to-define-an-icon-for-a-toolbar-button.md) + Describes how to display icons within a `ToolBar` control's buttons. + + [How to: Trigger Menu Events for Toolbar Buttons](how-to-trigger-menu-events-for-toolbar-buttons.md) + Gives directions on writing code to interpret which button the user clicks in a `ToolBar` control. + + Also see [How to: Define an Icon for a ToolBar Button Using the Designer](how-to-define-an-icon-for-a-toolbar-button-using-the-designer.md), [How to: Add Buttons to a ToolBar Control Using the Designer](how-to-add-buttons-to-a-toolbar-control-using-the-designer.md). + +## Reference + class + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [ToolStrip Control](toolstrip-control-windows-forms.md) + Describes toolbars that can host menus, controls, and user controls in Windows Forms applications. diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-architecture.md b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-architecture.md new file mode 100644 index 0000000000..43b2629313 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-architecture.md @@ -0,0 +1,424 @@ +--- +title: "ToolStrip Control Architecture" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], architecture" +ms.assetid: 71df2d18-862e-4701-9ff9-c1fe606f94f2 +--- +# ToolStrip Control Architecture + +The and classes provide a flexible, extensible system for displaying toolbar, status, and menu items. These classes are all contained in the namespace and they are all typically named with the "ToolStrip" prefix (such as ) or with the "Strip" suffix (such as ). + +## ToolStrip + +The following topics describe and the controls that derive from it. + + is the abstract base class for , , and . The following object model shows the inheritance hierarchy. + +![Diagram that shows the ToolStrip object model.](./media/toolstrip-control-architecture/toolstrip-object-model.gif) + +You can access all the items in a through the collection. You can access all the items in a through the collection. In a class derived from , you can also use the property to access only those items that are currently displayed. These are the items that are not currently in an overflow menu. + +The following items are specifically designed to work seamlessly with both and in all orientations. They are available by default at design time for the control: + +- + +- + +- + +- + +- + +- + +- + +### MenuStrip + + is the top-level container that supersedes . It also provides key handling and multiple document interface (MDI) features. Functionally, and work along with , although they are derived from . + +The following items are specifically designed to work seamlessly with both and in all orientations. They are available by default at design time for the control: + +- + +- + +- + +### StatusStrip + + replaces the control. Special features of include a custom table layout, support for the form's sizing and moving grips, and the `Spring` property, which allows a to fill available space automatically. + +The following items are specifically designed to work seamlessly with both and in all orientations. They are available by default at design time for the control: + +- + +- + +- + +- + +### ContextMenuStrip + + replaces . You can associate a with any control, and a right mouse click automatically displays the context menu (or shortcut menu). You can show a programmatically by using the method. supports cancelable and events to handle dynamic population and multiple-click scenarios. supports images, menu-item check state, text, access keys, shortcuts, and cascading menus. + +The following items are specifically designed to work seamlessly with both and in all orientations. They are available by default at design time for the control: + +- + +- + +- + +- + +### ToolStrip Generic Features + +The following topics describe features and behavior that are generic to the and derived controls. + +#### Painting + +You can do custom painting in controls in several ways. As with other Windows Forms controls, the and both have overridable `OnPaint` methods and `Paint` events. As with regular painting, the coordinate system is relative to the client area of the control; that is, the upper left-hand corner of the control is 0, 0. The `Paint` event and `OnPaint` method for a behave like other control paint events. + +The controls also provide finer access to the rendering of the items and container through the class, which has overridable methods for painting the background, item background, item image, item arrow, item text, and border of the . The event arguments for these methods expose several properties such as rectangles, colors, and text formats that you can adjust as desired. + +To adjust just a few aspects of how an item is painted, you typically override the . + +If you are writing a new item and want to control all aspects of the painting, override the `OnPaint` method. From within `OnPaint`, you can use methods from the . + +By default, the is double buffered, taking advantage of the setting. + +#### Parenting + +The concept of container ownership and parenting is more complex in controls than in other Windows Forms container controls. That is necessary to support dynamic scenarios such as overflow, sharing drop-down items across multiple items, and to support the generation of a from a control. + +The following list describes members related to parenting and explains their use. + +- accesses the item that is the source of the drop-down item. This is similar to , but instead of returning a control, it returns a . + +- determines which control is the source of the when multiple controls share the same . + +- is a read-only accessor to the property. A parent differs from an owner in that a parent denotes the returned current in which the item is displayed, which might be in the overflow area. + +- returns the whose Items collection contains the current . This is the best way to reference or other properties in the top-level without writing special code to handle overflow. + +#### Behavior of Inherited Controls + +The following controls are locked whenever they are used in inheritance: + +- + +- + +- + +- + +- that includes the panels in a and also individual controls. + +For example, create a new Windows Forms application by using one or more of the controls in the previous list. Set the access modifier of one or more controls to `public` or `protected`, and then build the project. Add a form that inherits from the first form, and then select an inherited control. The control appears locked, behaving as if its access modifier was `private`. + +#### ToolStripContainer Support of Inheritance + +The control supports limited inherited scenarios, similar to the following example: + +1. Create a new Windows Forms application. + +2. Add a to the form. + +3. Set the access modifier of the to `public` or `protected`. + +4. Add any combination of , , and controls to the regions of the . + +5. Build the project. + +6. Add a form that inherits from the first form. + +7. Select the inherited on the form. + +#### Inherited Behavior of Child Controls + +After you complete the previous steps, the following inherited behavior occurs: + +- In the designer, the control appears with an inherited icon. + +- The controls are locked; you cannot select or rearrange their contents. + +- You can add controls to the , move the controls, and make them child controls of the . + +- Your changes persist after building the form. + + > [!NOTE] + > Remove the access modifiers from all controls that are part of a . The access modifier of the governs the whole control. + +#### Partial Trust + +The limitations of `ToolStrip`s under partial trust are designed to prevent inadvertent entry of personal information that might be used by unauthorized persons or services. The protective measures are as follows: + +- `ToolStripDropDown` controls require to display items in a . This applies to both intrinsic controls such as , , and as well as to user-created controls. If this requirement is not met, these items are not displayed. No exception is thrown. + +- Setting the property to `false` is not allowed, and the cancelable event parameter is ignored. This makes it impossible to enter more than one keystroke without dismissing the drop-down item. If this requirement is not met, such items are not displayed. No exception is thrown. + +- Many keystroke handling events will not be raised if they occur in partial trust contexts other than . + +- Access keys are not processed when is not granted. + +#### Usage + +The following usage patterns have a bearing on layout, keyboard interaction, and end-user behavior: + +- Joined in a + + The can be repositioned within the and across s. The `Dock` property is ignored, and if the property is `false`, the size of the grows as items are added to the . Typically, the does not participate in the tab order. + +- Docked + + The is placed on one side of a container in a fixed position, and its size expands over the entire edge to which it is docked. Typically, the does not participate in the tab order. + +- Absolutely positioned + + The is like other controls, in that it is placed by the property, has a fixed size, and typically participates in the tab order. + +#### Keyboard Interaction + +##### Access Keys + +Combined with or following the ALT key, access keys are one way to activate a control using the keyboard. supports both explicit and implicit access keys. Explicit definition uses an ampersand (&) character preceding the letter. Implicit definition uses an algorithm that attempts to find a matching item based on the order of characters in a given `Text` property. + +##### Shortcut Keys + +The shortcut keys used by a use a combination of the enumeration (which is not order-specific) to define the shortcut key. You can also use the property to display a shortcut key with text only, such as displaying "Del" instead of "Delete." + +##### Navigation + +The ALT key activates the pointed to by . From there, CTRL+TAB navigates between controls within `ToolStripPanel`s. The TAB key and the arrow keys on the numeric keypad navigate between items in a . A special algorithm handles navigation in the overflow region. SPACEBAR selects a , , or . + +##### Focus and Validation + +When activated by the ALT key, the or typically neither take nor remove the focus from the control that currently has the focus. If there is a control hosted within the or a drop-down of the , the control gains focus when the user presses the TAB key. In general, the , , , and events of might not be raised when they are activated by the keyboard. In such cases, use the and events instead. + +By default, is `false`. Call explicitly on your form to perform validation. + +#### Layout + +You control layout by choosing one of the members of with the property. + +##### Stack Layouts + +Stacking is the arranging of items beside each other at both ends of the . The following list describes the stack layouts. + +- is the default. This setting causes the to alter its layout automatically in accordance with the property to handle dragging and docking scenarios. + +- renders the items beside each other vertically. + +- renders the items beside each other horizontally. + +##### Other Features of Stack Layouts + + determines the end of the to which the item is aligned. + +When items do not fit within the , an overflow button automatically appears. The property setting determines whether an item appears in the overflow area always, as needed, or never. + +In the event, you can inspect the property to determine whether an item was placed on the main , the overflow , or if it is not currently showing at all. The typical reasons why an item is not displayed are that the item did not fit on the main and its property was set to . + +Make a movable by putting it in a and setting its to . + +##### Other Layout Options + +The other layout options are and . + +##### Flow Layout + + layout is the default for , , and . It is similar to the . The features of layout are as follows: + +- All of the features of are exposed by the property. You must cast the class to a class. + +- You can use the and properties in code to align the items within the row. + +- The property is ignored. + +- In the event, you can inspect the property to determine whether an item was placed on the main or did not fit. + +- The grip is not rendered, and therefore a in layout style in a cannot be moved. + +- The overflow button is not rendered, and is ignored. + +##### Table Layout + + layout is the default for . It is similar to . The features of layout are as follows: + +- All of the features of are exposed by the property. You must cast the class to a class. + +- You can use the and properties in code to align the items within the table cell. + +- The property is ignored. + +- In the event, you can inspect the property to determine whether an item was placed on the main or did not fit. + +- The grip is not rendered, and therefore a in layout style in a cannot be moved. + +- The overflow button is not rendered, and is ignored. + +## ToolStripItem + +The following topics describe and the controls that derive from it. + + is the abstract base class for all the items that go into a . The following object model shows the inheritance hierarchy. + +![Diagram that shows the ToolStripItem object model.](./media/toolstrip-control-architecture/toolstripitem-object-model.gif) + + classes either inherit directly from , or they inherit indirectly from through or . + + controls must be contained in a , , , or and cannot be added directly to a form. The various container classes are designed to contain an appropriate subset of controls. + +The following table lists the stock controls and the containers in which they look best. Although any item can be hosted in any -derived container, these items were designed to look best in the following containers: + +> [!NOTE] +> does not appear in the designer toolbox. + +|Contained item|ToolStrip|MenuStrip|ContextMenuStrip|StatusStrip|ToolStripDropDown| +|--------------------|---------------|---------------|----------------------|-----------------|-----------------------| +||Yes|No|No|No|Yes| +||Yes|Yes|Yes|No|Yes| +||Yes|No|No|Yes|Yes| +||Yes|No|No|Yes|Yes| +||Yes|Yes|Yes|No|Yes| +||Yes|No|No|Yes|Yes| +||Yes|Yes|Yes|No|Yes| +||No|Yes|Yes|No|No| +||No|No|No|Yes|No| +||Yes|No|No|Yes|No| +||Yes|Yes|No|Yes|Yes| + +### ToolStripButton + + is the button item for . You can display it with various border styles, and you can use it to represent and activate operational states. You can also define it to have the focus by default. + +### ToolStripLabel + +The provides label functionality in controls. The is like a that does not get focus by default and that does not render as pushed or highlighted. + + as a hosted item supports access keys. + +Use the , , and properties on a to support link control in a . + +### ToolStripStatusLabel + + is a version of designed specifically for use in . The special features include , , and . + +### ToolStripSeparator + +The adds a vertical or horizontal line to a toolbar or menu, depending on the orientation. It provides grouping of or distinction between items, such as those on a menu. + +You can add a at design time by choosing it from a drop-down list. However, you can also automatically create a by typing a hyphen (-) in either the designer template node or in the method. + +### ToolStripControlHost + + is the abstract base class for , , and . can host other controls, including custom controls, in two ways: + +- Construct a with a class that derives from . To fully access the hosted control and properties, you must cast the property back to the actual class it represents. + +- Extend , and in the inherited class's parameterless constructor, call the base class constructor passing a class that derives from . This option lets you wrap common control methods and properties for easy access in a . + +### ToolStripComboBox + + is the optimized for hosting in a . A subset of the hosted control's properties and events are exposed at the level, but the underlying control is fully accessible through the property. + +### ToolStripTextBox + + is the optimized for hosting in a . A subset of the hosted control's properties and events are exposed at the level, but the underlying control is fully accessible through the property. + +### ToolStripProgressBar + + is the optimized for hosting in a . A subset of the hosted control's properties and events are exposed at the level, but the underlying control is fully accessible through the property. + +### ToolStripDropDownItem + + is the abstract base class for , , and , which can host items directly or host additional items in a drop-down container. You do this by setting the property to a and setting the property of the . Access these drop-down items directly through the property. + +### ToolStripMenuItem + + is a that works with and to handle the special highlighting, layout, and column arrangement for menus. + +### ToolStripDropDownButton + + looks like , but it shows a drop-down area when the user clicks it. Hide or show the drop-down arrow by setting the property. hosts a that displays items that overflow the . + +### ToolStripSplitButton + + combines button and drop-down button functionality. + +Use the property to synchronize the event of the chosen drop-down item with the item shown on the button. + +### ToolStripItem Generic Features + + provides the following generic features and options to inheriting controls: + +- Core events + +- Image handling + +- Alignment + +- Text and image relationship + +- Display style + +#### Core Events + + controls receive their own click, mouse, and paint events, and can perform some keyboard preprocessing also. + +#### Image Handling + +The , , , , and properties pertain to various aspects of image handling. Use images in controls by setting these properties directly or by setting the run-time–only property. + +Image scaling is determined by the interaction of properties in both and , as follows: + +- is the scale of the final image as determined by the combination of the image's setting and the container's setting. + + - If is `true` (the default) and is , no image scaling occurs, and the size is that of the largest item, or a prescribed minimum size. + + - If is `false` and is , neither image nor scaling occurs. + +#### Alignment + +The value of the property determines the end of the at which an item appears. The property works only when the layout style of the is set to one of the stack overflow values. + +Items are placed on the in the order in which the items appear in the Items collection. To programmatically change where an item is laid out, use the method to move the item in the collection. This method moves the item but does not duplicate it. + +#### Text and Image Relationship + +The property defines the relative placement of the image with respect to the text on a . Items that lack an image, text, or both are treated as special cases so that the does not display a blank spot for the missing element or elements. + +#### Display Style + + allows you to set the values of an item's Text and Image properties while displaying only what you want. This is typically used to change only the display style when showing the same item in a different context. + +## Accessory Classes + +Classes that provide various other functionality include: + +- supports -related tasks for entire applications, such as merging, settings, and renderer options. + +- allows you to apply a particular style or theme to a easily. + +- creates pens and brushes based on a replaceable color table (). + +- applies system colors and a flat visual style to applications. + +- is similar to . It uses four docked side panels (instances of ) and one central panel (an instance of ) to create a typical arrangement. You cannot remove the side panels, but you can hide them. You can neither remove nor hide the central panel. You can arrange one or more , , or controls in the side panels, and you can use the central panel for other controls. The also provides a way to get renderer support into the body of your form for a consistent appearance. does not support multiple document interface (MDI). + +- provides space for moving and arranging controls. You can use only one panel if you so choose, and works well in MDI scenarios. + +## See also + +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Technology Summary](toolstrip-technology-summary.md) +- [ToolStrip Control](toolstrip-control-windows-forms.md) +- [MenuStrip Control](menustrip-control-windows-forms.md) +- [StatusStrip Control](statusstrip-control.md) +- [ContextMenuStrip Control](contextmenustrip-control.md) +- [BindingNavigator Control](bindingnavigator-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-overview-windows-forms.md new file mode 100644 index 0000000000..bc5fcb28ce --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-overview-windows-forms.md @@ -0,0 +1,83 @@ +--- +title: "ToolStrip Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "Toolstrip" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], about ToolStrip control" + - "toolbars [Windows Forms], what's new in Windows Forms" + - "toolbars [Windows Forms]" + - "what's new [Windows Forms], toolbars" +ms.assetid: 81d067ed-297c-4dad-90de-1bcac15336ec +--- +# ToolStrip Control Overview (Windows Forms) +The Windows Forms control and its associated classes provide a common framework for combining user interface elements into toolbars, status bars, and menus. controls offer a rich design-time experience that includes in-place activation and editing, custom layout, and rafting, which is the ability of toolbars to share horizontal or vertical space. + + Although replaces and adds functionality to the control in previous versions, is retained for both backward compatibility and future use if desired. + +## Features of the ToolStrip Controls + Use the control to: + +- Present a common user interface across containers. + +- Create easily customized, commonly employed toolbars that support advanced user interface and layout features, such as docking, rafting, buttons with text and images, drop-down buttons and controls, overflow buttons, and run-time reordering of items. + +- Support overflow and run-time item reordering. The overflow feature moves items to a drop-down menu when there is not enough room to display them in a . + +- Support the typical appearance and behavior of the operating system through a common rendering model. + +- Handle events consistently for all containers and contained items, in the same way you handle events for other controls. + +- Drag items from one to another or within a . + +- Create drop-down controls and user interface type editors with advanced layouts in a . + + Use the class to use other controls on a and gain functionality for them. + + You can extend the functionality and modify the appearance and behavior by using the , , and along with the and enumerations. + + The control is highly configurable and extensible, and it provides many properties, methods, and events to customize appearance and behavior. Below are some noteworthy members: + +### Important ToolStrip Members + +|Name|Description| +|----------|-----------------| +||Gets or sets which edge of the parent container a is docked to.| +||Gets or sets a value indicating whether drag-and-drop and item reordering are handled privately by the class.| +||Gets or sets a value indicating how the lays out its items.| +||Gets or sets whether a is attached to the or or can float between the two.| +||Gets a value indicating whether a displays other items in a drop-down list when the is clicked.| +||Gets the that is the overflow button for a with overflow enabled.| +||Gets or sets a used to customize the appearance and behavior (look and feel) of a .| +||Gets or sets the painting styles to be applied to the .| +||Raised when the property changes.| + + The control's flexibility is achieved through the use of a number of companion classes. Below are some of the most noteworthy: + +### Important ToolStrip Companion Classes + +|Name|Description| +|----------|-----------------| +||Replaces and adds functionality to the class.| +||Replaces and adds functionality to the class.| +||Replaces and adds functionality to the class.| +||Abstract base class that manages events and layout for all the elements that a , , or can contain.| +||Provides a container with a panel on each side of the form in which controls can be arranged in various ways.| +||Handles the painting functionality for objects.| +||Provides Microsoft Office-style appearance.| +||Controls rendering and rafting, and the merging of , , and objects.| +||Specifies the painting style (custom, Windows XP, or Microsoft Office Professional) applied to multiple objects contained in a form.| +||Specifies the painting style (custom, Windows XP, or Microsoft Office Professional) applied to one object contained in a form.| +||Hosts other controls that are not specifically controls but for which you want functionality.| +||Specifies whether a is to be laid out on the main , on the overflow , or neither.| + + For more information, see [ToolStrip Technology Summary](toolstrip-technology-summary.md) and [ToolStrip Control Architecture](toolstrip-control-architecture.md). + +## See also + +- +- +- +- +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-windows-forms.md new file mode 100644 index 0000000000..1c0588b4dd --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-control-windows-forms.md @@ -0,0 +1,90 @@ +--- +title: "ToolStrip Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStrip control [Windows Forms]" +ms.assetid: e5ef455a-e049-429c-8005-30c93132fb79 +--- +# ToolStrip Control (Windows Forms) + controls are toolbars that can host menus, controls, and user controls in your Windows Forms applications. + +## In This Section + [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [How to: Manage ToolStrip Overflow](how-to-manage-toolstrip-overflow-in-windows-forms.md) + Demonstrates how to enable overflow functionality and control overflow behavior. + + [How to: Enable Reordering of ToolStrip Items at Run Time](how-to-enable-reordering-of-toolstrip-items-at-run-time-in-windows-forms.md) + Demonstrates how to enable run-time rearrangement of controls. + + [How to: Enable AutoComplete in ToolStrip Controls](how-to-enable-autocomplete-in-toolstrip-controls-in-windows-forms.md) + Demonstrates automatic completion functionality in a . + + [How to: Change the Spacing and Alignment of ToolStrip Items in Windows Forms](how-to-change-the-spacing-and-alignment-of-toolstrip-items-in-windows-forms.md) + Describes various ways to arrange s on the . + + [How to: Change the Appearance of ToolStrip Text and Images in Windows Forms](how-to-change-the-appearance-of-toolstrip-text-and-images-in-windows-forms.md) + Describes how to define and modify the arrangement of text and images on controls. + + [How to: Wrap a Windows Forms Control with ToolStripControlHost](how-to-wrap-a-windows-forms-control-with-toolstripcontrolhost.md) + Demonstrates hosting a control in a . + + [How to: Create and Set a Custom Renderer for the ToolStrip Control in Windows Forms](create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md) + Describes how to achieve standard and customized painting in controls. + + [How to: Custom Draw a ToolStrip Control](how-to-custom-draw-a-toolstrip-control.md) + Describes various aspects of custom (owner) drawing in controls. + + [How to: Create Toggle Buttons in ToolStrip Controls](how-to-create-toggle-buttons-in-toolstrip-controls.md) + Describes the creation of a toggling . + + [How to: Use ToolTips in ToolStrip Controls](how-to-use-tooltips-in-toolstrip-controls.md) + Describes defining tool tips for items. + + [How to: Move a ToolStrip Out of a ToolStripContainer onto a Form](how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md) + Describes how to have a with no container but a form. + + [How to: Position a ToolStripItem on a ToolStrip](how-to-position-a-toolstripitem-on-a-toolstrip.md) + Describes how to position a on at the leftmost or rightmost end of a . + + [How to: Enable the TAB Key to Move Out of a ToolStrip Control](how-to-enable-the-tab-key-to-move-out-of-a-toolstrip-control.md) + Describes how to tab within a and tab out of it to the next control in the tab order. + + [How to: Detect When the Mouse Pointer Is Over a ToolStripItem](how-to-detect-when-the-mouse-pointer-is-over-a-toolstripitem.md) + Describes how to set up items so that they detect when the mouse is over them without having to synchronize various mouse events. + + [How to: Create an MDI Form with ToolStripPanel Controls](how-to-create-an-mdi-form-with-toolstrippanel-controls.md) + Describes how to create a multiple document interface (MDI) form with controls. + + [How to: Create an MDI Form with Menu Merging and ToolStrip Controls](how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md) + Describes how to create an MDI form that supports controls and menu merging. + + [How to: Create a Professionally Styled ToolStrip Control](how-to-create-a-professionally-styled-toolstrip-control.md) + Describes how to use the class to create a composite control that mimics the **Navigation Pane** provided by Microsoft® Outlook®. + + [How to: Implement a Custom ToolStripRenderer](how-to-implement-a-custom-toolstriprenderer.md) + Describes how to customize the appearance of a control by implementing a class that derives from . + +- [How to: Create a Basic Windows Forms ToolStrip with Standard Items Using the Designer](create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md) + +- [How to: Move a ToolStrip Out of a ToolStripContainer onto a Form](how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md) + +- [Walkthrough: Creating a Professionally Styled ToolStrip Control](walkthrough-creating-a-professionally-styled-toolstrip-control.md) + +- [Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls](walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md) + +## Reference + class + Describes this class and has links to all its members. + + + Describes the class and has links to all its members. + + + Describes the class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstrip-technology-summary.md b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-technology-summary.md new file mode 100644 index 0000000000..fd5924426f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstrip-technology-summary.md @@ -0,0 +1,118 @@ +--- +title: "ToolStrip Technology Summary" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], technology summary" + - "status bars [Windows Forms], technology summary" + - "toolbars [Windows Forms], technology summary" + - "menus [Windows Forms], technology summary" +ms.assetid: e8d61973-7af9-429f-9df5-05a899c15a7b +--- +# ToolStrip Technology Summary +This topic summarizes information about the `ToolStrip` control and the classes that support its use. + + The `ToolStrip` control and its associated classes provide a complete solution for creating toolbars, status bars, and menus. + +## Namespaces + + +## Background + With the `ToolStrip` control and its associated classes, you can create advanced toolbar functionality that has consistent and professional appearance and behavior. The `ToolStrip` control and classes offer the following improvements over previous controls: + +- A more consistent event model. + +- A more consistent design-time behavior that contains task lists and item collection editors. + +- Custom rendering with `ToolStripManager` and `ToolStripRenderer`. + +- Built-in rafting (sharing of horizontal or vertical space within the tool area when docked) with the `ToolStripContainer` and `ToolStripPanel`. + +- Design-time and run-time reordering of items with the property. + +- Relocation of items to an overflow menu with the property. + +- Completely configurable control location with the `ToolStripContainer`, `ToolStripPanel`, and `ToolStripContentPanel`. + +- Hosting of `ToolStrip`, traditional, or custom controls using `ToolStripControlHost`. + +- Merging of `ToolStrip` controls using `ToolStripPanel`. + + `ToolStrip` is the extensible base class for `MenuStrip`, `ContextMenuStrip`, and `StatusStrip`. These controls are containers that inherit common behavior and event handling, extended so that each implementation deals with the behavior that is appropriate for it. Controls that derive from are listed in the following table. The base `ToolStrip` class handles painting, user input, and drag-and-drop events for these controls. + + The `ToolStrip`, `MenuStrip`, `ContextMenuStrip`, and `StatusStrip` controls replace the previous toolbar, menu, shortcut menu, and status bar controls, although those controls are retained for backward compatibility. + +## ToolStrip Classes at a Glance + The following table shows the ToolStrip classes grouped by technology area. + +|Technology area|Class| +|---------------------|-----------| +|Toolbar, Status, and Menu containers|







| +|ToolStrip items|





















| +|Location|



| +|Presentation and rendering|







| + +## ToolStrip Design-Time Features + The family of controls provides a rich set of tools and templates for in-place editing and defining the foundation of the user interface so that you can quickly create a working application. + +### Task Dialog Boxes + In Visual Studio, clicking the smart tag on a control in the designer displays a task list for convenient access to many frequently used commands. + +- [MenuStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233645(v=vs.100)) + +- [ToolStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233648(v=vs.100)) + +- [ContextMenuStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233646(v=vs.100)) + +- [StatusStrip Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233642(v=vs.100)) + +- [ToolStripContainer Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233647(v=vs.100)) + +### Items Collection Editors + In Visual Studio, when you click **Edit Items** on the task list or right-click the control and select **Edit Items** in the shortcut menu, the collection editor for the control is displayed. Collection editors let you add, remove, and reorder items that the control contains. You can also view and change the properties for the control and the control's items. + +- [MenuStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233625(v=vs.100)) + +- [StatusStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233631(v=vs.100)) + +- [ContextMenuStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233641(v=vs.100)) + +- [ToolStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233643(v=vs.100)) + +## Hosting Controls + The class provides built-in wrappers for , , and controls. You can also host any other existing or COM control in a . + + For an example of control hosting, see [How to: Wrap a Windows Forms Control with ToolStripControlHost](how-to-wrap-a-windows-forms-control-with-toolstripcontrolhost.md). + +## Rendering + classes implement a rendering scheme that is significantly different from other Windows Forms controls. With this scheme, you can easily apply styles and themes. + + To apply a style to a and all the objects it contains, you do not have to handle the event for each item. Instead, you can set the property to one of the values other than . Alternatively, you can set the directly to any class that inherits from the class. Setting this property automatically sets the . + + You can apply the same style to multiple objects in the same application by setting the to and setting the or property to that you want or value, respectively. + + For examples of rendering, see [How to: Create and Set a Custom Renderer for the ToolStrip Control in Windows Forms](create-and-set-a-custom-renderer-for-the-toolstrip-control-in-wf.md). + +## Styles and Themes + and associated classes provide an easy way to support visual styles and custom appearance that do not require overriding the methods for each item. Use the and the and properties. + +## Rafting and Docking + You can raft, dock, or absolutely position controls. items are laid out by the of the container. + + *Rafting* is the ability of toolbars to share horizontal or vertical space. A Windows form can have a that in turn has panels on the form's left, right, top, and bottom sides for positioning and rafting , , and controls. Multiple controls stack vertically if you put them in the left or right . They stack horizontally if you put them in the top or bottom . You can use the central of the to position traditional controls on the form. + + Any or all controls are directly selectable at design time and can be deleted. A is expandable and collapsible, and resizes with the controls that it contains. + + *Docking* is the specifying of a control's simple location on the form's left, right, top, or bottom side. + + The advantage of rafting over docking is that , , and controls can share horizontal or vertical space with other controls. + + Most of the controls can be docked to the form like other controls instead of using rafting. You can also specify that a control be freely positioned on the form by removing it from its and setting its `Dock` property to `None`, or you can specify its absolute position by setting the respective property. See [How to: Move a ToolStrip Out of a ToolStripContainer onto a Form](how-to-move-a-toolstrip-out-of-a-toolstripcontainer-onto-a-form.md). + + Use one or more controls for more flexibility, especially for Multiple Document Interface (MDI) applications, or if you do not need a . A provides a dockable space for locating and rafting controls but not traditional controls. By default, the does not appear in the designer **Toolbox**, but you can put it there by right-clicking the **Toolbox**, and then click **Choose Items**. You can also programmatically access the like any other class. + + The , , and let items overflow. This is similar to the way these items behave on Microsoft Office toolbars. + +## See also + +- [ToolStrip Control Overview](toolstrip-control-overview-windows-forms.md) +- [ToolStrip Control Architecture](toolstrip-control-architecture.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstripcontainer-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/toolstripcontainer-control-overview.md new file mode 100644 index 0000000000..94286cfa8d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstripcontainer-control-overview.md @@ -0,0 +1,32 @@ +--- +title: "ToolStripContainer Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ToolStripContainer" +helpviewer_keywords: + - "toolbars [Windows Forms], built-in rafting" + - "ToolStripContainer control [Windows Forms], about ToolStripContainer control" +ms.assetid: c7d63bff-64e2-4a63-bd89-d31bc96dacb8 +--- +# ToolStripContainer Control Overview +A has panels on its left, right, top, and bottom sides for positioning and rafting , , and controls. Multiple controls stack vertically if you put them in the left or right . They stack horizontally if you put them in the top or bottom . You can use the central of the to position traditional controls on the form. + + Any or all controls are directly selectable at design time and can be deleted. Each panel of a is expandable and collapsible, and resizes with the controls that it contains. + +### Important ToolStripContainer Members + +|Name|Description| +|----------|-----------------| +||Gets the bottom panel of the .| +||Gets or sets a value indicating whether the bottom panel of the is visible.| +||Gets the left panel of the .| +||Gets or sets a value indicating whether the left panel of the is visible.| +||Gets the right panel of the .| +||Gets or sets a value indicating whether the right panel of the is visible.| +||Gets the top panel of the .| +||Gets or sets a value indicating whether the top panel of the is visible.| + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstripcontainer-control.md b/dotnet-desktop-guide/framework/winforms/controls/toolstripcontainer-control.md new file mode 100644 index 0000000000..b7adbde686 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstripcontainer-control.md @@ -0,0 +1,40 @@ +--- +title: "ToolStripContainer Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "toolbars [Windows Forms], built-in rafting" + - "ToolStripContainer control [Windows Forms]" + - "ToolStrip control [Windows Forms], ToolStripContainer" +ms.assetid: 378fa5b4-38e1-46f4-8e5c-d0c19dcd0200 +--- +# ToolStripContainer Control + controls feature built-in rafting (sharing of horizontal or vertical space within the tool area when docked) by using the . + + The topics in this section describe the concepts and techniques that you can use to build features into your applications. + +## In This Section + [ToolStripContainer Control Overview](toolstripcontainer-control-overview.md) + Provides topics that describe the purpose and main concepts of the Windows Forms control. + + [How to: Add a ToolStripContainer to a Form](how-to-add-a-toolstripcontainer-to-a-form.md) + Demonstrates adding a to an application and adding a control to a specific panel of the . + + [How to: Add a Control to a ToolStripContentPanel](how-to-add-a-control-to-a-toolstripcontentpanel.md) + Demonstrates adding a control to the . + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the of a control. + + Also see [ToolStripContainer Tasks Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233647(v=vs.100)). + +## Related Sections + + Provides reference documentation for the control. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstrippanel-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/toolstrippanel-control-overview.md new file mode 100644 index 0000000000..060ea0cdc7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstrippanel-control-overview.md @@ -0,0 +1,29 @@ +--- +title: "ToolStripPanel Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ToolStripPanel" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStripPanel control [Windows Forms], about ToolStripPanel control" +ms.assetid: ce54a60c-5eba-4b4c-bd77-cf0748a666cc +--- +# ToolStripPanel Control Overview +A provides a single area for positioning and rafting , , and controls. Multiple controls stack vertically or horizontally depending on the of the . + +### Important ToolStripPanel Members + +|Name|Description| +|----------|-----------------| +||Gets or sets a value indicating the horizontal or vertical orientation of the .| +||Gets or sets a used to customize the appearance of a .| +||Gets or sets the painting styles to be applied to the .| +||Gets or sets the spacing, in pixels, between the and the .| +||Gets the in this .| +||Adds a to a .| + +## See also + +- +- +- [ToolStrip Sample](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/ms181005(v=vs.90)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstrippanel-control.md b/dotnet-desktop-guide/framework/winforms/controls/toolstrippanel-control.md new file mode 100644 index 0000000000..381d749a43 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstrippanel-control.md @@ -0,0 +1,33 @@ +--- +title: "ToolStripPanel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStripPanel control [Windows Forms]" + - "horizontal space" + - "ToolStrip control [Windows Forms], ToolStripPanel" + - "tool area [Windows Forms]" + - "vertical space" +ms.assetid: aa47af39-1e71-40ee-bb75-2d2478f81bd0 +--- +# ToolStripPanel Control +`ToolStripPanel` control enables the sharing of horizontal or vertical space within the tool area when docked and arranging of controls when you do not need the four panels and central panel of a . + + The topics in this section describe the concepts and techniques that you can use to build `ToolStripPanel` features into your applications. + +## In This Section + [ToolStripPanel Control Overview](toolstrippanel-control-overview.md) + Provides topics that describe the purpose and main concepts of the Windows Forms control. + + [How to: Join ToolStripPanels](how-to-join-toolstrippanels.md) + Demonstrates adding controls to a `ToolStripPanel`. + + [How to: Use ToolStripPanels for MDI](how-to-use-toolstrippanels-for-mdi.md) + Demonstrates the flexibility afforded by `ToolStripPanel` controls in a Multiple Document Interface application. + +## Reference + + Provides reference documentation for the control. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstripprogressbar-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/toolstripprogressbar-control-overview.md new file mode 100644 index 0000000000..35e022452b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstripprogressbar-control-overview.md @@ -0,0 +1,30 @@ +--- +title: "ToolStripProgressBar Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ToolStripProgressBar" +helpviewer_keywords: + - "toolbars [Windows Forms], progress bars" + - "progress controls [Windows Forms]" + - "ToolStripProgressBar control [Windows Forms], about ToolStripProgressBar control" +ms.assetid: ec3ab522-5fe4-4b4d-a551-bc19e84f4774 +--- +# ToolStripProgressBar Control Overview +The combines the rafting and rendering functionality of all controls with its typical process-tracking functionality. A is most usually hosted by , and less frequently by a . + + Although replaces and adds functionality to the control in previous versions, is retained for both backward compatibility and future use if desired. + +### Important ToolStripProgressBar Members + +|Name|Description| +|----------|-----------------| +||Gets or sets a value representing the delay between each display update, in milliseconds.| +||Gets or sets the upper bound of the range that is defined for this .| +||Gets or sets the lower bound of the range that is defined for this .| +||Gets or sets the style that the uses to display the progress of an operation.| +||Gets or sets the current value of the .| +||Advances the current position of the progress bar by the amount of the property.| + +## See also + +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstripprogressbar-control.md b/dotnet-desktop-guide/framework/winforms/controls/toolstripprogressbar-control.md new file mode 100644 index 0000000000..5316c0217f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstripprogressbar-control.md @@ -0,0 +1,27 @@ +--- +title: "ToolStripProgressBar Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStrip control [Windows Forms], ToolStripProgressBar" + - "ToolStripProgressBar control [Windows Forms]" + - "toolbars [Windows Forms], progress bars" + - "progress controls [Windows Forms]" +ms.assetid: cb3eb0a8-60b1-483e-a03f-93b0b1351dae +--- +# ToolStripProgressBar Control +The combines rendering and rafting features with its typical process-tracking functionality. + +## In This Section + [ToolStripProgressBar Control Overview](toolstripprogressbar-control-overview.md) + Provides topics that describe the purpose and main concepts of the Windows Forms control. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the control. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstripstatuslabel-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/toolstripstatuslabel-control-overview.md new file mode 100644 index 0000000000..d71028e340 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstripstatuslabel-control-overview.md @@ -0,0 +1,24 @@ +--- +title: "ToolStripStatusLabel Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ToolStripStatusLabel" +helpviewer_keywords: + - "ToolStripStatusLabel control [Windows Forms], aboutToolStripStatusLabel control" + - "status bars" +ms.assetid: 0b9c991e-a9fa-4609-9e1b-caadaef93821 +--- +# ToolStripStatusLabel Control Overview +The is a label for a . Like the or , the provides a non-clickable display area for text, images, or both. The is hosted by a . + +### Important ToolStripStatusLabel Members + +|Name|Description| +|----------|-----------------| +||Gets or sets a value indicating whether the automatically fills the available space on the as the form is resized| +||Gets or sets a value that indicates which sides of the show borders.| +||Gets or sets the border style of the .| + +## See also + +- diff --git a/dotnet-desktop-guide/framework/winforms/controls/toolstripstatuslabel-control.md b/dotnet-desktop-guide/framework/winforms/controls/toolstripstatuslabel-control.md new file mode 100644 index 0000000000..e3803fe3f6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/toolstripstatuslabel-control.md @@ -0,0 +1,29 @@ +--- +title: "ToolStripStatusLabel Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "ToolStripStatusLabel control [Windows Forms]" + - "status bars" + - "ToolStrip control [Windows Forms], ToolStripStatusLabel" +ms.assetid: 099bc74a-a29f-4f15-af0d-7c517ef50c7e +--- +# ToolStripStatusLabel Control +The provides a display area in a for text, images, or both. + +## In This Section + [ToolStripStatusLabel Control Overview](toolstripstatuslabel-control-overview.md) + Provides topics that describe the purpose and main concepts of the Windows Forms control. + +## Reference + + Provides reference documentation for the control. + + + Provides reference documentation for the control. + + + Provides reference documentation for the control. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/tooltip-component-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/tooltip-component-overview-windows-forms.md new file mode 100644 index 0000000000..89c9d6f0e5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/tooltip-component-overview-windows-forms.md @@ -0,0 +1,23 @@ +--- +title: "ToolTip Component Overview" +ms.date: "03/30/2017" +f1_keywords: + - "ToolTip" +helpviewer_keywords: + - "tooltips [Windows Forms], about tooltips" + - "ToolTip component [Windows Forms], about ToolTip component" +ms.assetid: 3fbc6f08-c882-4acd-a960-a08efe3c7e6e +--- +# ToolTip Component Overview (Windows Forms) +The Windows Forms component displays text when the user points at controls. A ToolTip can be associated with any control. An example use of this component: to save space on a form, you can display a small icon on a button and use a ToolTip to explain the button's function. + +## Working with the ToolTip Component + A component provides a `ToolTip` property to multiple controls on a Windows Form or other container. For example, if you place one component on a form, you can display "Type your name here" for a control and "Click here to save changes" for a control. + + The key methods of the component are and . You can use the method to set the ToolTips displayed for controls. For more information, see [How to: Set ToolTips for Controls on a Windows Form at Design Time](how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md). The key properties are , which must be set to `true` for the ToolTip to appear, and , which sets the length of time that the ToolTip string is shown, how long the user must point at the control for the ToolTip to appear, and how long it takes for subsequent ToolTip windows to appear. For more information, see [How to: Change the Delay of the Windows Forms ToolTip Component](how-to-change-the-delay-of-the-windows-forms-tooltip-component.md). + +## See also + +- +- [How to: Set ToolTips for Controls on a Windows Form at Design Time](how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md) +- [How to: Change the Delay of the Windows Forms ToolTip Component](how-to-change-the-delay-of-the-windows-forms-tooltip-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/tooltip-component-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/tooltip-component-windows-forms.md new file mode 100644 index 0000000000..778e03deca --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/tooltip-component-windows-forms.md @@ -0,0 +1,31 @@ +--- +title: "ToolTip Component" +ms.date: "03/30/2017" +helpviewer_keywords: + - "tooltips [Windows Forms]" + - "ToolTip component [Windows Forms]" +ms.assetid: 82e71dc3-0159-4f91-9f22-499224f004a0 +--- +# ToolTip Component (Windows Forms) +The Windows Forms component displays text when the user points at controls. A ToolTip can be associated with any control. An example use of this control: In order to save space on a form, you can display a small icon on a button and use a ToolTip to explain the button's function. + +## In This Section + [ToolTip Component Overview](tooltip-component-overview-windows-forms.md) + Introduces the general concepts of the component, which allows users to see text when they point the mouse at a control. + + [How to: Set ToolTips for Controls on a Windows Form at Design Time](how-to-set-tooltips-for-controls-on-a-windows-form-at-design-time.md) + Describes how to set Tooltips in code or in the designer. + + [How to: Change the Delay of the Windows Forms ToolTip Component](how-to-change-the-delay-of-the-windows-forms-tooltip-component.md) + Explains how to set values that control how long a Tooltip takes to appear and the length of time for which it is shown. + +## Reference + class + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. + + [Control Help Using ToolTips](../advanced/control-help-using-tooltips.md) + Discusses Tooltips as a way to make brief, specialized Help messages for individual controls on Windows Forms. diff --git a/dotnet-desktop-guide/framework/winforms/controls/trackbar-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/trackbar-control-overview-windows-forms.md new file mode 100644 index 0000000000..c899cc7cce --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/trackbar-control-overview-windows-forms.md @@ -0,0 +1,23 @@ +--- +title: "TrackBar Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "TrackBar" +helpviewer_keywords: + - "sliders [Windows Forms], about sliders" + - "TrackBar control [Windows Forms], about TrackBar control" + - "slider controls [Windows Forms], about slider controls" +ms.assetid: 95910ecb-8a4c-4776-89fa-206c89ed6973 +--- +# TrackBar Control Overview (Windows Forms) +The Windows Forms control (also sometimes called a "slider" control) is used for navigating through a large amount of information or for visually adjusting a numeric setting. The control has two parts: the thumb, also known as a slider, and the tick marks. The thumb is the part that can be adjusted. Its position corresponds to the property. The tick marks are visual indicators that are spaced at regular intervals. The trackbar moves in increments that you specify and can be aligned horizontally or vertically. For example, you might use the track bar to control the cursor blink rate or mouse speed for a system. + +## Key Properties + The key properties of the control are , , , and . is the spacing of the ticks. and are the smallest and largest values that can be represented on the track bar. + + Two other important properties are and . The value of the property is the number of positions the thumb moves in response to having the LEFT or RIGHT ARROW key pressed. The value of the property is the number of positions the thumb moves in response to having the PAGE UP or PAGE DOWN key pressed, or in response to mouse clicks on the track bar on either side of the thumb. + +## See also + +- +- [TrackBar Control](trackbar-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/trackbar-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/trackbar-control-windows-forms.md new file mode 100644 index 0000000000..fd94014f8b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/trackbar-control-windows-forms.md @@ -0,0 +1,23 @@ +--- +title: "TrackBar Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "sliders" + - "slider controls [Windows Forms]" + - "TrackBar control [Windows Forms]" +ms.assetid: 37d6aee3-7e8a-4a10-a99c-3a6e09199553 +--- +# TrackBar Control (Windows Forms) +The Windows Forms `TrackBar` control (also sometimes called a "slider" control) is used for navigating through a large amount of information or for visually adjusting a numeric setting. The `TrackBar` control has two parts: the thumb, also known as a slider, and the tick marks. The thumb is the part that can be adjusted. Its position corresponds to the property. The tick marks are visual indicators that are spaced at regular intervals. The track bar moves in increments that you specify and can be aligned horizontally or vertically. An example use of a track bar would be for setting cursor blink rate or mouse speed. + +## In This Section + [TrackBar Control Overview](trackbar-control-overview-windows-forms.md) + Introduces the general concepts of the `TrackBar` control, which allows users to navigate through information by visually adjusting a numeric setting. + +## Reference + class + Provides reference information on the class and its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/treeview-control-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/treeview-control-overview-windows-forms.md new file mode 100644 index 0000000000..408b37fccf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/treeview-control-overview-windows-forms.md @@ -0,0 +1,26 @@ +--- +title: "TreeView Control Overview" +ms.date: "03/30/2017" +f1_keywords: + - "TreeView" +helpviewer_keywords: + - "TreeView control [Windows Forms], about TreeView control" +ms.assetid: 0ece823a-9508-478a-bbdb-7d7c3bae51d5 +--- +# TreeView Control Overview (Windows Forms) + +With the Windows Forms control, you can display a hierarchy of nodes to users, like the way files and folders are displayed in the left pane of the Windows Explorer feature of the Windows operating system. Each node in the tree view might contain other nodes, called *child nodes*. You can display parent nodes, or nodes that contain child nodes, as expanded or collapsed. You can also display a tree view with check boxes next to the nodes by setting the tree view's property to `true`. You can then programmatically select or clear nodes by setting the node's property to `true` or `false`. + +## Key Properties + +The key properties of the control are and . The property contains the list of top-level nodes in the tree view. The property sets the currently selected node. You can display icons next to the nodes. The control uses images from the named in the tree view's property. The property sets the default image for nodes in the tree view. For more information about displaying images, see [How to: Set Icons for the Windows Forms TreeView Control](how-to-set-icons-for-the-windows-forms-treeview-control.md). If you are using Visual Studio 2005, you have access to a large library of standard images that you can use with the control. + +## See also + +- +- [TreeView Control](treeview-control-windows-forms.md) +- [How to: Set Icons for the Windows Forms TreeView Control](how-to-set-icons-for-the-windows-forms-treeview-control.md) +- [How to: Add and Remove Nodes with the Windows Forms TreeView Control](how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md) +- [How to: Iterate Through All Nodes of a Windows Forms TreeView Control](how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md) +- [How to: Determine Which TreeView Node Was Clicked](how-to-determine-which-treeview-node-was-clicked-windows-forms.md) +- [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/treeview-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/treeview-control-windows-forms.md new file mode 100644 index 0000000000..4eec1a5a9f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/treeview-control-windows-forms.md @@ -0,0 +1,44 @@ +--- +title: "TreeView Control" +ms.date: "03/30/2017" +helpviewer_keywords: + - "checked list items [Windows Forms], Windows Forms controls" + - "list controls [Windows Forms], Windows Forms" + - "list items [Windows Forms], Windows Forms controls that display" + - "TreeView control [Windows Forms]" +ms.assetid: 879438b4-4eac-45c6-b345-0229c9b21ab0 +--- +# TreeView Control (Windows Forms) +The Windows Forms `TreeView` control displays a hierarchy of nodes, like the way files and folders are displayed in the left pane of the Windows Explorer feature in Windows operating systems. + +## In This Section + [TreeView Control Overview](treeview-control-overview-windows-forms.md) + Explains what the control is and its key features and properties. + + [How to: Add and Remove Nodes with the Windows Forms TreeView Control](how-to-add-and-remove-nodes-with-the-windows-forms-treeview-control.md) + Gives instructions for adding and remove nodes from a tree view. + + [How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)](add-custom-information-to-a-treeview-or-listview-control-wf.md) + Gives instructions for deriving an item in a list view or a node in a tree view to add any fields, methods, or constructors you need. + + [How to: Determine Which TreeView Node Was Clicked](how-to-determine-which-treeview-node-was-clicked-windows-forms.md) + Gives instructions for determining which node in a tree view was clicked, so the application can respond appropriately. + + [How to: Iterate Through All Nodes of a Windows Forms TreeView Control](how-to-iterate-through-all-nodes-of-a-windows-forms-treeview-control.md) + Gives instructions for examining every node in a tree view. + + [How to: Set Icons for the Windows Forms TreeView Control](how-to-set-icons-for-the-windows-forms-treeview-control.md) + Gives instructions for displaying icons for the nodes of a tree view. + + [How to: Attach a ShortCut Menu to a TreeView Node](how-to-attach-a-shortcut-menu-to-a-treeview-node.md) + Demonstrates how to add a shortcut menu to a tree view node. + +Also see [How to: Add and Remove Nodes with the Windows Forms TreeView Control Using the Designer](add-and-remove-nodes-with-wf-treeview-control-using-the-designer.md), and [How to: Attach a Shortcut Menu to a TreeNode Using the Designer](how-to-attach-a-shortcut-menu-to-a-treenode-using-the-designer.md). + +## Reference + class + Describes this class and has links to all its members. + +## Related Sections + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/controls/troubleshooting-control-and-component-authoring.md b/dotnet-desktop-guide/framework/winforms/controls/troubleshooting-control-and-component-authoring.md new file mode 100644 index 0000000000..fc7e3ffe5e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/troubleshooting-control-and-component-authoring.md @@ -0,0 +1,119 @@ +--- +title: "Troubleshooting Control and Component Authoring" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "troubleshooting components" + - "troubleshooting controls [Windows Forms]" + - "controls [Windows Forms], troubleshooting" + - "components [Windows Forms], troubleshooting" + - "Windows Forms controls, debugging" +ms.assetid: e9c8c099-2271-4737-882f-50f336c7a55e +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Troubleshoot Control and Component Authoring + +This topic lists the following common problems that arise when developing components and controls: + +- Cannot Add Control to Toolbox + +- Cannot Debug the Windows Forms User Control or Component + +- Event Is Raised Twice in Inherited Control or Component + +- Design-Time Error: "Failed to Create Component '*Component Name*'" + +- STAThreadAttribute + +- Component Icon Does Not Appear in Toolbox + +## Cannot Add Control to Toolbox + +If you want to add a custom control that you created in another project or a third-party control to the **Toolbox**, you must do so manually. If the current project contains your control or component, it should appear in the **Toolbox** automatically. For more information, see [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md). + +### To add a control to the Toolbox + +1. Right-click the **Toolbox** and from the shortcut menu, select **Choose Items**. + +2. In the **Choose Toolbox Items** dialog box, add the component: + + - If you want to add a .NET Framework component or control, click the **.NET Framework Components** tab. + + – or – + + - If you want to add a COM component or ActiveX control, click the **COM Components** tab. + +3. If your control is listed in the dialog box, confirm it is selected, and then click **OK**. + + The control is added to the **Toolbox**. + +4. If your control is not listed in the dialog box, do the following: + + 1. Click the **Browse** button. + + 2. Browse to the folder that contains the .dll file that contains your control. + + 3. Select the .dll file and click **Open**. + + Your control appears in the dialog box. + + 4. Confirm that your control is selected, and then click **OK**. + + Your control is added to the **Toolbox**. + +## Cannot Debug the Windows Forms User Control or Component + +If your control derives from the class, you can debug its run-time behavior with the test container. For more information, see [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md). + +Other custom controls and components are not stand-alone projects. They must be hosted by an application such as a Windows Forms project. To debug a control or component, you must add it to a Windows Forms project. + +### To debug a control or component + +1. From the **Build** menu, click **Build Solution** to build your solution. + +2. From the **File** menu, choose **Add**, and then **New Project** to add a test project to your application. + +3. In the **Add New Project** dialog box choose **Windows Application** for the type of project. + +4. In **Solution Explorer**, right-click the **References** node for the new project. On the shortcut menu, click **Add Reference** to add a reference to the project containing the control or component. + +5. Create an instance of your control or component in the test project. If your component is in the **Toolbox**, you can drag it to your designer surface, or you can create the instance programmatically, as shown in the following code example. + + ```vb + Dim Component1 As New MyNeatComponent() + ``` + + ```csharp + MyNeatComponent Component1 = new MyNeatComponent(); + ``` + + You can now debug your control or component as usual. + +For more information about debugging, see [Debugging in Visual Studio](/visualstudio/debugger/debugger-feature-tour) and [Walkthrough: Debugging Custom Windows Forms Controls at Design Time](walkthrough-debugging-custom-windows-forms-controls-at-design-time.md). + +## Event Is Raised Twice in Inherited Control or Component + +This is likely due to a duplicated `Handles` clause. For more information, see [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers). + +## Design-Time Error: "Failed to Create Component 'Component Name'" + +Your component or control must provide a parameterless constructor with no parameters. When the design environment creates an instance of your component or control, it does not attempt to provide any parameters to constructor overloads that take parameters. + +## STAThreadAttribute + +The informs the common language runtime (CLR) that Windows Forms uses the single-threaded apartment model. You may notice unintended behavior if you do not apply this attribute to your Windows Forms application's `Main` method. For example, background images may not appear for controls like . Some controls may also require this attribute for correct AutoComplete and drag-and-drop behavior. + +## Component Icon Does Not Appear in Toolbox + +When you use to associate an icon with your custom component, the bitmap does not appear in the Toolbox for autogenerated components. To see the bitmap, reload the control by using the **Choose Toolbox Items** dialog box. For more information, see [How to: Provide a Toolbox Bitmap for a Control](how-to-provide-a-toolbox-bitmap-for-a-control.md). + +## See also + +- [Developing Windows Forms Controls at Design Time](developing-windows-forms-controls-at-design-time.md) +- [Walkthrough: Automatically Populating the Toolbox with Custom Components](walkthrough-automatically-populating-the-toolbox-with-custom-components.md) +- [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md) +- [Walkthrough: Debugging Custom Windows Forms Controls at Design Time](walkthrough-debugging-custom-windows-forms-controls-at-design-time.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/unbound-column-to-a-data-bound-datagridview.md b/dotnet-desktop-guide/framework/winforms/controls/unbound-column-to-a-data-bound-datagridview.md new file mode 100644 index 0000000000..5e2e6488cc --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/unbound-column-to-a-data-bound-datagridview.md @@ -0,0 +1,35 @@ +--- +title: Add an Unbound Column to a Data-Bound DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "columns [Windows Forms], unbound data" + - "data grids [Windows Forms], adding unbound columns" + - "DataGridView control [Windows Forms], unbound data" +ms.assetid: f7bdc4d8-ba8e-421b-ad62-82d936f01372 +--- +# How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control +The data you display in the control will normally come from a data source of some kind, but you might want to display a column of data that does not come from the data source. This kind of column is called an unbound column. Unbound columns can take many forms. Frequently, they are used to provide access to the details of a data row. + + The following code example demonstrates how to create an unbound column of **Details** buttons to display a child table related to a particular row in a parent table when you implement a master/detail scenario. To respond to button clicks, implement a event handler that displays a form containing the child table. + + There is support for this task in Visual Studio. Also see [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridViewMisc#010](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs#010)] + [!code-vb[System.Windows.Forms.DataGridViewMisc#010](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb#010)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the and assemblies. + +## See also + +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/use-the-row-template-to-customize-rows-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/use-the-row-template-to-customize-rows-in-the-datagrid.md new file mode 100644 index 0000000000..cf2d54e2c0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/use-the-row-template-to-customize-rows-in-the-datagrid.md @@ -0,0 +1,45 @@ +--- +title: Use the Row Template to Customize Rows in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "data grids [Windows Forms], customizing rows" + - "DataGridView control [Windows Forms], customizing rows" +ms.assetid: 6db61607-7e57-4a84-8d63-9d6a7ed7f9ff +--- +# How to: Use the Row Template to Customize Rows in the Windows Forms DataGridView Control +The control uses the row template as a basis for all rows that it adds to the control either through data binding or when you call the method without specifying an existing row to use. + + The row template gives you greater control over the appearance and behavior of rows than the property provides. With the row template, you can set any properties, including . + + There are some situations where you must use the row template to achieve a particular effect. For example, row height information cannot be stored in a , so you must use a row template to change the default height used by all rows. The row template is also useful when you create your own classes derived from and you want your custom type used when new rows are added to the control. + +> [!NOTE] +> The row template is used only when rows are added. You cannot change existing rows by changing the row template. + +### To use the row template + +- Set properties on the object retrieved from the property. + + [!code-cpp[System.Windows.Forms.DataGridView.RowTemplate#1](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CPP/datagridviewrowtemplate.cpp#1)] + [!code-csharp[System.Windows.Forms.DataGridView.RowTemplate#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CS/datagridviewrowtemplate.cs#1)] + [!code-vb[System.Windows.Forms.DataGridView.RowTemplate#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/VB/datagridviewrowtemplate.vb#1)] + +## Compiling the Code + This example requires: + +- A control named `dataGridView1`. + +- References to the , , and assemblies. + +## See also + +- +- +- +- +- [Basic Formatting and Styling in the Windows Forms DataGridView Control](basic-formatting-and-styling-in-the-windows-forms-datagridview-control.md) +- [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/user-drawn-controls.md b/dotnet-desktop-guide/framework/winforms/controls/user-drawn-controls.md new file mode 100644 index 0000000000..ebaeb17831 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/user-drawn-controls.md @@ -0,0 +1,81 @@ +--- +title: "User-Drawn Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], user-drawn" + - "OnPaint method [Windows Forms]" + - "user-drawn controls [Windows Forms]" +ms.assetid: 034af4b5-457f-4160-a937-22891817faa8 +--- +# User-Drawn Controls +The .NET Framework provides you with the ability to easily develop your own controls. You can create a user control, which is a set of standard controls bound together by code, or you can design your own control from the ground up. You can even use inheritance to create a control that inherits from an existing control and add to its inherent functionality. Whatever approach you use, the .NET Framework provides the functionality to draw a custom graphical interface for any control you create. + + Painting of a control is accomplished by the execution of code in the control's method. The single argument of the method is a object that provides all of the information and functionality required to render your control. The provides as properties two principal objects that will be used in the rendering of your control: + +- object - the rectangle that represents the part of the control that will be drawn. This can be the entire control, or part of the control depending on how the control is drawn. + +- object - encapsulates several graphics-oriented objects and methods that provide the functionality necessary to draw your control. + + For more information on the object and how to use it, see [How to: Create Graphics Objects for Drawing](../advanced/how-to-create-graphics-objects-for-drawing.md). + + The event is fired whenever the control is drawn or refreshed on the screen, and the object represents the rectangle in which painting will take place. If the entire control needs to be refreshed, the will represent the size of the entire control. If only part of the control needs to be refreshed, however, the object will represent only the region that needs to be redrawn. An example of such a case would be when a control was partially obscured by another control or form in the user interface. + + When inheriting from the class, you must override the method and provide graphics-rendering code within. If you want to provide a custom graphical interface to a user control or an inherited control, you can also do so by overriding the method. An example is shown below: + +```vb +Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + ' Call the OnPaint method of the base class. + MyBase.OnPaint(e) + + ' Declare and instantiate a drawing pen. + Using myPen As System.Drawing.Pen = New System.Drawing.Pen(Color.Aqua) + ' Draw an aqua rectangle in the rectangle represented by the control. + e.Graphics.DrawRectangle(myPen, New Rectangle(Me.Location, Me.Size)) + End Using +End Sub +``` + +```csharp +protected override void OnPaint(PaintEventArgs e) +{ + // Call the OnPaint method of the base class. + base.OnPaint(e); + + // Declare and instantiate a new pen. + using (System.Drawing.Pen myPen = new System.Drawing.Pen(Color.Aqua)) + { + // Draw an aqua rectangle in the rectangle represented by the control. + e.Graphics.DrawRectangle(myPen, new Rectangle(this.Location, + this.Size)); + } +} +``` + + The preceding example demonstrates how to render a control with a very simple graphical representation. It calls the method of the base class, it creates a object with which to draw, and finally draws an ellipse in the rectangle determined by the and of the control. Although most rendering code will be significantly more complicated than this, this example demonstrates the use of the object contained within the object. Note that if you are inheriting from a class that already has a graphical representation, such as or , and you do not wish to incorporate that representation into your rendering, you should not call your base class's method. + + 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: + +```vb +SetStyle(ControlStyles.ResizeRedraw, True) +``` + +```csharp +SetStyle(ControlStyles.ResizeRedraw, true); +``` + +> [!NOTE] +> Use the property to implement a non-rectangular control. + +## See also + +- +- +- +- +- +- [How to: Create Graphics Objects for Drawing](../advanced/how-to-create-graphics-objects-for-drawing.md) +- [Constituent Controls](constituent-controls.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/using-the-designer-with-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/using-the-designer-with-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..2bfff8d215 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/using-the-designer-with-the-windows-forms-datagridview-control.md @@ -0,0 +1,53 @@ +--- +title: Using the Designer with DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "tables [Windows Forms]" + - "DataGridView control [Windows Forms], designer support" + - "formatting [Windows Forms]" +ms.assetid: b66057a6-5983-4864-b4e7-8cbc88a7010c +--- +# Using the Designer with the Windows Forms DataGridView Control +Visual Studio provides designer support for the `DataGridView` control that enables you to perform many setup tasks without writing code. These tasks include binding the control to a data source, modifying the columns used to display data, and adjusting the appearance and basic behavior of the control. + +## In This Section + [How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer](add-and-remove-columns-in-the-datagrid-using-the-designer.md) + Describes how to use the **Add Columns** and **Edit Columns** dialog boxes to populate and modify the columns collection. + + [How to: Bind Data to the Windows Forms DataGridView Control Using the Designer](bind-data-to-the-datagrid-using-the-designer.md) + Describes how to use the **Choose Data Source** option on the control's smart tag to connect to data. + + [How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer](change-the-order-of-columns-in-the-datagrid-using-the-designer.md) + Describes how to use the **Edit Columns** dialog box to rearrange columns. + + [How to: Change the Type of a Windows Forms DataGridView Column Using the Designer](change-the-type-of-a-wf-datagridview-column-using-the-designer.md) + Describes how to use the **Edit Columns** dialog box to change column types. + + [How to: Enable Column Reordering in the Windows Forms DataGridView Control Using the Designer](enable-column-reordering-in-the-datagrid-using-the-designer.md) + Describes how to use the control's smart tag to enable users to rearrange columns. + + [How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer](freeze-columns-in-the-datagrid-using-the-designer.md) + Describes how to use the **Edit Columns** dialog box to prevent specific columns from scrolling. + + [How to: Hide Columns in the Windows Forms DataGridView Control Using the Designer](hide-columns-in-the-datagrid-using-the-designer.md) + Describes how to use the **Edit Columns** dialog box to hide specific columns. + + [How to: Make Columns Read-Only in the Windows Forms DataGridView Control Using the Designer](make-columns-read-only-in-the-datagrid-using-the-designer.md) + Describes how to use the **Edit Columns** dialog box to prevent users from editing values in specific columns. + + [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer](prevent-row-addition-and-deletion-in-the-datagrid-using-the-designer.md) + Describes how to use the control's smart tag to prevent users from adding or deleting rows. + + [How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer](set-alternating-row-styles-for-the-datagrid-using-the-designer.md) + Describes how to use the **CellStyle Builder** dialog box to create a ledger-like appearance in the control. + + [How to: Set Default Cell Styles and Data Formats for the Windows Forms DataGridView Control Using the Designer](default-cell-styles-datagridview.md) + Describes how to use the **CellStyle Builder** dialog box to set up the basic appearance and data-display formats for the control. + +## Reference + + Provides reference documentation for the control. + +## See also + +- [DataGridView Control](datagridview-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/using-the-managed-html-document-object-model.md b/dotnet-desktop-guide/framework/winforms/controls/using-the-managed-html-document-object-model.md new file mode 100644 index 0000000000..716c866433 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/using-the-managed-html-document-object-model.md @@ -0,0 +1,35 @@ +--- +title: "Using the Managed HTML Document Object Model" +ms.date: "03/30/2017" +helpviewer_keywords: + - "managed HTML DOM" +ms.assetid: a017dd5c-cd7b-47e4-952c-f4f54cb48409 +--- +# Using the Managed HTML Document Object Model +The managed HTML document object model (DOM) provides a wrapper based on the .NET Framework for the HTML classes exposed by Internet Explorer. Use these classes to manipulate HTML pages hosted in the control, or to build new pages from the beginning. + +## In This Section + [How to: Access the Managed HTML Document Object Model](how-to-access-the-managed-html-document-object-model.md) + Describes how to obtain a valid instance of from either a Windows Forms application or a hosted in Internet Explorer. + + [How to: Access the HTML Source in the Managed HTML Document Object Model](how-to-access-the-html-source-in-the-managed-html-document-object-model.md) + Describes how to obtain the original, unmodified HTML source, and how to obtain the "live" source that reflects the current state of the DOM. + + [How to: Change Styles on an Element in the Managed HTML Document Object Model](how-to-change-styles-on-an-element-in-the-managed-html-document-object-model.md) + Describes how to manipulate styles, which are used to control the visual display of elements. + + [Accessing Frames in the Managed HTML Document Object Model](accessing-frames-in-the-managed-html-document-object-model.md) + Describes what frames and framesets are, and how to access the DOM of a frame. + + [Accessing Unexposed Members on the Managed HTML Document Object Model](accessing-unexposed-members-on-the-managed-html-document-object-model.md) + Describes how to access members of the underlying DOM that do not have a managed equivalent. + +## Reference + + + + + + +## Related Sections + [WebBrowser Control](webbrowser-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..4ab8a31c06 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/using-the-row-for-new-records-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,59 @@ +--- +title: Using the Row for New Records in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], adding rows for new records" + - "rows [Windows Forms], new records" + - "DataGridView control [Windows Forms], data entry" +ms.assetid: 6110f1ea-9794-442c-a98a-f104a1feeaf4 +--- +# Using the Row for New Records in the Windows Forms DataGridView Control +When you use a for editing data in your application, you will often want to give your users the ability to add new rows of data to the data store. The control supports this functionality by providing a row for new records, which is always shown as the last row. It is marked with an asterisk (*) symbol in its row header. The following sections discuss some of the things you should consider when you program with the row for new records enabled. + +## Displaying the Row for New Records + Use the property to indicate whether the row for new records is displayed. The default value of this property is `true`. + + For the data bound case, the row for new records will be shown if the property of the control and the property of the data source are both `true`. If either is `false` then the row will not be shown. + +## Populating the Row for New Records with Default Data + When the user selects the row for new records as the current row, the control raises the event. + + This event provides access to the new and enables you to populate the new row with default data. For more information, see [How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control](specify-default-values-for-new-rows-in-the-datagrid.md) + +## The Rows Collection + The row for new records is contained in the control's collection but behaves differently in two respects: + +- The row for new records cannot be removed from the collection programmatically. An is thrown if this is attempted. The user also cannot delete the row for new records. The method does not remove this row from the collection. + +- No row can be added after the row for new records. An is raised if this is attempted. As a result, the row for new records is always the last row in the control. The methods on that add rows—, , and —all call insertion methods internally when the row for new records is present. + +## Visual Customization of the Row for New Records + When the row for new records is created, it is based on the row specified by the property. Any cell styles that are not specified for this row are inherited from other properties. For more information about cell style inheritance, see [Cell Styles in the Windows Forms DataGridView Control](cell-styles-in-the-windows-forms-datagridview-control.md). + + The initial values displayed by cells in the row for new records are retrieved from each cell's property. For cells of type , this property returns a placeholder image. Otherwise, this property returns `null`. You can override this property to return a custom value. However, these initial values can be replaced by a event handler when focus enters the row for new records. + + The standard icons for this row's header, which are an arrow or an asterisk, are not exposed publicly. If you want to customize the icons, you will need to create a custom class. + + The standard icons use the property of the in use by the row header cell. The standard icons are not rendered if there is not enough space to display them completely. + + If the row header cell has a string value set, and if there is not enough room for both the text and icon, the icon is dropped first. + +## Sorting + In unbound mode, new records will always be added to the end of the even if the user has sorted the content of the . The user will need to apply the sort again in order to sort the row to the correct position; this behavior is similar to that of the control. + + In data bound and virtual modes, the insertion behavior when a sort is applied will be dependent on the implementation of the data model. For ADO.NET, the row is immediately sorted into the correct position. + +## Other Notes on the Row for New Records + You cannot set the property of this row to `false`. An is raised if this is attempted. + + The row for new records is always created in the unselected state. + +## Virtual Mode + If you are implementing virtual mode, you will need to track when a row for new records is needed in the data model and when to roll back the addition of the row. The exact implementation of this functionality depends on the implementation of the data model and its transaction semantics, for example, whether commit scope is at the cell or row level. For more information, see [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) +- [How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control](specify-default-values-for-new-rows-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/varieties-of-custom-controls.md b/dotnet-desktop-guide/framework/winforms/controls/varieties-of-custom-controls.md new file mode 100644 index 0000000000..185f0ee386 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/varieties-of-custom-controls.md @@ -0,0 +1,109 @@ +--- +title: "Varieties of Custom Controls" +ms.date: "03/30/2017" +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" +ms.assetid: 3cea09e5-4344-4ccb-9858-b66ccac210ff +--- +# Varieties of Custom Controls +With the .NET Framework, you can develop and implement new controls. You can extend the functionality of the familiar user control as well as existing controls through inheritance. You can also write custom controls that perform their own painting. + + Deciding which kind of control to create can be confusing. This topic 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 kind of control for your project. + +> [!NOTE] +> For information about authoring a control to use on Web Forms, see [Developing Custom ASP.NET Server Controls](https://docs.microsoft.com/previous-versions/aspnet/zt27tfhy(v=vs.100)). + +## 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. + + The class performs the following tasks to provide visual display in Windows Forms applications: + +- 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 is relatively easy to develop your own Windows Forms controls. + +## Kinds of Controls + Windows Forms supports three kinds of user-defined controls: *composite*, *extended*, and *custom*. The following sections describe each kind of control and give recommendations for choosing the kind to use in your projects. + +### 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 could 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. For an example of this kind of composite control, see [How to: Apply Attributes in Windows Forms Controls](how-to-apply-attributes-in-windows-forms-controls.md). + + 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. For more information, see [Developing a Composite Windows Forms Control](developing-a-composite-windows-forms-control.md). + + **Recommendation** + + Inherit from the class if: + +- You want to combine the functionality of several Windows Forms controls into a single reusable unit. + +### Extended Controls + You can derive an inherited control from any existing Windows Forms control. With this approach, you can retain 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. + + **Recommendation** + + Inherit from a Windows Forms control if: + +- Most of the functionality you need is already identical to an existing Windows Forms control. + +- You do not need a custom graphical user interface, or you want to design a new graphical user interface for an existing control. + +### 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. For more information, see [How to: Develop a Simple Windows Forms Control](how-to-develop-a-simple-windows-forms-control.md). + + **Recommendation** + + Inherit from the class if: + +- You want to provide a custom graphical representation of your control. + +- You need to implement custom functionality that is not available through standard controls. + +### ActiveX Controls + Although the Windows Forms infrastructure has been optimized to host Windows Forms controls, you can still use ActiveX controls. There is support for this task in Visual Studio. For more information, see [How to: Add ActiveX Controls to Windows Forms](how-to-add-activex-controls-to-windows-forms.md). + +### Windowless Controls + The Microsoft Visual Basic® 6.0and ActiveX technologies support *windowless* controls. Windowless controls are not 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. For more information, see [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)) and [How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/307hck25(v=vs.120)). + +## See also + +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) +- [How to: Develop a Simple Windows Forms Control](how-to-develop-a-simple-windows-forms-control.md) +- [Developing a Composite Windows Forms Control](developing-a-composite-windows-forms-control.md) +- [Extending Design-Time Support](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/37899azc(v=vs.120)) +- [How to: Create a Windows Forms Control That Takes Advantage of Design-Time Features](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2013/307hck25(v=vs.120)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/view-errors-within-a-dataset-with-wf-errorprovider-component.md b/dotnet-desktop-guide/framework/winforms/controls/view-errors-within-a-dataset-with-wf-errorprovider-component.md new file mode 100644 index 0000000000..8ffab3ca6d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/view-errors-within-a-dataset-with-wf-errorprovider-component.md @@ -0,0 +1,62 @@ +--- +title: View Errors Within a DataSet using ErrorProvider Component +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "errors [Windows Forms], dataset errors" + - "error messages [Windows Forms], viewing in datasets" + - "ErrorProvider component [Windows Forms], dataset errors" +ms.assetid: cbae023f-d651-4210-bdea-bcc5f037e321 +--- +# How to: View Errors Within a DataSet with the Windows Forms ErrorProvider Component +You can use the Windows Forms component to view column errors within a dataset or other data source. For an component to display data errors on a form, it does not have to be directly associated with a control. Once it is bound to a data source, it can display an error icon next to any control that is bound to the same data source. + +> [!NOTE] +> If you change the error provider's and properties at run time, you should use the method to avoid conflicts. + +### To display data errors + +1. Bind the component to a specific column within a data table. + + ```vb + ' Assumes existence of DataSet1, DataTable1 + TextBox1.DataBindings.Add("Text", DataSet1, "Customers.Name") + ErrorProvider1.DataSource = DataSet1 + ErrorProvider1.DataMember = "Customers" + ``` + + ```csharp + // Assumes existence of DataSet1, DataTable1 + textBox1.DataBindings.Add("Text", DataSet1, "Customers.Name"); + errorProvider1.DataSource = DataSet1; + errorProvider1.DataMember = "Customers"; + ``` + +2. Set the property to the form. + + ```vb + ErrorProvider1.ContainerControl = Me + ``` + + ```csharp + errorProvider1.ContainerControl = this; + ``` + +3. Set the position of the current record to a row that contains a column error. + + ```vb + DataTable1.Rows(5).SetColumnError("Name", "Bad data in this row.") + Me.BindingContext(DataTable1).Position = 5 + ``` + + ```csharp + DataTable1.Rows[5].SetColumnError("Name", "Bad data in this row."); + this.BindingContext [DataTable1].Position = 5; + ``` + +## See also + +- [ErrorProvider Component Overview](errorprovider-component-overview-windows-forms.md) +- [How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component](display-error-icons-for-form-validation-with-wf-errorprovider.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/virtual-mode-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/virtual-mode-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..76982465f6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/virtual-mode-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,66 @@ +--- +title: Virtual Mode in DataGridView Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "DataGridView control [Windows Forms], virtual mode" +ms.assetid: feae5d43-2848-4b1a-8ea7-77085dc415b5 +--- +# Virtual Mode in the Windows Forms DataGridView Control +With virtual mode, you can manage the interaction between the control and a custom data cache. To implement virtual mode, set the property to `true` and handle one or more of the events described in this topic. You will typically handle at least the `CellValueNeeded` event, which enables the control look up values in the data cache. + +## Bound Mode and Virtual Mode + Virtual mode is necessary only when you need to supplement or replace bound mode. In bound mode, you set the property and the control automatically loads the data from the specified source and submits user changes back to it. You can control which of the bound columns are displayed, and the data source itself typically handles operations such as sorting. + +## Supplementing Bound Mode + You can supplement bound mode by displaying unbound columns along with the bound columns. This is sometimes called "mixed mode" and is useful for displaying things like calculated values or user-interface (UI) controls. + + Because unbound columns are outside the data source, they are ignored by the data source's sorting operations. Therefore, when you enable sorting in mixed mode, you must manage the unbound data in a local cache and implement virtual mode to let the control interact with it. + + For more information about using virtual mode to maintain the values in unbound columns, see the examples in the property and class reference topics. + +## Replacing Bound Mode + If bound mode does not meet your performance needs, you can manage all your data in a custom cache through virtual-mode event handlers. For example, you can use virtual mode to implement a just-in-time data loading mechanism that retrieves only as much data from a networked database as is necessary for optimal performance. This scenario is particularly useful when working with large amounts of data over a slow network connection or with client machines that have a limited amount of RAM or storage space. + + For more information about using virtual mode in a just-in-time scenario, see [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md). + +## Virtual-Mode Events + If your data is read-only, the `CellValueNeeded` event may be the only event you will need to handle. Additional virtual-mode events let you enable specific functionality like user edits, row addition and deletion, and row-level transactions. + + Some standard events (such as events that occur when users add or delete rows, or when cell values are edited, parsed, validated, or formatted) are useful in virtual mode, as well. You can also handle events that let you maintain values not typically stored in a bound data source, such as cell ToolTip text, cell and row error text, cell and row shortcut menu data, and row height data. + + For more information about implementing virtual mode to manage read/write data with a row-level commit scope, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + + For an example that implements virtual mode with a cell-level commit scope, see the property reference topic. + + The following events occur only when the property is set to `true`. + +|Event|Description| +|-----------|-----------------| +||Used by the control to retrieve a cell value from the data cache for display. This event occurs only for cells in unbound columns.| +||Used by the control to commit user input for a cell to the data cache. This event occurs only for cells in unbound columns.

Call the method when changing a cached value outside of a event handler to ensure that the current value is displayed in the control and to apply any automatic sizing modes currently in effect.| +||Used by the control to indicate the need for a new row in the data cache.| +||Used by the control to determine whether a row has any uncommitted changes.| +||Used by the control to indicate that a row should revert to its cached values.| + + The following events are useful in virtual mode, but can be used regardless of the property setting. + +|Events|Description| +|------------|-----------------| +|





|Used by the control to indicate when rows are deleted or added, letting you update the data cache accordingly.| +|









|Used by the control to format cell values for display and to parse and validate user input.| +||Used by the control to retrieve cell ToolTip text when the property is set or the property is `true`.

Cell ToolTips are displayed only when the property value is `true`.| +|

|Used by the control to retrieve cell or row error text when the property is set or the property is `true`.

Call the method or the method when you change the cell or row error text to ensure that the current value is displayed in the control.

Cell and row error glyphs are displayed when the and property values are `true`.| +|

|Used by the control to retrieve a cell or row when the control property is set or the property is `true`.| +|

|Used by the control to retrieve or store row height information in the data cache. Call the method when changing the cached row height information outside of a event handler to ensure that the current value is used in the display of the control.| + +## Best Practices in Virtual Mode + If you are implementing virtual mode in order to work efficiently with large amounts of data, you will also want to ensure that you are working efficiently with the control itself. For more information about the efficient use of cell styles, automatic sizing, selections, and row sharing, see [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) +- [Best Practices for Scaling the Windows Forms DataGridView Control](best-practices-for-scaling-the-windows-forms-datagridview-control.md) +- [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md) +- [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md b/dotnet-desktop-guide/framework/winforms/controls/virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md new file mode 100644 index 0000000000..e6e6e82089 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/virtual-mode-with-just-in-time-data-loading-in-the-datagrid.md @@ -0,0 +1,40 @@ +--- +title: Implement Virtual Mode with Just-In-Time Data Loading in DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "examples [Windows Forms], just-in-time data loading" + - "data [Windows Forms], managing large data sets" + - "DataGridView control [Windows Forms], virtual mode" + - "just-in-time data loading" + - "DataGridView control [Windows Forms], large data sets" + - "virtual mode [Windows Forms], just-in-time data loading" +ms.assetid: 33825f92-7a22-40ee-86d9-9a2ed1ead7b7 +--- +# How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control +The following code example shows how to use virtual mode in the control with a data cache that loads data from a server only when it is needed. This example is described in detail in [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md). + +## Example + [!code-csharp[System.Windows.Forms.DataGridView.Virtual_lazyloading#000](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs#000)] + [!code-vb[System.Windows.Forms.DataGridView.Virtual_lazyloading#000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb#000)] + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Xml, and System.Windows.Forms assemblies. + +- Access to a server with the Northwind SQL Server sample database installed. + +## .NET Framework Security + Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + +## See also + +- +- +- +- [Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control](implementing-virtual-mode-jit-data-loading-in-the-datagrid.md) +- [Performance Tuning in the Windows Forms DataGridView Control](performance-tuning-in-the-windows-forms-datagridview-control.md) +- [Virtual Mode in the Windows Forms DataGridView Control](virtual-mode-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md new file mode 100644 index 0000000000..094484ca49 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md @@ -0,0 +1,189 @@ +--- +title: Arrange Controls Using FlowLayoutPanel +description: Learn how to use the FlowLayoutPanel control and the TableLayoutPanel control to provide intuitive ways to arrange controls in your Windows Forms project. +ms.date: "03/30/2017" +helpviewer_keywords: + - "FlowLayoutPanel control [Windows Forms], walkthroughs" + - "Windows Forms controls, arranging" + - "controls [Windows Forms], arranging with FlowLayoutPanel" + - "layout [Windows Forms], walkthroughs" +ms.assetid: a1744323-0316-49c2-992e-ebfc0a976b85 +--- +# Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel + +Some applications require a form with a layout that arranges itself appropriately as the form is resized or as the contents change in size. When you need a dynamic layout and you do not want to handle events explicitly in your code, consider using a layout panel. + +The control and the control provide intuitive ways to arrange controls on your form. Both provide an automatic, configurable ability to control the relative positions of child controls contained within them, and both give you dynamic layout features at run time, so they can resize and reposition child controls as the dimensions of the parent form change. Layout panels can be nested within layout panels, to enable the realization of sophisticated user interfaces. + +The arranges its contents in a grid, providing functionality similar to the HTML \ element. Its cells are arranged in rows and columns, and these can have different sizes. For more information, see [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md). + +The arranges its contents in a specific flow direction: horizontal or vertical. Its contents can be wrapped from one row to the next, or from one column to the next. Alternately, its contents can be clipped instead of wrapped. Tasks illustrated in this walkthrough include: + +- Creating a Windows Forms project + +- Arranging Controls Horizontally and Vertically + +- Changing Flow Direction + +- Inserting Flow Breaks + +- Arranging Controls Using Padding and Margins + +- Inserting Controls by Double-clicking Them in the Toolbox + +- Inserting a Control by Drawing Its Outline + +- Inserting Controls Using the Caret + +- Reassigning Existing Controls to a Different Parent + +When you are finished, you'll have an understanding of the role played by these important layout features. + +## Create the project + +1. In Visual Studio, create a Windows-based application project called "FlowLayoutPanelExample" (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. Select the form in the **Forms Designer**. + +## Arranging Controls Horizontally and Vertically + The control allows you to place controls along rows or columns without requiring you to precisely specify the position of each individual control. + + The control can resize or reflow its child controls as the dimensions of the parent form change. + +### To arrange controls horizontally and vertically using a FlowLayoutPanel + +1. Drag a control from the **Toolbox** onto your form. + +2. Drag a control from the **Toolbox** into the . Note that it is automatically moved to the upper-left corner of the control. + +3. Drag another control from the **Toolbox** into the . Note that the control is automatically moved to a position next to the first control. If your is too narrow to fit the two controls on the same row, the new control is automatically moved to the next row. + +4. Drag several more controls from the **Toolbox** into the . Continue placing controls until one wraps to the next row. + +5. Change the value of the control's property to `false`. Note that the child controls no longer flow to the next row. Instead, they are moved to the first row and clipped. + +6. Change the value of the control's property to `true`. Note that the child controls again wrap to the next row. + +7. Decrease the width of the control until all the controls are moved into the first column. + +8. Increase the width of the control until all the controls are moved into the first row. You may need to resize your form to accommodate the greater width. + +## Changing Flow Direction + The property allows you to change the direction in which controls are arranged. You can arrange the child controls from left to right, from right to left, from top to bottom, or from bottom to top. + +### To change the flow direction in a FlowLayoutPanel + +1. Change the value of the control's property to . Note that the child controls are rearranged into one or more columns, depending on the height of the control. + +2. Resize the so its height is shorter than the column of controls. Note that the rearranges the child controls to flow into the next column. Continue decreasing the height and note that the child controls flow into consecutive columns. Change the value of the control's property to . Note that the positions of the child controls are reversed. Observe the layout when you change the value of the property to . + +## Inserting Flow Breaks + The control 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. + +### To insert flow breaks + +1. Change the value of the control's property to . + +2. Select one of the controls in the middle of the leftmost column. + +3. Set the value of the control's FlowBreak property to `true`. Note that the column is broken and the controls following the selected control flow into the next column. Set the value of the control's FlowBreak property to `false` to return to the original behavior. + +## Positioning Controls Using Docking and Anchoring + Docking and anchoring behaviors of child controls differ from the behaviors in other container controls. Both docking and anchoring are relative to the largest control in the flow direction. + +### To position controls using docking and anchoring + +1. Increase the size of the until the controls are all arranged in a column. + +2. Select the top control. Increase its width so that it is about twice as wide as the other controls. + +3. Select the second control. Change the value of its property to . Note that it is moved so that its right border is aligned with the first control's right border. + +4. Change the value of its property to and . Note that it is sized to the same width as the first control. + +5. Select the third control. Change the value of its property to . Note that it is sized to the same width as the first control. + +## Arranging Controls Using Padding and Margins + You can also arrange controls in your control by changing the and properties. + + The property allows you to control the placement of controls within a control's cell. It specifies the spacing between the child controls and the control's border. + + The property allows you to control the spacing between controls. + +### To arrange controls using the Padding and Margin properties + +1. Change the value of the control's property to . If your form is large enough, the controls will be moved into the first column of the control. + +2. Change the value of the control's property by expanding the entry in the **Properties** window and setting the property to **20**. For more information, see [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md). Note that the child controls are moved toward the center of the control. The increased value for the property pushes the child controls away from the control's borders. + +3. Select all of the controls in the and set the value of the property to **20**. Note that the spacing between the controls increases, so they are moved further apart. You may need to resize the control to be larger to see all of the child controls. + +## Inserting Controls by Double-clicking Them in the Toolbox + You can populate your control by double-clicking controls in the **Toolbox**. + +### To insert controls by double-clicking in the Toolbox + +1. Double-click the control icon in the **Toolbox**. Note that a new control appears in the control. + +2. Double-click several more controls in the **Toolbox**. Note that the new controls appear successively in the control. + +## Inserting a Control by Drawing Its Outline + You can insert a control into a control and specify its size by drawing its outline in a cell. + +### To insert a Control by drawing its outline + +1. In the **Toolbox**, click the control icon. Do not drag it onto the form. + +2. Move the mouse pointer over the control. Note that the pointer changes to a crosshair with the control icon attached. + +3. Click and hold the mouse button. + +4. Drag the mouse pointer to draw the outline of the control. When you are satisfied with the size, release the mouse button. Note that the control is created in the next open location of the control. + +## Inserting Controls Using the Insertion Bar + You can insert controls at a specific position in a control. When you drag a control into the control's client area, an insertion bar appears to indicate where the control will be inserted. + +### To insert a control using the caret + +1. Drag a control from the **Toolbox** into the control and point to the space between two controls. Note that an insertion bar is drawn, indicating where the will be placed when it is dropped into the control. Before you drop the new control into the control, move the mouse pointer around to observe how the insertion bar moves. + +2. Drop the new control into the control. Note that the new control is not aligned with the others, because its property has a different value. + +## Reassigning Existing Controls to a Different Parent + You can assign controls that exist on your form to a new control. + +### To reparent existing controls + +1. Drag three controls from the **Toolbox** onto the form. Position them near to each other, but leave them unaligned. + +2. In the **Toolbox**, click the control icon. Do not drag it onto the form. + +3. Move the mouse pointer close to the three controls. Note that the pointer changes to a crosshair with the control icon attached. + +4. Click and hold the mouse button. + +5. Drag the mouse pointer to draw the outline of the control. Draw the outline around the three controls. + +6. Release the mouse button. Note that the three controls are inserted into the control. + +## Next Steps + You can achieve a complex layout using a combination of layout panels and controls. Suggestions for more exploration include: + +- Resize one of the controls to a larger size and note the effect on the layout. + +- Layout panels can contain other layout panels. Experiment with dropping a control into the existing control. + +- Dock the control to the parent form. Resize the form and note the effect on the layout. + +- Set the property of one of the controls to `false` and note how the reflows in response. + +## See also + +- +- +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) +- [AutoSize Property Overview](autosize-property-overview.md) +- [How to: Dock Controls on Windows Forms](how-to-dock-controls-on-windows-forms.md) +- [How to: Anchor Controls on Windows Forms](how-to-anchor-controls-on-windows-forms.md) +- [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md new file mode 100644 index 0000000000..72218b087c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md @@ -0,0 +1,197 @@ +--- +title: Arranging Controls Using a TableLayoutPanel +description: Learn how to arrange controls on your Windows Forms by using the FlowLayoutPanel control and the TableLayoutPanel control. +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], arranging with TableLayoutPanel" + - "TableLayoutPanel control [Windows Forms], walkthroughs" + - "Windows Forms controls, arranging" +ms.assetid: d474885e-12cc-4ab7-b997-2a23a643049b +--- +# Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel + +Some applications require a form with a layout that arranges itself appropriately as the form is resized or as the contents change in size. When you need a dynamic layout and you do not want to handle events explicitly in your code, consider using a layout panel. + +The control and the control provide intuitive ways to arrange controls on your form. Both provide an automatic, configurable ability to control the relative positions of child controls contained within them, and both give you dynamic layout features at run time, so they can resize and reposition child controls as the dimensions of the parent form change. Layout panels can be nested within layout panels, to enable the realization of sophisticated user interfaces. + +The arranges its contents in a specific flow direction: horizontal or vertical. Its contents can be wrapped from one row to the next, or from one column to the next. Alternately, its contents can be clipped instead of wrapped. For more information, see [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md). + +The arranges its contents in a grid, providing functionality similar to the HTML \
element. The control allows you to place controls in a grid layout without requiring you to precisely specify the position of each individual control. Its cells are arranged in rows and columns, and these can have different sizes. Cells can be merged across rows and columns. Cells can contain anything a form can contain and behave in most other respects as containers. + +The control also provides a proportional resizing capability at run time, so your layout can change smoothly as your form is resized. This makes the control well suited for purposes such as data-entry forms and localized applications. For more information, see [Walkthrough: Creating a Resizable Windows Form for Data Entry](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/991eahec(v=vs.100)) and [Walkthrough: Creating a Localizable Windows Form](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/7k9fa71y(v=vs.100)). + +In general, you should not use a control as a container for the whole layout. Use controls to provide proportional resizing capabilities to parts of the layout. + +Tasks illustrated in this walkthrough include: + +- Creating a Windows Forms project + +- Arranging Controls in Rows and Columns + +- Setting Row and Column Properties + +- Spanning Rows and Columns with a Control + +- Automatic Handling of Overflows + +- Inserting Controls by Double-clicking Them in the Toolbox + +- Inserting a Control by Drawing Its Outline + +- Reassigning Existing Controls to a Different Parent + +When you are finished, you will have an understanding of the role played by these important layout features. + +## Creating the Project + +The first step is to create the project and set up the form. + +#### To create the project + +1. Create a Windows Application project called "TableLayoutPanelExample". For more information, see [How to: Create a Windows Forms application project](/visualstudio/ide/step-1-create-a-windows-forms-application-project) . + +2. Select the form in the **Windows** **Forms Designer**. + +## Arranging Controls in Rows and Columns + +The control allows you to easily arrange controls into rows and columns. + +#### To arrange controls in rows and columns using a TableLayoutPanel + +1. Drag a control from the **Toolbox** onto your form. Note that, by default, the control has four cells. + +2. Drag a control from the **Toolbox** into the control and drop it into one of the cells. Note that the control is created within the cell you selected. + +3. Drag three more controls from the **Toolbox** into the control, so that each cell contains a button. + +4. Grab the vertical sizing handle between the two columns and move it to the left. Note that the controls in the first column are resized to a smaller width, while size of the controls in the second column is unchanged. + +5. Grab the vertical sizing handle between the two columns and move it to the right. Note that the controls in the first column return to their original size, while the controls in the second column are moved to the right. + +6. Move the horizontal sizing handle up and down to see the effect on the controls in the panel. + +## Positioning Controls Within Cells Using Docking and Anchoring + +The anchoring behavior of child controls in a differs from the behavior in other container controls. The docking behavior of child controls is the same as other container controls. + +#### Positioning controls within cells + +1. Select the first control. Change the value of its property to . Note that the control expands to fill its cell. + +2. Select one of the other controls. Change the value of its property to . Note that it is moved so that its right border is near the right border of the cell. The distance between the borders is the sum of the control's property and the panel's property. + +3. Change the value of the control's property to and . Note that the control is sized to the width of the cell, with the and values taken into account. + +4. Repeat steps 2 and 3 with the and styles. + +## Setting Row and Column Properties + +You can set individual properties of rows and columns by using the and collections. + +#### To set row and column properties + +1. Select the control in the **Windows Forms Designer**. + +2. In the **Properties** windows, open the collection by clicking the ellipsis (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/visual-studio-ellipsis-button.png)) button next to the **Columns** entry. + +3. Select the first column and change the value of its property to . Click **OK** to accept the change. Note that the width of the first column is reduced to fit the control. Also note that the width of the column is not resizable. + +4. In the **Properties** window, open the collection and select the first column. Change the value of its property to . Click **OK** to accept the change. Resize the control to a larger width and note that the width of the first column expands. Resize the control to a smaller width and note that the buttons in the first column are sized to fit the cell. Also note that the width of the column is resizable. + +5. In the **Properties** window, open the collection and select all the listed columns. Set the value of every property to . Click **OK** to accept the change. Repeat with the collection. + +6. Grab one of the corner resizing handles and resize both the width and height of the control. Note that the rows and columns are resized as the control's size changes. Also note that the rows and columns are resizable with the horizontal and vertical sizing handles. + +## Spanning Rows and Columns with a Control + +The control adds several new properties to controls at design time. Two of these properties are `RowSpan` and `ColumnSpan`. You can use these properties to make a control span more than one row or column. + +#### To span rows and columns with a control + +1. Select the control in the first row and first column. + +2. In the **Properties** windows, change the value of the `ColumnSpan` property to **2**. Note that the control fills the first column and the second column. Also note than an extra row has been added to accommodate this change. + +3. Repeat step 2 for the `RowSpan` property. + +## Inserting Controls by Double-clicking Them in the Toolbox + +You can populate your control by double-clicking controls in the **Toolbox**. + +#### To insert controls by double-clicking in the Toolbox + +1. Drag a control from the **Toolbox** onto your form. + +2. Double-click the control icon in the **Toolbox**. Note that a new button control appears in the control's first cell. + +3. Double-click several more controls in the **Toolbox**. Note that the new controls appear successively in the control's unoccupied cells. Also note that the control expands to accommodate the new controls if no open cells are available. + +## Automatic Handling of Overflows + +When you are inserting controls into the control, you may run out of empty cells for your new controls. The control handles this situation automatically by increasing the number of cells. + +#### To observe automatic handling of overflows + +1. If there are still empty cells in the control, continue inserting new controls until the control is full. + +2. Once the control is full, double-click the icon in the **Toolbox** to insert another control. Note that the control creates new cells to accommodate the new control. Insert a few more controls and observe the resizing behavior. + +3. Change the value of the control's property to . Double-click the icon in the **Toolbox** to insert controls until the control is full. Double-click the icon in the **Toolbox** again. Note that you receive an error message from the **Windows Forms Designer** informing you that additional rows and columns cannot be created. + +## Inserting a Control by Drawing Its Outline + +You can insert a control into a control and specify its size by drawing its outline in a cell. + +#### To insert a Control by drawing its outline + +1. Drag a control from the **Toolbox** onto your form. + +2. In the **Toolbox**, click the control icon. Do not drag it onto the form. + +3. Move the mouse pointer over the control. Note that the pointer changes to a crosshair with the control icon attached. + +4. Click and hold the mouse button. + +5. Drag the mouse pointer to draw the outline of the control. When you are satisfied with the size, release the mouse button. Note that the control is created in the cell in which you drew the control's outline. + +## Multiple Controls Within Cells Are Not Permitted + +The control can contain only one child control per cell. + +#### To demonstrate that multiple controls within cells are not permitted + +- Drag a control from the **Toolbox** into the control and drop it into one of the occupied cells. Note that the control does not allow you to drop the control into the occupied cell. + +## Swapping Controls + +The control enables you to swap the controls occupying two different cells. + +#### To swap controls + +- Drag one of the controls from an occupied cell and drop into onto another occupied cell. Note that the two controls are moved from one cell into the other. + +## Next Steps + +You can achieve a complex layout using a combination of layout panels and controls. Suggestions for more exploration include: + +- Try resizing one of the controls to a larger size and note the effect on the layout. + +- Paste a selection of multiple controls into the control and note how the controls are inserted. + +- Layout panels can contain other layout panels. Experiment with dropping a control into the existing control. + +- Dock the control to the parent form. Resize the form and note the effect on the layout. + +## See also + +- +- +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) +- [Walkthrough: Creating a Resizable Windows Form for Data Entry](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/991eahec(v=vs.100)) +- [Walkthrough: Creating a Localizable Windows Form](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/7k9fa71y(v=vs.100)) +- [Best Practices for the TableLayoutPanel Control](best-practices-for-the-tablelayoutpanel-control.md) +- [AutoSize Property Overview](autosize-property-overview.md) +- [How to: Dock Controls on Windows Forms](how-to-dock-controls-on-windows-forms.md) +- [How to: Anchor Controls on Windows Forms](how-to-anchor-controls-on-windows-forms.md) +- [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-snaplines.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-snaplines.md new file mode 100644 index 0000000000..0b6465db2f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-arranging-controls-on-windows-forms-using-snaplines.md @@ -0,0 +1,190 @@ +--- +title: Arranging Controls Using Snaplines +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], arranging with snaplines" + - "snaplines [Windows Forms], arranging Windows Forms controls" + - "SnapLine class [Windows Forms], walkthroughs" + - "Windows Forms controls, arranging" +ms.assetid: d5c9edc7-cf30-4a97-8ebe-201d569340f8 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Arrange controls on Windows Forms using snaplines + +Precise placement of controls on your form is a high priority for many applications. The Windows Forms Designer gives you many layout tools to accomplish this. One of the most important is the feature. + +Snaplines show you precisely where to line up controls with other controls. They also show you the recommended distances for margins between controls, as specified by the [Windows User Interface guidelines](/windows/win32/uxguide/guidelines). + +Snaplines make it easy to align your controls, for crisp, professional appearance and behavior (look and feel). + +## Create the project + +1. In Visual Studio, create a Windows-based application project called "SnaplineExample". + +2. Select the form in the Forms Designer. + +## Space and align controls + +Snaplines give you an accurate and intuitive way to align controls on your form. They appear when you are moving a selected control or controls near a position that would align with another control or set of controls. Your selection will "snap" to the suggested position as you move it past the other controls. + +### To arrange controls using snaplines + +1. Drag a control from the **Toolbox** onto your form. + +2. Move the control to the lower-right corner of the form. Note the snaplines that appear as the control approaches the bottom and right borders of the form. These snaplines display the recommended distance between the borders of the control and the form. + +3. Move the control around the borders of the form and note where the snaplines appear. When you are finished, move the control near the center of the form. + +4. Drag another control from the **Toolbox** onto your form. + +5. Move the second control until it is nearly level with the first. Note the snapline that appears at the text baseline of both buttons, and note that the control you are moving snaps to a position that is exactly level with the other control. + +6. Move the second control until it is positioned directly above the first. Note the snaplines that appear along the left and right edges of both buttons, and note that the control you are moving snaps to a position that is exactly aligned with the other control. + +7. Select one of the controls and move it close to the other, until they are almost touching. Note the snapline that appears between them. This distance is the recommended distance between the borders of the controls. Also note that the control you are moving snaps to this position. + +8. Drag two controls from the **Toolbox** onto your form. + +9. Move one of the controls until it is nearly level with the first. Note the snaplines that appear along the top and bottom edges of both controls, and note that the control you are moving snaps to a position that is exactly level with the other control. + +## Align to form and container margins + +Snaplines help you to align your controls to form and container margins in a consistent manner. + +1. Select one of the controls and move it close to the right border of the form until a snapline appears. The snapline's distance from the right border is the sum of the control's property and the form's property values. + + > [!NOTE] + > If the form's property is set to 0,0,0,0, the Windows Forms Designer gives the form a shadowed value of 9,9,9,9. To override this behavior, assign a value other than 0,0,0,0. + +2. Change the value of the control's property by expanding the entry in the **Properties** window and setting the property to 0. For details, see [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md). + +3. Move the control close to the right border of the form until a snapline appears. This distance is now given by the value of the form's property. + +4. Drag a control from the **Toolbox** onto your form. + +5. Change the value of the control's property by expanding the entry in the **Properties** window and setting the property to 10. + +6. Drag a control from the **Toolbox** into the control. + +7. Move the control close to the right border of the control until a snapline appears. Move the control within the control and note where the snaplines appear. + +## Align to grouped controls + +You can use snaplines to align grouped controls as well as controls within a control. + +1. Select two of the controls on your form. Move the selection around and note the snaplines that appear between your selection and the other controls. + +2. Drag a control from the **Toolbox** onto your form. + +3. Drag a control from the **Toolbox** into the control. + +4. Select one of the controls and move it around the control. Note the snaplines that appear at the edges of the control. Also note the snaplines that appear at the edges of the control that is contained by the control. Controls that are children of a container control also support snaplines. + +## Use snaplines to place a control by outlining its size + +1. In the **Toolbox**, click the control icon. Do not drag it onto the form. + +2. Move the mouse pointer over the form's design surface. Note that the pointer changes to a crosshair with the control icon attached. Also note the snaplines that appear to suggest aligned positions for the control. + +3. Click and hold the mouse button. + +4. Drag the mouse pointer around the form. Note that an outline is drawn, indicating the position and the size of the control. + +5. Drag the pointer until it aligns with another control on the form. Note that a snapline appears to indicate alignment. + +6. Release the mouse button. The control is created at the position and size indicated by the outline. + +## Use snaplines when dragging a control from the Toolbox + +1. Drag a control from the **Toolbox** onto your form, but do not release the mouse button. + +2. Move the mouse pointer over the form's design surface. Note that the pointer changes to indicate the position at which the new control will be created. + +3. Drag the mouse pointer around the form. Note the snaplines that appear to suggest aligned positions for the control. Find a position that is aligned with other controls. + +4. Release the mouse button. The control is created at the position indicated by the snaplines. + +## Resize a control using snaplines + +1. Drag a control from the **Toolbox** onto your form. + +2. Resize the control by grabbing one of the corner sizing handles and dragging. For details, see [How to: Resize Controls on Windows Forms](how-to-resize-controls-on-windows-forms.md). + +3. Drag the sizing handle until one of the control's borders is aligned with another control. Note that a snapline appears. Also note that the sizing handle snaps to the position indicated by the snapline. + +4. Resize the control in different directions and align the sizing handle to different controls. Note how the snaplines appear in various orientations to indicate alignment. + +## Align a label to a control's text + +1. Drag a control from the **Toolbox** onto your form. When you drop the control onto the form, click the smart-tag glyph and select the **Set text to textBox1** option. For details, see [Walkthrough: Perform common tasks using designer actions](perform-common-tasks-design-actions.md). + +2. Drag a control from the **Toolbox** onto your form. + +3. Change the value of the control's property to `true`. Note that the control's borders are adjusted to fit the display text. + +4. Move the control to the left of the control, so it is aligned with the bottom edge of the control. Note the snapline that appears along the bottom edges of the two controls. + +5. Move the control slightly upward, until the text and the text are aligned. Note the differently styled snapline that appears, indicating when the text fields of both controls are aligned. + +## Use snaplines with keyboard navigation + +1. Drag a control from the **Toolbox** onto your form. Place it in the upper-left corner of the form. + +2. Press **Ctrl**+**down arrow**. Note that the control moves down the form to the first available horizontal alignment position. + +3. Press **Ctrl**+**down arrow** until the control reaches the bottom of the form. Note the positions it occupies as it moves down the form. + +4. Press **Ctrl**+**right arrow**. Note that the control moves across the form to the first available vertical alignment position. + +5. Press **Ctrl**+**right arrow** until the control reaches the side of the form. Note the positions it occupies as it moves across the form. + +6. Move the control around the form with a combination of arrow keys. Note the positions the control occupies and the snaplines that accompany them. + +7. Press **Shift**+**arrow keys** to resize the control by increments of one pixel. + +8. Press **Ctrl**+**Shift**+**arrow keys** to resize the control in snapline increments. + +## Selectively disable snaplines + +1. Drag a control from the **Toolbox** onto your form. + +2. Double-click the control icon in the **Toolbox**. Note that a new button control appears in the control's first cell. + +3. Double-click the control icon in the **Toolbox** twice more. This leaves one empty cell in the control. + +4. Drag a control from the **Toolbox** into the empty cell of the control. Note that no snaplines appear. + +5. Drag the control out of the control and move it around the control. Note that snaplines appear again. + +## Disable snaplines + +Press the **Alt** key and while moving a control around the form. + +No snaplines appear and the control does not snap to any potential alignment positions. + +### To disable snaplines in the design environment + +1. From the **Tools** menu, open the **Options** dialog box. Select **Windows Forms Designer**. + +2. Select the **General** node. In the **Layout Mode** section, change the selection from **SnapLines** to **SnapToGrid**. + +3. Select **OK** to apply the setting. + +4. Select a control on your form and move it around the other controls. Note that snaplines do not appear. + +## Next steps + +Snaplines offer an intuitive means of aligning controls on your form. Suggestions for more exploration include: + +- Try nesting a control within another control. Place a control within the child control, and another within the parent control. Move the controls around to see how the snaplines cross container boundaries. + +- Create a column of controls and a corresponding column of controls. Set the value of the controls' property to `true`. Use snaplines to move the controls so their displayed text is aligned with the text in the controls. + +## See also + +- +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Laying Out Windows Forms Controls with Padding, Margins, and the AutoSize Property](windows-forms-controls-padding-autosize.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-authoring-a-composite-control-with-visual-csharp.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-authoring-a-composite-control-with-visual-csharp.md new file mode 100644 index 0000000000..3648a350d1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-authoring-a-composite-control-with-visual-csharp.md @@ -0,0 +1,415 @@ +--- +title: "Walkthrough: Authoring a Composite Control with Visual C#" +ms.date: "03/30/2017" +dev_langs: + - CSharp +helpviewer_keywords: + - "custom controls [C#]" + - "user controls [Windows Forms], creating with Visual C#" + - "UserControl class [Windows Forms], walkthroughs" + - "user controls [C#]" + - "custom controls [Windows Forms], creating" +ms.assetid: f88481a8-c746-4a36-9479-374ce5f2e91f +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Author a Composite Control with C\# + +Composite controls provide a means by which custom graphical interfaces can be created and reused. A composite control is essentially a component with a visual representation. As such, it might consist of one or more Windows Forms controls, components, or blocks of code that can extend functionality by validating user input, modifying display properties, or performing other tasks required by the author. Composite controls can be placed on Windows Forms in the same manner as other controls. In the first part of this walkthrough, you create a simple composite control called `ctlClock`. In the second part of the walkthrough, you extend the functionality of `ctlClock` through inheritance. + +## Create the Project + +When you create a new project, you specify its name to set the root namespace, assembly name, and project name, and ensure that the default component will be in the correct namespace. + +### To create the ctlClockLib control library and the ctlClock control + +1. In Visual Studio, create a new **Windows Forms Control Library** project, and name it **ctlClockLib**. + + The project name, `ctlClockLib`, is also assigned to the root namespace by default. The root namespace is used to qualify the names of components in the assembly. For example, if two assemblies provide components named `ctlClock`, you can specify your `ctlClock` component using `ctlClockLib.ctlClock.` + +2. In **Solution Explorer**, right-click **UserControl1.cs**, and then click **Rename**. Change the file name to `ctlClock.cs`. Click the **Yes** button when you are asked if you want to rename all references to the code element "UserControl1". + + > [!NOTE] + > By default, a composite control inherits from the class provided by the system. The class provides functionality required by all composite controls, and implements standard methods and properties. + +3. On the **File** menu, click **Save All** to save the project. + +## Add Windows Controls and Components to the Composite Control + +A visual interface is an essential part of your composite control. This visual interface is implemented by the addition of one or more Windows controls to the designer surface. In the following demonstration, you will incorporate Windows controls into your composite control and write code to implement functionality. + +### To add a Label and a Timer to your composite control + +1. In **Solution Explorer**, right-click **ctlClock.cs**, and then click **View Designer**. + +2. In the **Toolbox**, expand the **Common Controls** node, and then double-click **Label**. + + A control named `label1` is added to your control on the designer surface. + +3. In the designer, click **label1**. In the Properties window, set the following properties. + + |Property|Change to| + |--------------|---------------| + |**Name**|`lblDisplay`| + |**Text**|`(blank space)`| + |**TextAlign**|`MiddleCenter`| + |**Font.Size**|`14`| + +4. In the **Toolbox**, expand the **Components** node, and then double-click **Timer**. + + Because a is a component, it has no visual representation at run time. Therefore, it does not appear with the controls on the designer surface, but rather in the **Component Designer** (a tray at the bottom of the designer surface). + +5. In the **Component Designer**, click **timer1**, and then set the property to `1000` and the property to `true`. + + The property controls the frequency with which the component ticks. Each time `timer1` ticks, it runs the code in the `timer1_Tick` event. The interval represents the number of milliseconds between ticks. + +6. In the **Component Designer**, double-click **timer1** to go to the `timer1_Tick` event for `ctlClock`. + +7. Modify the code so that it resembles the following code sample. Be sure to change the access modifier from `private` to `protected`. + + ```csharp + protected void timer1_Tick(object sender, System.EventArgs e) + { + // Causes the label to display the current time. + lblDisplay.Text = DateTime.Now.ToLongTimeString(); + } + ``` + + This code will cause the current time to be shown in `lblDisplay`. Because the interval of `timer1` was set to `1000`, this event will occur every thousand milliseconds, thus updating the current time every second. + +8. Modify the method to be overridable with the `virtual` keyword. For more information, see the "Inheriting from a User Control" section below. + + ```csharp + protected virtual void timer1_Tick(object sender, System.EventArgs e) + ``` + +9. On the **File** menu, click **Save All** to save the project. + +## Add Properties to the Composite Control + +Your clock control now encapsulates a control and a component, each with its own set of inherent properties. While the individual properties of these controls will not be accessible to subsequent users of your control, you can create and expose custom properties by writing the appropriate blocks of code. In the following procedure, you will add properties to your control that enable the user to change the color of the background and text. + +### To add a property to your composite control + +1. In **Solution Explorer**, right-click **ctlClock.cs**, and then click **View Code**. + + The **Code Editor** for your control opens. + +2. Locate the `public partial class ctlClock` statement. Beneath the opening brace (`{)`, type the following code. + + ```csharp + private Color colFColor; + private Color colBColor; + ``` + + These statements create the private variables that you will use to store the values for the properties you are about to create. + +3. Enter or paste the following code beneath the variable declarations from step 2. + + ```csharp + // Declares the name and type of the property. + public Color ClockBackColor + { + // Retrieves the value of the private variable colBColor. + get + { + return colBColor; + } + // Stores the selected value in the private variable colBColor, and + // updates the background color of the label control lblDisplay. + set + { + colBColor = value; + lblDisplay.BackColor = colBColor; + } + } + // Provides a similar set of instructions for the foreground color. + public Color ClockForeColor + { + get + { + return colFColor; + } + set + { + colFColor = value; + lblDisplay.ForeColor = colFColor; + } + } + ``` + + The preceding code makes two custom properties, `ClockForeColor` and `ClockBackColor`, available to subsequent users of this control. The `get` and `set` statements provide for storage and retrieval of the property value, as well as code to implement functionality appropriate to the property. + +4. On the **File** menu, click **Save All** to save the project. + +## Test the Control + +Controls are not stand-alone applications; they must be hosted in a container. Test your control's run-time behavior and exercise its properties with the **UserControl Test Container**. For more information, see [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md). + +### To test your control + +1. Press **F5** to build the project and run your control in the **UserControl Test Container**. + +2. In the test container's property grid, locate the `ClockBackColor` property, and then select the property to display the color palette. + +3. Choose a color by clicking it. + + The background color of your control changes to the color you selected. + +4. Use a similar sequence of events to verify that the `ClockForeColor` property is functioning as expected. + + In this section and the preceding sections, you have seen how components and Windows controls can be combined with code and packaging to provide custom functionality in the form of a composite control. You have learned to expose properties in your composite control, and how to test your control after it is complete. In the next section you will learn how to construct an inherited composite control using `ctlClock` as a base. + +## Inherit from a Composite Control + +In the previous sections, you learned how to combine Windows controls, components, and code into reusable composite controls. Your composite control can now be used as a base upon which other controls can be built. The process of deriving a class from a base class is called *inheritance*. In this section, you will create a composite control called `ctlAlarmClock`. This control will be derived from its parent control, `ctlClock`. You will learn to extend the functionality of `ctlClock` by overriding parent methods and adding new methods and properties. + +The first step in creating an inherited control is to derive it from its parent. This action creates a new control that has all of the properties, methods, and graphical characteristics of the parent control, but can also act as a base for the addition of new or modified functionality. + +### To create the inherited control + +1. In **Solution Explorer**, right-click **ctlClockLib**, point to **Add**, and then click **User Control**. + + The **Add New Item** dialog box opens. + +2. Select the **Inherited User Control** template. + +3. In the **Name** box, type `ctlAlarmClock.cs`, and then click **Add**. + + The **Inheritance Picker** dialog box appears. + +4. Under **Component Name**, double-click **ctlClock**. + +5. In **Solution Explorer**, browse through the current projects. + + > [!NOTE] + > A file called **ctlAlarmClock.cs** has been added to the current project. + +### Add the Alarm Properties + +Properties are added to an inherited control in the same way they are added to a composite control. You will now use the property declaration syntax to add two properties to your control: `AlarmTime`, which will store the value of the date and time the alarm is to go off, and `AlarmSet`, which will indicate whether the alarm is set. + +#### To add properties to your composite control + +1. In **Solution Explorer**, right-click **ctlAlarmClock**, and then click **View Code**. + +2. Locate the `public class` statement. Note that your control inherits from `ctlClockLib.ctlClock`. Beneath the opening brace (`{)` statement, type the following code. + + ```csharp + private DateTime dteAlarmTime; + private bool blnAlarmSet; + // These properties will be declared as public to allow future + // developers to access them. + public DateTime AlarmTime + { + get + { + return dteAlarmTime; + } + set + { + dteAlarmTime = value; + } + } + public bool AlarmSet + { + get + { + return blnAlarmSet; + } + set + { + blnAlarmSet = value; + } + } + ``` + +### Add to the Graphical Interface of the Control + +Your inherited control has a visual interface that is identical to the control it inherits from. It possesses the same constituent controls as its parent control, but the properties of the constituent controls will not be available unless they were specifically exposed. You may add to the graphical interface of an inherited composite control in the same manner as you would add to any composite control. To continue adding to your alarm clock's visual interface, you will add a label control that will flash when the alarm is sounding. + +#### To add the label control + +1. In **Solution Explorer**, right-click **ctlAlarmClock**, and then click **View Designer**. + + The designer for `ctlAlarmClock` opens in the main window. + +2. Click the display portion of the control, and view the Properties window. + + > [!NOTE] + > While all the properties are displayed, they are dimmed. This indicates that these properties are native to `lblDisplay` and cannot be modified or accessed in the Properties window. By default, controls contained in a composite control are `private`, and their properties are not accessible by any means. + + > [!NOTE] + > If you want subsequent users of your composite control to have access to its internal controls, declare them as `public` or `protected`. This will allow you to set and modify properties of controls contained within your composite control by using the appropriate code. + +3. Add a control to your composite control. + +4. Using the mouse, drag the control immediately beneath the display box. In the Properties window, set the following properties. + + |Property|Setting| + |--------------|-------------| + |**Name**|`lblAlarm`| + |**Text**|**Alarm!**| + |**TextAlign**|`MiddleCenter`| + |**Visible**|`false`| + +### Add the Alarm Functionality + +In the previous procedures, you added properties and a control that will enable alarm functionality in your composite control. In this procedure, you will add code to compare the current time to the alarm time and, if they are the same, to flash an alarm. By overriding the `timer1_Tick` method of `ctlClock` and adding additional code to it, you will extend the capability of `ctlAlarmClock` while retaining all of the inherent functionality of `ctlClock`. + +#### To override the timer1_Tick method of ctlClock + +1. In the **Code Editor**, locate the `private bool blnAlarmSet;` statement. Immediately beneath it, add the following statement. + + ```csharp + private bool blnColorTicker; + ``` + +2. In the **Code Editor**, locate the closing brace (`})` at the end of the class. Just before the brace, add the following code. + + ```csharp + protected override void timer1_Tick(object sender, System.EventArgs e) + { + // Calls the Timer1_Tick method of ctlClock. + base.timer1_Tick(sender, e); + // Checks to see if the alarm is set. + if (AlarmSet == false) + return; + else + // If the date, hour, and minute of the alarm time are the same as + // the current time, flash an alarm. + { + if (AlarmTime.Date == DateTime.Now.Date && AlarmTime.Hour == + DateTime.Now.Hour && AlarmTime.Minute == DateTime.Now.Minute) + { + // Sets lblAlarmVisible to true, and changes the background color based on + // the value of blnColorTicker. The background color of the label + // will flash once per tick of the clock. + lblAlarm.Visible = true; + if (blnColorTicker == false) + { + lblAlarm.BackColor = Color.Red; + blnColorTicker = true; + } + else + { + lblAlarm.BackColor = Color.Blue; + blnColorTicker = false; + } + } + else + { + // Once the alarm has sounded for a minute, the label is made + // invisible again. + lblAlarm.Visible = false; + } + } + } + ``` + + The addition of this code accomplishes several tasks. The `override` statement directs the control to use this method in place of the method that was inherited from the base control. When this method is called, it calls the method it overrides by invoking the `base.timer1_Tick` statement, ensuring that all of the functionality incorporated in the original control is reproduced in this control. It then runs additional code to incorporate the alarm functionality. A flashing label control will appear when the alarm occurs. + + Your alarm clock control is almost complete. The only thing that remains is to implement a way to turn it off. To do this, you will add code to the `lblAlarm_Click` method. + +#### To implement the shutoff method + +1. In **Solution Explorer**, right-click **ctlAlarmClock.cs**, and then click **View Designer**. + + The designer opens. + +2. Add a button to the control. Set the properties of the button as follows. + + |Property|Value| + |--------------|-----------| + |**Name**|`btnAlarmOff`| + |**Text**|**Disable Alarm**| + +3. In the designer, double-click **btnAlarmOff**. + + The **Code Editor** opens to the `private void btnAlarmOff_Click` line. + +4. Modify this method so that it resembles the following code. + + ```csharp + private void btnAlarmOff_Click(object sender, System.EventArgs e) + { + // Turns off the alarm. + AlarmSet = false; + // Hides the flashing label. + lblAlarm.Visible = false; + } + ``` + +5. On the **File** menu, click **Save All** to save the project. + +### Use the Inherited Control on a Form + +You can test your inherited control the same way you tested the base class control, `ctlClock`: Press **F5** to build the project and run your control in the **UserControl Test Container**. For more information, see [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md). + +To put your control to use, you will need to host it on a form. As with a standard composite control, an inherited composite control cannot stand alone and must be hosted in a form or other container. Since `ctlAlarmClock` has a greater depth of functionality, additional code is required to test it. In this procedure, you will write a simple program to test the functionality of `ctlAlarmClock`. You will write code to set and display the `AlarmTime` property of `ctlAlarmClock`, and will test its inherent functions. + +#### To build and add your control to a test form + +1. In **Solution Explorer**, right-click **ctlClockLib**, and then click **Build**. + +2. Add a new **Windows Forms Application** project to the solution, and name it **Test**. + +3. In **Solution Explorer**, right-click the **References** node for your test project. Click **Add Reference** to display the **Add Reference** dialog box. Click the tab labeled **Projects**. Your `ctlClockLib` project will be listed under **Project Name**. Double-click the project to add the reference to the test project. + +4. In **Solution Explorer**, right-click **Test**, and then click **Build**. + +5. In the **Toolbox**, expand the **ctlClockLib Components** node. + +6. Double-click **ctlAlarmClock** to add a copy of `ctlAlarmClock` to your form. + +7. In the **Toolbox**, locate and double-click **DateTimePicker** to add a control to your form, and then add a control by double-clicking **Label**. + +8. Use the mouse to position the controls in a convenient place on the form. + +9. Set the properties of these controls in the following manner. + + |Control|Property|Value| + |-------------|--------------|-----------| + |`label1`|**Text**|`(blank space)`| + ||**Name**|`lblTest`| + |`dateTimePicker1`|**Name**|`dtpTest`| + ||**Format**|| + +10. In the designer, double-click **dtpTest**. + + The **Code Editor** opens to `private void dtpTest_ValueChanged`. + +11. Modify the code so that it resembles the following. + + ```csharp + private void dtpTest_ValueChanged(object sender, System.EventArgs e) + { + ctlAlarmClock1.AlarmTime = dtpTest.Value; + ctlAlarmClock1.AlarmSet = true; + lblTest.Text = "Alarm Time is " + + ctlAlarmClock1.AlarmTime.ToShortTimeString(); + } + ``` + +12. In **Solution Explorer**, right-click **Test**, and then click **Set as StartUp Project**. + +13. On the **Debug** menu, click **Start Debugging**. + + The test program starts. Note that the current time is updated in the `ctlAlarmClock` control, and that the starting time is shown in the control. + +14. Click the where the minutes of the hour are displayed. + +15. Using the keyboard, set a value for minutes that is one minute greater than the current time shown by `ctlAlarmClock`. + + The time for the alarm setting is shown in `lblTest`. Wait for the displayed time to reach the alarm setting time. When the displayed time reaches the time to which the alarm is set, the `lblAlarm` will flash. + +16. Turn off the alarm by clicking `btnAlarmOff`. You may now reset the alarm. + +This article has covered a number of key concepts. You have learned to create a composite control by combining controls and components into a composite control container. You have learned to add properties to your control, and to write code to implement custom functionality. In the last section, you learned to extend the functionality of a given composite control through inheritance, and to alter the functionality of host methods by overriding those methods. + +## See also + +- [Varieties of Custom Controls](varieties-of-custom-controls.md) +- [How to: Display a Control in the Choose Toolbox Items Dialog Box](how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md) +- [Walkthrough: Inheriting from a Windows Forms Control with Visual C#](walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-automatically-populating-the-toolbox-with-custom-components.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-automatically-populating-the-toolbox-with-custom-components.md new file mode 100644 index 0000000000..315e4a8954 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-automatically-populating-the-toolbox-with-custom-components.md @@ -0,0 +1,89 @@ +--- +title: "Walkthrough: Automatically Populating the Toolbox with Custom Components" +ms.date: "03/30/2017" +helpviewer_keywords: + - "IToolboxService interface" + - "Toolbox [Windows Forms], populating" + - "custom components [Windows Forms], adding to Toolbox" +ms.assetid: 2fa1e3e8-6b9f-42b2-97c0-2be57444dba4 +--- +# Walkthrough: Automatically Populating the Toolbox with Custom Components + +If your components are defined by a project in the currently open solution, they will automatically appear in the **Toolbox**, with no action required by you. You can also manually populate the **Toolbox** with your custom components by using the [Choose Toolbox Items Dialog Box (Visual Studio)](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/dyca0t6t(v=vs.100)), but the **Toolbox** takes account of items in your solution's build outputs with all the following characteristics: + +- Implements ; + +- Does not have set to `false`; + +- Does not have set to `false`. + +> [!NOTE] +> The **Toolbox** does not follow reference chains, so it won't display items that are not built by a project in your solution. + +This walkthrough demonstrates how a custom component automatically appears in the **Toolbox** once the component is built. Tasks illustrated in this walkthrough include: + +- Creating a Windows Forms project. + +- Creating a custom component. + +- Creating an instance of a custom component. + +- Unloading and reloading a custom component. + +When you are finished, you will see that the **Toolbox** is populated with a component that you have created. + +## Create the project + +1. In Visual Studio, create a Windows-based application project called `ToolboxExample` (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. Add a new component to the project. Call it `DemoComponent`. + + For more information, see [How to: Add New Project Items](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/w0572c5b(v=vs.100)). + +3. Build the project. + +4. From the **Tools** menu, click the **Options** item. Click **General** under the **Windows Forms Designer** item and ensure that the **AutoToolboxPopulate** option is set to **True**. + +## Create an instance of a custom component + +The next step is to create an instance of the custom component on the form. Because the **Toolbox** automatically accounts for the new component, this is as easy as creating any other component or control. + +1. Open the project's form in the **Forms Designer**. + +2. In the **Toolbox**, click the new tab called **ToolboxExample Components**. + + Once you click the tab, you will see **DemoComponent**. + + > [!NOTE] + > For performance reasons, components in the auto-populated area of the **Toolbox** do not display custom bitmaps, and the is not supported. To display an icon for a custom component in the **Toolbox**, use the **Choose Toolbox Items** dialog box to load your component. + +3. Drag your component onto your form. + + An instance of the component is created and added to the **Component Tray**. + +## Unload and reload a custom component + +The **Toolbox** takes account of the components in each loaded project, and when a project is unloaded, it removes references to the project's components. + +1. Unload the project from the solution. + + For more information about unloading projects, see [How to: Unload and Reload Projects](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/tt479x1t(v=vs.100)). If you are prompted to save, choose **Yes**. + +2. Add a new **Windows Application** project to the solution. Open the form in the **Designer**. + + The **ToolboxExample Components** tab from the previous project is now gone. + +3. Reload the `ToolboxExample` project. + + The **ToolboxExample Components** tab now reappears. + +## Next steps + +This walkthrough demonstrates that the **Toolbox** takes account of a project's components, but the **Toolbox** is also takes account of controls. Experiment with your own custom controls by adding and removing control projects from your solution. + +## See also + +- [General, Windows Forms Designer, Options Dialog Box](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/5aazxs78(v=vs.100)) +- [How to: Manipulate Toolbox Tabs](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/66kwe227(v=vs.100)) +- [Choose Toolbox Items Dialog Box (Visual Studio)](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/dyca0t6t(v=vs.100)) +- [Putting Controls on Windows Forms](putting-controls-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-a-professionally-styled-toolstrip-control.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-a-professionally-styled-toolstrip-control.md new file mode 100644 index 0000000000..18ab2f9abe --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-a-professionally-styled-toolstrip-control.md @@ -0,0 +1,177 @@ +--- +title: "Walkthrough: Creating a Professionally Styled ToolStrip Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ToolStripProfessionalRenderer class [Windows Forms]" + - "ToolStripRenderer class [Windows Forms]" + - "toolbars [Windows Forms], walkthroughs" + - "ToolStrip control [Windows Forms], creating professionally styled controls" +ms.assetid: b52339ae-f1d3-494e-996e-eb455614098a +--- +# Walkthrough: Creating a Professionally Styled ToolStrip Control + +You can give your application’s controls a professional appearance and behavior by writing your own class derived from the type. + +This walkthrough demonstrates how to use controls to create a composite control that resembles the **Navigation Pane** provided by Microsoft® Outlook®. The following tasks are illustrated in this walkthrough: + +- Creating a Windows Control Library project. + +- Designing the StackView Control. + +- Implementing a Custom Renderer. + +When you are finished, you will have a reusable custom client control with the professional appearance of a Microsoft Office® XP control. + +To copy the code in this topic as a single listing, see [How to: Create a Professionally Styled ToolStrip Control](how-to-create-a-professionally-styled-toolstrip-control.md). + +## Prerequisites + +You'll need Visual Studio to complete this walkthrough. + +## Create the control library project + +1. In Visual Studio, create a new Windows Control Library project named `StackViewLibrary`. + +2. In **Solution Explorer**, delete the project's default control by deleting the source file named "UserControl1.cs" or "UserControl1.vb", depending on your language of choice. + + For more information, see [How to: Remove, Delete, and Exclude Items](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/0ebzhwsk(v=vs.100)). + +3. Add a new item to the **StackViewLibrary** project. Give the new source file a base name of `StackView`. + +## Design the StackView control + +The `StackView` control is a composite control with one child control. For more information about composite controls, see [Varieties of Custom Controls](varieties-of-custom-controls.md). + +1. From the **Toolbox**, drag a control to the design surface. + +2. In the **Properties** window, set the control's properties according to the following table. + + |Property|Value| + |--------------|-----------| + |Name|`stackStrip`| + |CanOverflow|`false`| + |Dock|| + |Font|`Tahoma, 10pt, style=Bold`| + |GripStyle|| + |LayoutStyle|| + |Padding|`0, 7, 0, 0`| + |RenderMode|| + +3. In the Windows Forms Designer, click the control's **Add** button and add a to the `stackStrip` control. + +4. In the **Properties** window, set the control's properties according to the following table. + + |Property|Value| + |--------------|-----------| + |Name|`mailStackButton`| + |CheckOnClick|true| + |CheckState|| + |DisplayStyle|| + |ImageAlign|| + |ImageScaling|| + |ImageTransparentColor|`238, 238, 238`| + |Margin|`0, 0, 0, 0`| + |Padding|`3, 3, 3, 3`| + |Text|**Mail**| + |TextAlign|| + +5. Repeat step 7 for three more controls. + + Name the controls `calendarStackButton`, `contactsStackButton`, and `tasksStackButton`. Set the value of the property to **Calendar**, **Contacts**, and **Tasks**, respectively. + +## Handle events + +Two events are important to make the `StackView` control behave correctly. Handle the event to position the control correctly. Handle the event for each to give the `StackView` control state behavior similar to the control. + +1. In the Windows Forms Designer, select the `StackView` control. + +2. In the **Properties** window, click **Events**. + +3. Double-click the Load event to generate the `StackView_Load` event handler. + +4. In the `StackView_Load` event handler, copy and paste the following code. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#3)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#3)] + +5. In the Windows Forms Designer, select the `mailStackButton` control. + +6. In the **Properties** window, click **Events**. + +7. Double-click the Click event. + + The Windows Forms Designer generates the `mailStackButton_Click` event handler. + +8. Rename the `mailStackButton_Click` event handler to `stackButton_Click`. + + For more information, see [Rename a code symbol refactoring](/visualstudio/ide/reference/rename). + +9. Insert the following code into the `stackButton_Click` event handler. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#4)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#4)] + +10. In the Windows Forms Designer, select the `calendarStackButton` control. + +11. In the **Properties** window, set the Click event to the `stackButton_Click` event handler. + +12. Repeat steps 10 and 11 for the `contactsStackButton` and `tasksStackButton` controls. + +## Define icons + +Each `StackView` button has an associated icon. For convenience, each icon is represented as a Base64-encoded string, which is deserialized before a is created from it. In a production environment, you store bitmap data as a resource, and your icons appear in the Windows Forms Designer. For more information, see [How to: Add Background Images to Windows Forms](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/dff9f95f(v=vs.100)). + +1. In the Code Editor, insert the following code into the `StackView` class definition. This code initializes the bitmaps for the icons. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#2)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#2)] + +2. Add a call to the `InitializeImages` method in the `StackView` class constructor. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#5)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#5)] + +## Implement a custom renderer + +You can customize most elements of the `StackView` control my implementing a class that derives from the class. In this procedure, you will implement a class that customizes the grip and draws gradient backgrounds for the controls. + +1. Insert the following code into the `StackView` control definition. + + This is the definition for the `StackRenderer` class, which overrides the , , and methods to produce a custom appearance. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#10)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#10)] + +2. In the `StackView` control's constructor, create a new instance of the `StackRenderer` class and assign this instance to the `stackStrip` control's property. + + [!code-csharp[System.Windows.Forms.ToolStrip.StackView#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs#5)] + [!code-vb[System.Windows.Forms.ToolStrip.StackView#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb#5)] + +## Test the StackView control + +The `StackView` control derives from the class. Therefore, you can test the control with the **UserControl Test Container**. For more information, see [How to: Test the Run-Time Behavior of a UserControl](how-to-test-the-run-time-behavior-of-a-usercontrol.md). + +1. Press **F5** to build the project and start the **UserControl Test Container**. + +2. Move the pointer over the buttons of the `StackView` control, and then click a button to see the appearance of its selected state. + +## Next steps + +In this walkthrough, you have created a reusable custom client control with the professional appearance of an Office XP control. You can use the family of controls for many other purposes: + +- Create shortcut menus for your controls with . For more information, see [ContextMenu Component Overview](contextmenu-component-overview-windows-forms.md). + +- Create a form with an automatically populated standard menu. For more information, see [Walkthrough: Providing Standard Menu Items to a Form](walkthrough-providing-standard-menu-items-to-a-form.md). + +- Create a multiple document interface (MDI) form with docking controls. For more information, see [How to: Create an MDI Form with Menu Merging and ToolStrip Controls](how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md). + +## See also + +- +- +- +- [ToolStrip Control](toolstrip-control-windows-forms.md) +- [How to: Provide Standard Menu Items to a Form](how-to-provide-standard-menu-items-to-a-form.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md new file mode 100644 index 0000000000..e84d36005f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md @@ -0,0 +1,195 @@ +--- +title: "Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "toolbars [Windows Forms]" + - "ToolStripPanel control [Windows Forms]" + - "MDI [Windows Forms], creating forms" + - "multiple document interface forms" + - "MDI forms" + - "ToolStrip control [Windows Forms]" + - "MDI forms [Windows Forms], creating" + - "MDI forms [Windows Forms], walkthroughs" +ms.assetid: fbab4221-74af-42d0-bbf4-3c97f7b2e544 +--- +# Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls + +The namespace supports multiple document interface (MDI) applications, and the control supports menu merging. MDI forms can also controls. + +This walkthrough demonstrates how to use controls with an MDI form. The form also supports menu merging with child menus. The following tasks are illustrated in this walkthrough: + +- Creating a Windows Forms project. + +- Creating the main menu for your form. The actual name of the menu will vary. + +- Adding the control to the **Toolbox**. + +- Creating a child form. + +- Arranging controls by z-order. + +When you are finished, you will have an MDI form that supports menu merging and movable controls. + +To copy the code in this topic as a single listing, see [How to: Create an MDI Form with Menu Merging and ToolStrip Controls](how-to-create-an-mdi-form-with-menu-merging-and-toolstrip-controls.md). + +## Prerequisites + +You'll need Visual Studio to complete this walkthrough. + +## Create the project + +1. In Visual Studio, create a Windows Application project called **MdiForm** (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. In the Windows Forms Designer, select the form. + +3. In the Properties window, set the value of the to `true`. + +## Create the main menu + +The parent MDI form contains the main menu. The main menu has one menu item named **Window**. With the **Window** menu item, you can create child forms. Menu items from child forms are merged into the main menu. + +1. From the **Toolbox**, drag a control onto the form. + +2. Add a to the control and name it **Window**. + +3. Select the control. + +4. In the Properties window, set the value of the property to `ToolStripMenuItem1`. + +5. Add a subitem to the **Window** menu item, and then name the subitem **New**. + +6. In the Properties window, click **Events**. + +7. Double-click the event. + + The Windows Forms Designer generates an event handler for the event. + +8. Insert the following code into the event handler. + + [!code-csharp[System.Windows.Forms.ToolStrip.MdiForm#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.ToolStrip.MdiForm#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/VB/Form1.vb#2)] + +## Add the ToolStripPanel control to the Toolbox + +When you use controls with an MDI form you must have the control. You must add the control to the **Toolbox** to build your MDI form in the Windows Forms Designer. + +1. Open the **Toolbox**, and then click the **All Windows Forms** tab to show the available Windows Forms controls. + +2. Right-click to open the shortcut menu, and select **Choose Items**. + +3. In the **Choose Toolbox Items** dialog box, scroll down the **Name** column until you find **ToolStripPanel**. + +4. Select the check box by **ToolStripPanel**, and then click **OK**. + + The control appears in the **Toolbox**. + +## Create a child form + +In this procedure, you will define a separate child form class that has its own control. The menu items for this form are merged with those of the parent form. + +1. Add a new form named `ChildForm` to the project. + + For more information, see [How to: Add Windows Forms to a Project](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/y2xxdce3(v=vs.100)). + +2. From the **Toolbox**, drag a control onto the child form. + +3. Click the control's designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)), and then select **Edit Items**. + +4. In the **Items Collection Editor** dialog box, add a new named **ChildMenuItem** to the child menu. + + For more information, see [ToolStrip Items Collection Editor](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/ms233643(v=vs.100)). + +## Test the form + +1. Press **F5** to compile and run your form. + +2. Click the **Window** menu item to open the menu, and then click **New**. + + A new child form is created in the form's MDI client area. The child form's menu is merged with the main menu. + +3. Close the child form. + + The child form's menu is removed from the main menu. + +4. Click **New** several times. + + The child forms are automatically listed under the **Window** menu item because the control's property is assigned. + +## Add ToolStrip support + +In this procedure, you will add four controls to the MDI parent form. Each control is added inside a control, which is docked to the edge of the form. + +1. From the **Toolbox**, drag a control onto the form. + +2. With the control selected, double-click the control in the **Toolbox**. + + A control is created in the control. + +3. Select the control. + +4. In the Properties window, change the value of the control's property to . + + The control docks to the left side of the form, underneath the main menu. The MDI client area resizes to fit the control. + +5. Repeat steps 1 through 4. + + Dock the new control to the top of the form. + + The control is docked underneath the main menu, but to the right of the first control. This step illustrates the importance of z-order in correctly positioning controls. + +6. Repeat steps 1 through 4 for two more controls. + + Dock the new controls to the right and bottom of the form. + +## Arrange ToolStripPanel controls by Z-order + +The position of a docked control on your MDI form is determined by the control's position in the z-order. You can easily arrange the z-order of your controls in the Document Outline window. + +1. In the **View** menu, click **Other Windows**, and then click **Document Outline**. + + The arrangement of your controls from the previous procedure is nonstandard. This is because the z-order is not correct. Use the Document Outline window to change the z-order of the controls. + +2. In the Document Outline window, select **ToolStripPanel4**. + +3. Click the down-arrow button repeatedly, until **ToolStripPanel4** is at the bottom of the list. + + The **ToolStripPanel4** control is docked to the bottom of the form, underneath the other controls. + +4. Select **ToolStripPanel2**. + +5. Click the down-arrow button one time to position the control third in the list. + + The **ToolStripPanel2** control is docked to the top of the form, underneath the main menu and above the other controls. + +6. Select various controls in the **Document Outline** window and move them to different positions in the z-order. Note the effect of the z-order on the placement of docked controls. Use CTRL-Z or **Undo** on the **Edit** menu to undo your changes. + +## Checkpoint - test your form + +1. Press **F5** to compile and run your form. + +2. Click the grip of a control and drag the control to different positions on the form. + + You can drag a control from one control to another. + +## Next steps + +In this walkthrough, you have created an MDI parent form with controls and menu merging. You can use the family of controls for many other purposes: + +- Create shortcut menus for your controls with . For more information, see [ContextMenu Component Overview](contextmenu-component-overview-windows-forms.md). + +- Created a form with an automatically populated standard menu. For more information, see [Walkthrough: Providing Standard Menu Items to a Form](walkthrough-providing-standard-menu-items-to-a-form.md). + +- Give your controls a professional appearance. For more information, see [How to: Set the ToolStrip Renderer for an Application](how-to-set-the-toolstrip-renderer-for-an-application.md). + +## See also + +- +- +- +- [How to: Create MDI Parent Forms](../advanced/how-to-create-mdi-parent-forms.md) +- [How to: Create MDI Child Forms](../advanced/how-to-create-mdi-child-forms.md) +- [How to: Insert a MenuStrip into an MDI Drop-Down Menu](how-to-insert-a-menustrip-into-an-mdi-drop-down-menu-windows-forms.md) +- [ToolStrip Control](toolstrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-an-unbound-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-an-unbound-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..bfb230f8d4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-creating-an-unbound-windows-forms-datagridview-control.md @@ -0,0 +1,94 @@ +--- +title: Create an Unbound DataGridView Control +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data [Windows Forms], displaying without binding to data source" + - "DataGridView control [Windows Forms], unbound data" + - "DataGridView control [Windows Forms], displaying data without binding to a data source" + - "data [Windows Forms], unbound" + - "walkthroughs [Windows Forms], DataGridView control" +ms.assetid: 5a8d6afa-1b4b-4b24-8db8-501086ffdebe +--- +# Walkthrough: Creating an Unbound Windows Forms DataGridView Control +You may frequently want to display tabular data that does not originate from a database. For example, you may want to show the contents of a two-dimensional array of strings. The class provides an easy and highly customizable way to display data without binding to a data source. This walkthrough shows how to populate a control and manage the addition and deletion of rows in "unbound" mode. By default, the user can add new rows. To prevent row addition, set the property is `false`. + + To copy the code in this topic as a single listing, see [How to: Create an Unbound Windows Forms DataGridView Control](how-to-create-an-unbound-windows-forms-datagridview-control.md). + +## Creating the Form + +#### To use an unbound DataGridView control + +1. Create a class that derives from and contains the following variable declarations and `Main` method. + + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#01](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#01)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#01](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#01)] + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#02](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#02)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#02](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#02)] + +2. Implement a `SetupLayout` method in your form's class definition to set up the form's layout. + + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#20)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#20)] + +3. Create a `SetupDataGridView` method to set up the columns and properties. + + This method first adds the control to the form's collection. Next, the number of columns to be displayed is set using the property. The default style for the column headers is set by setting the , , and properties of the returned by the property. + + Layout and appearance properties are set, and then the column names are assigned. When this method exits, the control is ready to be populated. + + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#30)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#30)] + +4. Create a `PopulateDataGridView` method to add rows to the control. + + Each row represents a song and its associated information. + + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#40](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#40)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#40](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#40)] + +5. With the utility methods in place, you can attach event handlers. + + You will handle the **Add** and **Delete** buttons' events, the form's event, and the control's event. + + When the **Add** button's event is raised, a new, empty row is added to the . + + When the **Delete** button's event is raised, the selected row is deleted, unless it is the row for new records, which enables the user add new rows. This row is always the last row in the control. + + When the form's event is raised, the `SetupLayout`, `SetupDataGridView`, and `PopulateDataGridView` utility methods are called. + + When the event is raised, each cell in the `Date` column is formatted as a long date, unless the cell's value cannot be parsed. + + [!code-csharp[System.Windows.Forms.DataGridViewSimpleUnbound#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewSimpleUnbound#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb#10)] + +## Testing the Application + You can now test the form to make sure it behaves as expected. + +#### To test the form + +- Press F5 to run the application. + + You will see a control that displays the songs listed in `PopulateDataGridView`. You can add new rows with the **Add Row** button, and you can delete selected rows with the **Delete Row** button. The unbound control is the data store, and its data is independent of any external source, such as a or an array. + +## Next Steps + This application gives you a basic understanding of the control's capabilities. You can customize the appearance and behavior of the control in several ways: + +- Change border and header styles. For more information, see [How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control](change-the-border-and-gridline-styles-in-the-datagrid.md). + +- Enable or restrict user input to the control. For more information, see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md), and [How to: Make Columns Read-Only in the Windows Forms DataGridView Control](how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md). + +- Check user input for database-related errors. For more information, see [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md). + +- Handle very large data sets using virtual mode. For more information, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +- Customize the appearance of cells. For more information, see [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) and [How to: Set Default Cell Styles for the Windows Forms DataGridView Control](how-to-set-default-cell-styles-for-the-windows-forms-datagridview-control.md). + +## See also + +- +- [Displaying Data in the Windows Forms DataGridView Control](displaying-data-in-the-windows-forms-datagridview-control.md) +- [How to: Create an Unbound Windows Forms DataGridView Control](how-to-create-an-unbound-windows-forms-datagridview-control.md) +- [Data Display Modes in the Windows Forms DataGridView Control](data-display-modes-in-the-windows-forms-datagridview-control.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-debugging-custom-windows-forms-controls-at-design-time.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-debugging-custom-windows-forms-controls-at-design-time.md new file mode 100644 index 0000000000..20b276fcad --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-debugging-custom-windows-forms-controls-at-design-time.md @@ -0,0 +1,148 @@ +--- +title: Debug Custom Controls at Design Time +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "debugging [Visual Studio], walkthroughs" + - "custom controls [Windows Forms], walkthroughs" + - "visual editors" + - "debugging [Visual Studio], Windows Forms" + - "custom controls [Windows Forms], debugging" + - "designers" + - "controls [Windows Forms], debugging" + - "walkthroughs [Windows Forms], debugging" + - "design-time debugging" +ms.assetid: 1fd83ccd-3798-42fc-85a3-6cba99467387 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Debug Custom Windows Forms Controls at Design Time + +When you create a custom control, you will often find it necessary to debug its design-time behavior. This is especially true if you are authoring a custom designer for your custom control. For details, see [Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md). + +You can debug your custom controls using Visual Studio, just as you would debug any other .NET Framework classes. The difference is that you will debug a separate instance of Visual Studio that is running your custom control's code. + +## Create the project + +The first step is to create the application project. You will use this project to build the application that hosts the custom control. + +In Visual Studio, create a Windows Application project, and name it **DebuggingExample**. + +## Create the control library project + +1. Add a **Windows Control Library** project to the solution. + +2. Add a new **UserControl** item to the DebugControlLibrary project. Name it **DebugControl**. + +3. In **Solution Explorer**, delete the project's default control by deleting the code file with a base name of UserControl1. + +4. Build the solution. + +## Checkpoint + +At this point, you will be able to see your custom control in the **Toolbox**. + +To check your progress, find the new tab called **DebugControlLibrary Components** and click to select it. When it opens, you will see your control listed as **DebugControl** with the default icon beside it. + +## Add a property to your custom control + +To demonstrate that your custom control's code is running at design-time, you will add a property and set a breakpoint in the code that implements the property. + +1. Open **DebugControl** in the **Code Editor**. Add the following code to the class definition: + + ```vb + Private demoStringValue As String = Nothing + + Public Property DemoString() As String + + Get + Return Me.demoStringValue + End Get + + Set(ByVal value As String) + Me.demoStringValue = value + End Set + + End Property + ``` + + ```csharp + private string demoStringValue = null; + [Browsable(true)] + public string DemoString + { + get + { + return this.demoStringValue; + } + set + { + demoStringValue = value; + } + } + ``` + +2. Build the solution. + +## Add your custom control to the host form + +To debug the design-time behavior of your custom control, you will place an instance of the custom control class on a host form. + +1. In the "DebuggingExample" project, open Form1 in the **Windows Forms Designer**. + +2. In the **Toolbox**, open the **DebugControlLibrary Components** tab and drag a **DebugControl** instance onto the form. + +3. Find the `DemoString` custom property in the **Properties** window. Note that you can change its value as you would any other property. Also note that when the `DemoString` property is selected, the property's description string appears at the bottom of the **Properties** window. + +## Set up the project for design-time debugging + +To debug your custom control's design-time behavior, you will debug a separate instance of Visual Studio that is running your custom control's code. + +1. Right-click on the **DebugControlLibrary** project in the **Solution Explorer** and select **Properties**. + +2. In the **DebugControlLibrary** property sheet, select the **Debug** tab. + + In the **Start Action** section, select **Start external program**. You will be debugging a separate instance of Visual Studio, so click the ellipsis (![The Ellipsis button (...) in the Properties window of Visual Studio](./media/visual-studio-ellipsis-button.png)) button to browse for the Visual Studio IDE. The name of the executable file is **devenv.exe**, and if you installed to the default location, its path is *%ProgramFiles(x86)%\Microsoft Visual Studio\2019\\\\Common7\IDE*. + +3. Select **OK** to close the dialog box. + +4. Right-click the **DebugControlLibrary** project and select **Set as StartUp Project** to enable this debugging configuration. + +## Debug your custom control at design time + +Now you are ready to debug your custom control as it runs in design mode. When you start the debugging session, a new instance of Visual Studio will be created, and you will use it to load the "DebuggingExample" solution. When you open Form1 in the **Forms Designer**, an instance of your custom control will be created and will start running. + +1. Open the **DebugControl** source file in the **Code Editor** and place a breakpoint on the `Set` accessor of the `DemoString` property. + +2. Press **F5** to start the debugging session. A new instance of Visual Studio is created. You can distinguish between the instances in two ways: + + - The debugging instance has the word **Running** in its title bar + + - The debugging instance has the **Start** button on its **Debug** toolbar disabled + + Your breakpoint is set in the debugging instance. + +3. In the new instance of Visual Studio, open the "DebuggingExample" solution. You can easily find the solution by selecting **Recent Projects** from the **File** menu. The "DebuggingExample.sln" solution file will be listed as the most recently used file. + +4. Open Form1 in the **Forms Designer** and select the **DebugControl** control. + +5. Change the value of the `DemoString` property. When you commit the change, the debugging instance of Visual Studio acquires focus and execution stops at your breakpoint. You can single-step through the property accessor just as your would any other code. + +6. To stop debugging, exit the hosted instance of Visual Studio or select the **Stop Debugging** button in the debugging instance. + +## Next steps + +Now that you can debug your custom controls at design time, there are many possibilities for expanding your control's interaction with the Visual Studio IDE. + +- You can use the property of the class to write code that will only execute at design time. For details, see . + +- There are several attributes you can apply to your control's properties to manipulate your custom control's interaction with the designer. You can find these attributes in the namespace. + +- You can write a custom designer for your custom control. This gives you complete control over the design experience using the extensible designer infrastructure exposed by Visual Studio. For details, see [Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md). + +## See also + +- [Walkthrough: Creating a Windows Forms Control That Takes Advantage of Visual Studio Design-Time Features](creating-a-wf-control-design-time-features.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-implementing-a-form-that-uses-a-background-operation.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-implementing-a-form-that-uses-a-background-operation.md new file mode 100644 index 0000000000..08e6c875ca --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-implementing-a-form-that-uses-a-background-operation.md @@ -0,0 +1,162 @@ +--- +title: "Walkthrough: Implementing a Form That Uses a Background Operation" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "threading [Windows Forms], forms" + - "BackgroundWorker component" + - "background tasks" + - "forms [Windows Forms], multithreading" + - "threading [Windows Forms], walkthroughs" + - "forms [Windows Forms], background operations" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: 4691b796-9200-471a-89c3-ba4c7cc78c03 +--- +# Walkthrough: Implementing a Form That Uses a Background Operation + +If you have an operation that will take a long time to complete, and you do not want your user interface (UI) to stop responding or to block, you can use the class to execute the operation on another thread. + +This walkthrough illustrates how to use the class to perform time-consuming computations "in the background," while the user interface remains responsive. When you are through, you will have an application that computes Fibonacci numbers asynchronously. Even though computing a large Fibonacci number can take a noticeable amount of time, the main UI thread will not be interrupted by this delay, and the form will be responsive during the calculation. + +Tasks illustrated in this walkthrough include: + +- Creating a Windows-based Application + +- Creating a in Your Form + +- Adding Asynchronous Event Handlers + +- Adding Progress Reporting and Support for Cancellation + +For a complete listing of the code used in this example, see [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md). + +## Create a form that uses a background operation + +1. In Visual Studio, create a Windows-based application project called `BackgroundWorkerExample` (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. In **Solution Explorer**, right-click **Form1** and select **Rename** from the shortcut menu. Change the file name to `FibonacciCalculator`. Click the **Yes** button when you are asked if you want to rename all references to the code element '`Form1`'. + +3. Drag a control from the **Toolbox** onto the form. Set the property to `1` and the property to `91`. + +4. Add two controls to the form. + +5. Rename the first control `startAsyncButton` and set the property to `Start Async`. Rename the second control `cancelAsyncButton`, and set the property to `Cancel Async`. Set its property to `false`. + +6. Create an event handler for both of the controls' events. For details, see [How to: Create Event Handlers Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/zwwsdtbk(v=vs.100)). + +7. Drag a control from the **Toolbox** onto the form and rename it `resultLabel`. + +8. Drag a control from the **Toolbox** onto the form. + +## Create a BackgroundWorker with the Designer + +You can create the for your asynchronous operation using the **Windows** **Forms Designer**. + +From the **Components** tab of the **Toolbox**, drag a onto the form. + +## Add asynchronous event handlers + +You are now ready to add event handlers for the component's asynchronous events. The time-consuming operation that will run in the background, which computes Fibonacci numbers, is called by one of these event handlers. + +1. In the **Properties** window, with the component still selected, click the **Events** button. Double-click the and events to create event handlers. For more information about how to use event handlers, see [How to: Create Event Handlers Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/zwwsdtbk(v=vs.100)). + +2. Create a new method, called `ComputeFibonacci`, in your form. This method does the actual work, and it will run in the background. This code demonstrates the recursive implementation of the Fibonacci algorithm, which is notably inefficient, taking exponentially longer time to complete for larger numbers. It is used here for illustrative purposes, to show an operation that can introduce long delays in your application. + + [!code-cpp[System.ComponentModel.BackgroundWorker#10](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#10)] + [!code-csharp[System.ComponentModel.BackgroundWorker#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#10)] + [!code-vb[System.ComponentModel.BackgroundWorker#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#10)] + +3. In the event handler, add a call to the `ComputeFibonacci` method. Take the first parameter for `ComputeFibonacci` from the property of the . The and parameters will be used later for progress reporting and cancellation support. Assign the return value from `ComputeFibonacci` to the property of the . This result will be available to the event handler. + + > [!NOTE] + > The event handler does not reference the `backgroundWorker1` instance variable directly, as this would couple this event handler to a specific instance of . Instead, a reference to the that raised this event is recovered from the `sender` parameter. This is important when the form hosts more than one . It is also important not to manipulate any user-interface objects in your event handler. Instead, communicate to the user interface through the events. + + [!code-cpp[System.ComponentModel.BackgroundWorker#5](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#5)] + [!code-csharp[System.ComponentModel.BackgroundWorker#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#5)] + [!code-vb[System.ComponentModel.BackgroundWorker#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#5)] + +4. In the `startAsyncButton` control's event handler, add the code that starts the asynchronous operation. + + [!code-cpp[System.ComponentModel.BackgroundWorker#13](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#13)] + [!code-csharp[System.ComponentModel.BackgroundWorker#13](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#13)] + [!code-vb[System.ComponentModel.BackgroundWorker#13](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#13)] + +5. In the event handler, assign the result of the calculation to the `resultLabel` control. + + [!code-cpp[System.ComponentModel.BackgroundWorker#6](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#6)] + [!code-csharp[System.ComponentModel.BackgroundWorker#6](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#6)] + [!code-vb[System.ComponentModel.BackgroundWorker#6](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#6)] + +## Adding Progress Reporting and Support for Cancellation + +For asynchronous operations that will take a long time, it is often desirable to report progress to the user and to allow the user to cancel the operation. The class provides an event that allows you to post progress as your background operation proceeds. It also provides a flag that allows your worker code to detect a call to and interrupt itself. + +### Implement progress reporting + +1. In the **Properties**, window, select `backgroundWorker1`. Set the and properties to `true`. + +2. Declare two variables in the `FibonacciCalculator` form. These will be used to track progress. + + [!code-cpp[System.ComponentModel.BackgroundWorker#14](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#14)] + [!code-csharp[System.ComponentModel.BackgroundWorker#14](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#14)] + [!code-vb[System.ComponentModel.BackgroundWorker#14](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#14)] + +3. Add an event handler for the event. In the event handler, update the with the property of the parameter. + + [!code-cpp[System.ComponentModel.BackgroundWorker#7](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#7)] + [!code-csharp[System.ComponentModel.BackgroundWorker#7](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#7)] + [!code-vb[System.ComponentModel.BackgroundWorker#7](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#7)] + +### Implement support for cancellation + +1. In the `cancelAsyncButton` control's event handler, add the code that cancels the asynchronous operation. + + [!code-cpp[System.ComponentModel.BackgroundWorker#4](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#4)] + [!code-csharp[System.ComponentModel.BackgroundWorker#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#4)] + [!code-vb[System.ComponentModel.BackgroundWorker#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#4)] + +2. The following code fragments in the `ComputeFibonacci` method report progress and support cancellation. + + [!code-cpp[System.ComponentModel.BackgroundWorker#11](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#11)] + [!code-csharp[System.ComponentModel.BackgroundWorker#11](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#11)] + [!code-vb[System.ComponentModel.BackgroundWorker#11](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#11)] + [!code-cpp[System.ComponentModel.BackgroundWorker#12](~/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp#12)] + [!code-csharp[System.ComponentModel.BackgroundWorker#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs#12)] + [!code-vb[System.ComponentModel.BackgroundWorker#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb#12)] + +## Checkpoint + +At this point, you can compile and run the Fibonacci Calculator application. + +Press **F5** to compile and run the application. + +While the calculation is running in the background, you will see the displaying the progress of the calculation toward completion. You can also cancel the pending operation. + +For small numbers, the calculation should be very fast, but for larger numbers, you should see a noticeable delay. If you enter a value of 30 or greater, you should see a delay of several seconds, depending on the speed of your computer. For values greater than 40, it may take minutes or hours to finish the calculation. While the calculator is busy computing a large Fibonacci number, notice that you can freely move the form around, minimize, maximize, and even dismiss it. This is because the main UI thread is not waiting for the calculation to finish. + +## Next steps + +Now that you have implemented a form that uses a component to execute a computation in the background, you can explore other possibilities for asynchronous operations: + +- Use multiple objects for several simultaneous operations. + +- To debug your multithreaded application, see [How to: Use the Threads Window](/visualstudio/debugger/how-to-use-the-threads-window). + +- Implement your own component that supports the asynchronous programming model. For more information, see [Event-based Asynchronous Pattern Overview](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview). + + > [!CAUTION] + > When using multithreading of any sort, you potentially expose yourself to very serious and complex bugs. Consult the [Managed Threading Best Practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) before implementing any solution that uses multithreading. + +## See also + +- +- [Managed Threading](https://docs.microsoft.com/dotnet/standard/threading/index) +- [Managed Threading Best Practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) +- [Event-based Asynchronous Pattern Overview](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview) +- [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md) +- [Walkthrough: Running an Operation in the Background](walkthrough-running-an-operation-in-the-background.md) +- [BackgroundWorker Component](backgroundworker-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md new file mode 100644 index 0000000000..54244ac994 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-inheriting-from-a-windows-forms-control-with-visual-csharp.md @@ -0,0 +1,141 @@ +--- +title: Inherit from a Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "inheritance [Windows Forms], custom controls" + - "inheritance [Windows Forms], control" + - "Windows Forms controls, inheritance" + - "inheritance [Windows Forms], walkthroughs" + - "custom controls [Windows Forms], inheritance" +ms.assetid: 09476da0-8d4c-4a4c-b969-649519dfb438 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Inherit from a Windows Forms Control with C\# + +With C#, you can create powerful custom controls through *inheritance*. Through inheritance you are able to create controls that retain all of the inherent functionality of standard Windows Forms controls but also incorporate custom functionality. In this walkthrough, you will create a simple inherited control called `ValueButton`. This button will inherit functionality from the standard Windows Forms control, and will expose a custom property called `ButtonValue`. + +## Create the Project + +When you create a new project, you specify its name in order to set the root namespace, assembly name, and project name, and to ensure that the default component will be in the correct namespace. + +### To create the ValueButtonLib control library and the ValueButton control + +1. In Visual Studio, create a new **Windows Forms Control Library** project, and name it **ValueButtonLib**. + + The project name, `ValueButtonLib`, is also assigned to the root namespace by default. The root namespace is used to qualify the names of components in the assembly. For example, if two assemblies provide components named `ValueButton`, you can specify your `ValueButton` component using `ValueButtonLib.ValueButton`. For more information, see [Namespaces](https://docs.microsoft.com/dotnet/csharp/programming-guide/namespaces/index). + +2. In **Solution Explorer**, right-click **UserControl1.cs**, then choose **Rename** from the shortcut menu. Change the file name to **ValueButton.cs**. Click the **Yes** button when you are asked if you want to rename all references to the code element '`UserControl1`'. + +3. In **Solution Explorer**, right-click **ValueButton.cs** and select **View Code**. + +4. Locate the `class` statement line, `public partial class ValueButton`, and change the type from which this control inherits from to . This allows your inherited control to inherit all the functionality of the control. + +5. In **Solution Explorer**, open the **ValueButton.cs** node to display the designer-generated code file, **ValueButton.Designer.cs**. Open this file in the **Code Editor**. + +6. Locate the `InitializeComponent` method and remove the line that assigns the property. This property does not exist in the control. + +7. From the **File** menu, choose **Save All** to save the project. + + > [!NOTE] + > A visual designer is no longer available. Because the control does its own painting, you are unable to modify its appearance in the designer. Its visual representation will be exactly the same as that of the class it inherits from (that is, ) unless modified in the code. You can still add components, which have no UI elements, to the design surface. + +## Add a Property to Your Inherited Control + +One possible use of inherited Windows Forms controls is the creation of controls that are identical in look and feel of standard Windows Forms controls, but expose custom properties. In this section, you will add a property called `ButtonValue` to your control. + +### To add the Value property + +1. In **Solution Explorer**, right-click **ValueButton.cs**, and then click **View Code** from the shortcut menu. + +2. Locate the `class` statement. Immediately after the `{`, type the following code: + + ```csharp + // Creates the private variable that will store the value of your + // property. + private int varValue; + // Declares the property. + public int ButtonValue + { + // Sets the method for retrieving the value of your property. + get + { + return varValue; + } + // Sets the method for setting the value of your property. + set + { + varValue = value; + } + } + ``` + + This code sets the methods by which the `ButtonValue` property is stored and retrieved. The `get` statement sets the value returned to the value that is stored in the private variable `varValue`, and the `set` statement sets the value of the private variable by use of the `value` keyword. + +3. From the **File** menu, choose **Save All** to save the project. + +## Test the control + +Controls are not stand-alone projects; they must be hosted in a container. In order to test your control, you must provide a test project for it to run in. You must also make your control accessible to the test project by building (compiling) it. In this section, you will build your control and test it in a Windows Form. + +### To build your control + +On the **Build** menu, click **Build Solution**. The build should be successful with no compiler errors or warnings. + +### To create a test project + +1. On the **File** menu, point to **Add** and then click **New Project** to open the **Add New Project** dialog box. + +2. Select the **Windows** node, beneath the **Visual C#** node, and click **Windows Forms Application**. + +3. In the **Name** box, enter **Test**. + +4. In **Solution Explorer**, right-click the **References** node for your test project, then select **Add Reference** from the shortcut menu to display the **Add Reference** dialog box. + +5. Click the tab labeled **Projects**. Your ValueButtonLib project will be listed under **Project Name**. Double-click the project to add the reference to the test project. + +6. In **Solution Explorer,** right-click **Test** and select **Build**. + +### To add your control to the form + +1. In **Solution Explorer**, right-click **Form1.cs** and choose **View Designer** from the shortcut menu. + +2. In the **Toolbox**, select **ValueButtonLib Components**. Double-click **ValueButton**. + + A **ValueButton** appears on the form. + +3. Right-click the **ValueButton** and select **Properties** from the shortcut menu. + +4. In the **Properties** window, examine the properties of this control. Note that they are identical to the properties exposed by a standard button, except that there is an additional property, ButtonValue. + +5. Set the **ButtonValue** property to **5**. + +6. In the **All Windows Forms** tab of the **Toolbox**, double-click **Label** to add a control to your form. + +7. Relocate the label to the center of the form. + +8. Double-click `valueButton1`. + + The **Code Editor** opens to the `valueButton1_Click` event. + +9. Insert the following line of code. + + ```csharp + label1.Text = valueButton1.ButtonValue.ToString(); + ``` + +10. In **Solution Explorer**, right-click **Test**, and choose **Set as Startup Project** from the shortcut menu. + +11. From the **Debug** menu, select **Start Debugging**. + + `Form1` appears. + +12. Click `valueButton1`. + + The numeral '5' is displayed in `label1`, demonstrating that the `ButtonValue` property of your inherited control has been passed to `label1` through the `valueButton1_Click` method. Thus your `ValueButton` control inherits all the functionality of the standard Windows Forms button, but exposes an additional, custom property. + +## See also + +- [How to: Display a Control in the Choose Toolbox Items Dialog Box](how-to-display-a-control-in-the-choose-toolbox-items-dialog-box.md) +- [Walkthrough: Authoring a Composite Control with Visual C#](walkthrough-authoring-a-composite-control-with-visual-csharp.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-providing-standard-menu-items-to-a-form.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-providing-standard-menu-items-to-a-form.md new file mode 100644 index 0000000000..e3e98cd7f0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-providing-standard-menu-items-to-a-form.md @@ -0,0 +1,111 @@ +--- +title: "Walkthrough: Providing Standard Menu Items to a Form" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "menu items [Windows Forms], standard" + - "toolbars [Windows Forms], walkthroughs" + - "StatusStrip control [Windows Forms]" + - "ToolStrip control [Windows Forms]" +ms.assetid: dac37d98-589e-4d6d-9673-6437e8943122 +--- +# Walkthrough: Providing Standard Menu Items to a Form + +You can provide a standard menu for your forms with the control. + +This walkthrough demonstrates how to use a control to create a standard menu. The form also responds when a user selects a menu item. The following tasks are illustrated in this walkthrough: + +- Creating a Windows Forms project. + +- Creating a standard menu. + +- Creating a control. + +- Handling menu item selection. + +When you are finished, you will have a form with a standard menu that displays menu item selections in a control. + +To copy the code in this topic as a single listing, see [How to: Provide Standard Menu Items to a Form](how-to-provide-standard-menu-items-to-a-form.md). + +## Prerequisites + +You'll need Visual Studio to complete this walkthrough. + +## Create the project + +1. In Visual Studio, create a Windows application project called **StandardMenuForm** (**File** > **New** > **Project** > **Visual C#** or **Visual Basic** > **Classic Desktop** > **Windows Forms Application**). + +2. In the Windows Forms Designer, select the form. + +## Create a standard menu + +The Windows Forms Designer can automatically populate a control with standard menu items. + +1. From the **Toolbox**, drag a control onto your form. + +2. Click the control's designer actions glyph (![Small black arrow](./media/designer-actions-glyph.gif)) and select **Insert Standard Items**. + + The control is populated with the standard menu items. + +3. Click the **File** menu item to see its default menu items and corresponding icons. + +## Create a StatusStrip control + +Use the control to display status for your Windows Forms applications. In the current example, menu items selected by the user are displayed in a control. + +1. From the **Toolbox**, drag a control onto your form. + + The control automatically docks to the bottom of the form. + +2. Click the control's drop-down button and select **StatusLabel** to add a control to the control. + +## Handle item selection + +Handle the event to respond when the user selects a menu item. + +1. Click the **File** menu item that you created in the Creating a Standard Menu section. + +2. In the **Properties** window, click **Events**. + +3. Double-click the event. + + The Windows Forms Designer generates an event handler for the event. + +4. Insert the following code into the event handler. + + [!code-csharp[System.Windows.Forms.ToolStrip.StandardMenu#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.ToolStrip.StandardMenu#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/VB/Form1.vb#3)] + +5. Insert the `UpdateStatus` utility method definition into the form. + + [!code-csharp[System.Windows.Forms.ToolStrip.StandardMenu#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.ToolStrip.StandardMenu#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/VB/Form1.vb#2)] + +## Checkpoint -test your form + +1. Press **F5** to compile and run your form. + +2. Click the **File** menu item to open the menu. + +3. On the **File** menu, click one of the items to select it. + + The control displays the selected item. + +## Next steps + +In this walkthrough, you have created a form with a standard menu. You can use the family of controls for many other purposes: + +- Create shortcut menus for your controls with . For more information, see [ContextMenu Component Overview](contextmenu-component-overview-windows-forms.md). + +- Create a multiple document interface (MDI) form with docking controls. For more information, see [Walkthrough: Creating an MDI Form with Menu Merging and ToolStrip Controls](walkthrough-creating-an-mdi-form-with-menu-merging-and-toolstrip-controls.md). + +- Give your controls a professional appearance. For more information, see [How to: Set the ToolStrip Renderer for an Application](how-to-set-the-toolstrip-renderer-for-an-application.md). + +## See also + +- +- +- +- [MenuStrip Control](menustrip-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-running-an-operation-in-the-background.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-running-an-operation-in-the-background.md new file mode 100644 index 0000000000..51f2f0df67 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-running-an-operation-in-the-background.md @@ -0,0 +1,101 @@ +--- +title: "Walkthrough: Running an Operation in the Background" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "background tasks" + - "forms [Windows Forms], multithreading" + - "forms [Windows Forms], background operations" + - "background threads" + - "BackgroundWorker class [Windows Forms], examples" + - "threading [Windows Forms], background operations" + - "background operations" +ms.assetid: 1b9a4e0a-f134-48ff-a1be-c461446a31ba +--- +# Walkthrough: Running an Operation in the Background + +If you have an operation that will take a long time to complete, and you do not want to cause delays in your user interface, you can use the class to run the operation on another thread. + +For a complete listing of the code used in this example, see [How to: Run an Operation in the Background](how-to-run-an-operation-in-the-background.md). + +## Run an operation in the background + +1. With your form active in the Windows Forms Designer in Visual Studio, drag two controls from the **Toolbox** to the form, and then set the `Name` and properties of the buttons according to the following table. + + |Button|Name|Text| + |------------|----------|----------| + |`button1`|`startBtn`|**Start**| + |`button2`|`cancelBtn`|**Cancel**| + +2. Open the **Toolbox**, click the **Components** tab, and then drag the component onto your form. + + The `backgroundWorker1` component appears in the **Component Tray**. + +3. In the **Properties** window, set the property to `true`. + +4. In the **Properties** window, click on the **Events** button, and then double-click the and events to create event handlers. + +5. Insert your time-consuming code into the event handler. + +6. Extract any parameters required by the operation from the property of the parameter. + +7. Assign the result of the computation to the property of the . + + This is will be available to the event handler. + + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#2)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#2)] + +8. Insert code for retrieving the result of your operation in the event handler. + + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#3)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#3)] + +9. Implement the `TimeConsumingOperation` method. + + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#4)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#4)] + +10. In the Windows Forms Designer, double-click `startButton` to create the event handler. + +11. Call the method in the event handler for `startButton`. + + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#5)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#5)] + +12. In the Windows Forms Designer, double-click `cancelButton` to create the event handler. + +13. Call the method in the event handler for `cancelButton`. + + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#6](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#6)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#6](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#6)] + +14. At the top of the file, import the System.ComponentModel and System.Threading namespaces. + + [!code-csharp[System.ComponentModel.BackgroundWorker.Example#7](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs#7)] + [!code-vb[System.ComponentModel.BackgroundWorker.Example#7](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb#7)] + +15. Press **F6** to build the solution, and then press **Ctrl**+**F5** to run the application outside the debugger. + + > [!NOTE] + > If you press **F5** to run the application under the debugger, the exception raised in the `TimeConsumingOperation` method is caught and displayed by the debugger. When you run the application outside the debugger, the handles the exception and caches it in the property of the . + +16. Click the **Start** button to run an asynchronous operation, and then click the **Cancel** button to stop a running asynchronous operation. + + The outcome of each operation is displayed in a . + +## Next steps + +- Implement a form that reports progress as an asynchronous operation proceeds. For more information, see [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md). + +- Implement a class that supports the Asynchronous Pattern for Components. For more information, see [Implementing the Event-based Asynchronous Pattern](https://docs.microsoft.com/dotnet/standard/asynchronous-programming-patterns/implementing-the-event-based-asynchronous-pattern). + +## See also + +- +- +- [How to: Implement a Form That Uses a Background Operation](how-to-implement-a-form-that-uses-a-background-operation.md) +- [How to: Run an Operation in the Background](how-to-run-an-operation-in-the-background.md) +- [BackgroundWorker Component](backgroundworker-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-updating-status-bar-information-at-run-time.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-updating-status-bar-information-at-run-time.md new file mode 100644 index 0000000000..9ff13e0d25 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-updating-status-bar-information-at-run-time.md @@ -0,0 +1,87 @@ +--- +title: "Walkthrough: Updating Status Bar Information at Run Time" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "status bars [Windows Forms], updating at run time" + - "status bars [Windows Forms], refreshing panels" + - "StatusBar control [Windows Forms], refreshing panels" + - "panels [Windows Forms], refreshing status bar" +ms.assetid: cc2abb06-c082-49f7-a5a3-2fd1bbcb58d1 +--- +# Walkthrough: Updating Status Bar Information at Run Time +> [!IMPORTANT] +> The and controls replace and add functionality to the and controls; however, the and controls are retained for both backward compatibility and future use, if you choose. + + Often, a program will call for you to update the contents of status bar panels dynamically at run time, based on changes to application state or other user interaction. This is a common way to signal users that keys such as the CAPS LOCK, NUM LOCK, or SCROLL LOCK are enabled, or to provide the date or a clock as a convenient reference. + + In the following example, you will use an instance of the class to host a clock. + +### To get the status bar ready for updating + +1. Create a new Windows form. + +2. Add a control to your form. For details, see [How to: Add Controls to Windows Forms](how-to-add-controls-to-windows-forms.md). + +3. Add a status bar panel to your control. For details, see [How to: Add Panels to a StatusBar Control](how-to-add-panels-to-a-statusbar-control.md). + +4. For the control you added to your form, set the property to `true`. + +5. Add a Windows Forms component to the form. + + > [!NOTE] + > The Windows Forms component is designed for a Windows Forms environment. If you need a timer that is suitable for a server environment, see [Introduction to Server-Based Timers](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2008/tb9yt5e6(v=vs.90)). + +6. Set the property to `true`. + +7. Set the property of the to 30000. + + > [!NOTE] + > The property of the component is set to 30 seconds (30,000 milliseconds) to ensure that an accurate time is reflected in the time displayed. + +### To implement the timer to update the status bar + +1. Insert the following code into the event handler of the component to update the panel of the control. + + ```vb + Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick + StatusBar1.Panels(0).Text = Now.ToShortTimeString + End Sub + ``` + + ```csharp + private void timer1_Tick(object sender, System.EventArgs e) + { + statusBar1.Panels[0].Text = DateTime.Now.ToShortTimeString(); + } + ``` + + ```cpp + private: + System::Void timer1_Tick(System::Object ^ sender, + System::EventArgs ^ e) + { + statusBar1->Panels[0]->Text = + DateTime::Now.ToShortTimeString(); + } + ``` + + At this point, you are ready to run the application and observe the clock running in the status bar panel. + +### To test the application + +1. Debug the application and press F5 to run it. For details about debugging, see [Debugging in Visual Studio](/visualstudio/debugger/debugger-feature-tour). + + > [!NOTE] + > It will take approximately 30 seconds for the clock to appear in the status bar. This is to get the most accurate time possible. Conversely, to make the clock appear sooner, you can reduce the value of the property you set in step 7 in the previous procedure. + +## See also + +- +- +- [How to: Add Panels to a StatusBar Control](how-to-add-panels-to-a-statusbar-control.md) +- [How to: Determine Which Panel in the Windows Forms StatusBar Control Was Clicked](determine-which-panel-wf-statusbar-control-was-clicked.md) +- [StatusBar Control Overview](statusbar-control-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-validating-data-in-the-windows-forms-datagridview-control.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-validating-data-in-the-windows-forms-datagridview-control.md new file mode 100644 index 0000000000..fb5765c4ac --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-validating-data-in-the-windows-forms-datagridview-control.md @@ -0,0 +1,96 @@ +--- +title: "Walkthrough: Validate data in DataGridView control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "validating data [Windows Forms], Windows Forms" + - "data [Windows Forms], validation" + - "DataGridView control [Windows Forms], data validation" + - "data grids [Windows Forms], validating data" + - "data validation [Windows Forms], Windows Forms" + - "walkthroughs [Windows Forms], DataGridView control" +ms.assetid: a4f1d015-2969-430c-8ea2-b612d179c290 +--- +# Walkthrough: Validating Data in the Windows Forms DataGridView Control + +When you display data entry functionality to users, you frequently have to validate the data entered into your form. The class provides a convenient way to perform validation before data is committed to the data store. You can validate data by handling the event, which is raised by the when the current cell changes. + +In this walkthrough, you will retrieve rows from the `Customers` table in the Northwind sample database and display them in a control. When a user edits a cell in the `CompanyName` column and tries to leave the cell, the event handler will examine new company name string to make sure it is not empty; if the new value is an empty string, the will prevent the user's cursor from leaving the cell until a non-empty string is entered. + +To copy the code in this topic as a single listing, see [How to: Validate Data in the Windows Forms DataGridView Control](how-to-validate-data-in-the-windows-forms-datagridview-control.md). + +## Prerequisites + +In order to complete this walkthrough, you will need: + +- Access to a server that has the Northwind SQL Server sample database. + +## Creating the Form + +#### To validate data entered in a DataGridView + +1. Create a class that derives from and contains a control and a component. + + The following code example provides basic initialization and includes a `Main` method. + + [!code-csharp[System.Windows.Forms.DataGridViewDataValidation#01](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs#01)] + [!code-vb[System.Windows.Forms.DataGridViewDataValidation#01](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb#01)] + [!code-csharp[System.Windows.Forms.DataGridViewDataValidation#02](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs#02)] + [!code-vb[System.Windows.Forms.DataGridViewDataValidation#02](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb#02)] + +2. Implement a method in your form's class definition for handling the details of connecting to the database. + + This code example uses a `GetData` method that returns a populated object. Be sure that you set the `connectionString` variable to a value that is appropriate for your database. + + > [!IMPORTANT] + > Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication, also known as integrated security, is a more secure way to control access to a database. For more information, see [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information). + + [!code-csharp[System.Windows.Forms.DataGridViewDataValidation#30](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs#30)] + [!code-vb[System.Windows.Forms.DataGridViewDataValidation#30](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb#30)] + +3. Implement a handler for your form's event that initializes the and and sets up the data binding. + + [!code-csharp[System.Windows.Forms.DataGridViewDataValidation#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs#10)] + [!code-vb[System.Windows.Forms.DataGridViewDataValidation#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb#10)] + +4. Implement handlers for the control's and events. + + The event handler is where you determine whether the value of a cell in the `CompanyName` column is empty. If the cell value fails validation, set the property of the class to `true`. This causes the control to prevent the cursor from leaving the cell. Set the property on the row to an explanatory string. This displays an error icon with a ToolTip that contains the error text. In the event handler, set the property on the row to the empty string. The event occurs only when the cell exits edit mode, which it cannot do if it fails validation. + + [!code-csharp[System.Windows.Forms.DataGridViewDataValidation#20](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs#20)] + [!code-vb[System.Windows.Forms.DataGridViewDataValidation#20](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb#20)] + +## Testing the Application + +You can now test the form to make sure it behaves as expected. + +#### To test the form + +- Compile and run the application. + + You will see a filled with data from the `Customers` table. When you double-click a cell in the `CompanyName` column, you can edit the value. If you delete all the characters and hit the TAB key to exit the cell, the prevents you from exiting. When you type a non-empty string into the cell, the control lets you exit the cell. + +## Next Steps + +This application gives you a basic understanding of the control's capabilities. You can customize the appearance and behavior of the control in several ways: + +- Change border and header styles. For more information, see [How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control](change-the-border-and-gridline-styles-in-the-datagrid.md). + +- Enable or restrict user input to the control. For more information, see [How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control](prevent-row-addition-and-deletion-datagridview.md), and [How to: Make Columns Read-Only in the Windows Forms DataGridView Control](how-to-make-columns-read-only-in-the-windows-forms-datagridview-control.md). + +- Check user input for database-related errors. For more information, see [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md). + +- Handle very large data sets using virtual mode. For more information, see [Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control](implementing-virtual-mode-wf-datagridview-control.md). + +- Customize the appearance of cells. For more information, see [How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control](customize-the-appearance-of-cells-in-the-datagrid.md) and [How to: Set Font and Color Styles in the Windows Forms DataGridView Control](how-to-set-font-and-color-styles-in-the-windows-forms-datagridview-control.md). + +## See also + +- +- +- [Data Entry in the Windows Forms DataGridView Control](data-entry-in-the-windows-forms-datagridview-control.md) +- [How to: Validate Data in the Windows Forms DataGridView Control](how-to-validate-data-in-the-windows-forms-datagridview-control.md) +- [Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control](handling-errors-that-occur-during-data-entry-in-the-datagrid.md) +- [Protecting Connection Information](https://docs.microsoft.com/dotnet/framework/data/adonet/protecting-connection-information) diff --git a/dotnet-desktop-guide/framework/winforms/controls/walkthrough-working-with-the-maskedtextbox-control.md b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-working-with-the-maskedtextbox-control.md new file mode 100644 index 0000000000..cdea0ea178 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/walkthrough-working-with-the-maskedtextbox-control.md @@ -0,0 +1,124 @@ +--- +title: "Walkthrough: Working with the MaskedTextBox Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "input [Windows Forms], controlling to ensure validity" + - "MaskedTextBox control [Windows Forms], walkthroughs" + - "MaskedTextBox control [Windows Forms], validation" + - "user input [Windows Forms], controlling" + - "text [Windows Forms], controls for input" +ms.assetid: df60565e-5447-4110-92a6-be1f6ff5faa3 +--- +# Walkthrough: Working with the MaskedTextBox Control +Tasks illustrated in this walkthrough include: + +- Initializing the control + +- Using the event handler to alert the user when a character does not conform to the mask + +- Assigning a type to the property and using the event handler to alert the user when the value they're attempting to commit is not valid for the type + +## Creating the Project and Adding a Control + +#### To add a MaskedTextBox control to your form + +1. Open the form on which you want to place the control. + +2. Drag a control from the **Toolbox** to your form. + +3. Right-click the control and choose **Properties**. In the **Properties** window, select the **Mask** property and click the **...** (ellipsis) button next to the property name. + +4. In the **Input Mask** dialog box, select the **Short Date** mask and click **OK**. + +5. In the **Properties** window set the property to `true`. This property causes a short beep to sound every time the user attempts to input a character that violates the mask definition. + + For a summary of the characters that the Mask property supports, see the Remarks section of the property. + +## Alert the User to Input Errors + +#### Add a balloon tip for rejected mask input + +1. Return to the **Toolbox** and add a to your form. + +2. Create an event handler for the event that raises the when an input error occurs. The balloon tip remains visible for five seconds, or until the user clicks it. + + ```csharp + public void Form1_Load(Object sender, EventArgs e) + { + ... // Other initialization code + maskedTextBox1.Mask = "00/00/0000"; + maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected) + } + + void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) + { + toolTip1.ToolTipTitle = "Invalid Input"; + toolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", maskedTextBox1, maskedTextBox1.Location, 5000); + } + ``` + + ```vb + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + Me.ToolTip1.IsBalloon = True + Me.MaskedTextBox1.Mask = "00/00/0000" + End Sub + + Private Sub MaskedTextBox1_MaskInputRejected(sender as Object, e as MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected + ToolTip1.ToolTipTitle = "Invalid Input" + ToolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", MaskedTextBox1, 5000) + End Sub + ``` + +## Alert the User to a Type that Is Not Valid + +#### Add a balloon tip for invalid data types + +1. In your form's event handler, assign a object representing the type to the control's property: + + ```csharp + private void Form1_Load(Object sender, EventArgs e) + { + // Other code + maskedTextBox1.ValidatingType = typeof(System.DateTime); + maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted); + } + ``` + + ```vb + Private Sub Form1_Load(sender as Object, e as EventArgs) + // Other code + MaskedTextBox1.ValidatingType = GetType(System.DateTime) + End Sub + ``` + +2. Add an event handler for the event: + + ```csharp + public void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e) + { + if (!e.IsValidInput) + { + toolTip1.ToolTipTitle = "Invalid Date Value"; + toolTip1.Show("We're sorry, but the value you entered is not a valid date. Please change the value.", maskedTextBox1, 5000); + e.Cancel = true; + } + } + ``` + + ```vb + Public Sub MaskedTextBox1_TypeValidationCompleted(sender as Object, e as TypeValidationEventArgs) + If Not e.IsValidInput Then + ToolTip1.ToolTipTitle = "Invalid Date Value" + ToolTip1.Show("We're sorry, but the value you entered is not a valid date. Please change the value.", maskedTextBox1, 5000) + e.Cancel = True + End If + End Sub + ``` + +## See also + +- +- [MaskedTextBox Control](maskedtextbox-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/ways-to-select-a-windows-forms-button-control.md b/dotnet-desktop-guide/framework/winforms/controls/ways-to-select-a-windows-forms-button-control.md new file mode 100644 index 0000000000..d643877609 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/ways-to-select-a-windows-forms-button-control.md @@ -0,0 +1,29 @@ +--- +title: Ways to Select a Button Control +ms.date: "03/30/2017" +helpviewer_keywords: + - "Button control [Windows Forms], selecting" +ms.assetid: fe2fc058-5118-4f70-b264-6147d64a7a8d +--- +# Ways to Select a Windows Forms Button Control +A Windows Forms button can be selected in the following ways: + +- Use a mouse to click the button. + +- Invoke the button's event in code. + +- Move the focus to the button by pressing the TAB key, and then choose the button by pressing the SPACEBAR or ENTER. + +- Press the access key (ALT + the underlined letter) for the button. For more information about access keys, see [How to: Create Access Keys for Windows Forms Controls](how-to-create-access-keys-for-windows-forms-controls.md). + +- If the button is the "accept" button of the form, pressing ENTER chooses the button, even if another control has the focus — except if that other control is another button, a multi-line text box, or a custom control that traps the enter key. + +- If the button is the "cancel" button of the form, pressing ESC chooses the button, even if another control has the focus. + +- Call the method to select the button programmatically. + +## See also + +- [Button Control Overview](button-control-overview-windows-forms.md) +- [How to: Respond to Windows Forms Button Clicks](how-to-respond-to-windows-forms-button-clicks.md) +- [Button Control](button-control-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/webbrowser-control-overview.md b/dotnet-desktop-guide/framework/winforms/controls/webbrowser-control-overview.md new file mode 100644 index 0000000000..bc53970c9c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/webbrowser-control-overview.md @@ -0,0 +1,56 @@ +--- +title: "WebBrowser Control Overview" +description: Learn how to use the WebBrowser control to seamlessly combine Web controls with Windows Forms controls in a single application. +ms.date: "03/30/2017" +f1_keywords: + - "WebBrowser" +helpviewer_keywords: + - "WebBrowser control [Windows Forms], about" + - "Web pages [Windows Forms], displaying in applications" +ms.assetid: 6e3e1cc2-9c48-4136-9659-e99e4e60b7e9 +--- +# WebBrowser Control Overview +The control provides a managed wrapper for the WebBrowser ActiveX control. The managed wrapper lets you display Web pages in your Windows Forms client applications. You can use the control to duplicate Internet Explorer Web browsing functionality in your application or you can disable default Internet Explorer functionality and use the control as a simple HTML document viewer. You can also use the control to add DHTML-based user interface elements to your form and hide the fact that they are hosted in the control. This approach lets you seamlessly combine Web controls with Windows Forms controls in a single application. + +## Frequently Used Properties, Methods, and Events + The control has several properties, methods, and events that you can use to implement controls found in Internet Explorer. For example, you can use the `Navigate` method to implement an address bar, and the `GoBack`, `GoForward`, `Stop`, and `Refresh` methods to implement navigation buttons on a toolbar. You can handle the `Navigated` event to update the address bar with the value of the `Url` property and the title bar with the value of the `DocumentTitle` property. + + If you want to generate your own page content within your application, you can set the `DocumentText` property. If you are familiar with the HTML document object model (DOM), you can also manipulate the contents of the current Web page through the `Document` property. With this property, you can store and modify documents in memory instead of navigating among files. + + The `Document` property also lets you call methods implemented in Web page scripting code from your client application code. To access your client application code from your scripting code, set the `ObjectForScripting` property. The object that you specify can be accessed by your script code as the `window.external` object. + +|Name|Description| +|----------|-----------------| +| property|Gets an object that provides managed access to the HTML document object model (DOM) of the current Web page.| +| event|Occurs when a Web page finishes loading.| +| property|Gets or sets the HTML content of the current Web page.| +| property|Gets the title of the current Web page.| +| method|Navigates to the previous page in history.| +| method|Navigates to the next page in history.| +| method|Navigates to the specified URL.| +| event|Occurs before navigation begins, enabling the action to be canceled.| +| property|Gets or sets an object that Web page scripting code can use to communicate with your application.| +| method|Prints the current Web page.| +| method|Reloads the current Web page.| +| method|Halts the current navigation and stops dynamic page elements such as sounds and animation.| +| property|Gets or sets the URL of the current Web page. Setting this property navigates the control to the new URL.| + +## See also + +- +- +- +- +- +- +- +- +- +- +- +- [How to: Navigate to a URL with the WebBrowser Control](how-to-navigate-to-a-url-with-the-webbrowser-control.md) +- [How to: Print with a WebBrowser Control](how-to-print-with-a-webbrowser-control.md) +- [How to: Add Web Browser Capabilities to a Windows Forms Application](how-to-add-web-browser-capabilities-to-a-windows-forms-application.md) +- [How to: Create an HTML Document Viewer in a Windows Forms Application](how-to-create-an-html-document-viewer-in-a-windows-forms-application.md) +- [How to: Implement Two-Way Communication Between DHTML Code and Client Application Code](implement-two-way-com-between-dhtml-and-client.md) +- [WebBrowser Security](webbrowser-security.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/webbrowser-control-windows-forms.md b/dotnet-desktop-guide/framework/winforms/controls/webbrowser-control-windows-forms.md new file mode 100644 index 0000000000..5d34e503a4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/webbrowser-control-windows-forms.md @@ -0,0 +1,78 @@ +--- +title: "WebBrowser Control" +description: Learn about how the Windows Forms WebBrowser control hosts webpages and provides web browsing capabilities to your application. +ms.date: "03/30/2017" +helpviewer_keywords: + - "WebBrowser control [Windows Forms]" + - "Web pages [Windows Forms], hosting in applications" + - "Web pages [Windows Forms], Windows Forms controls" +ms.assetid: 12667861-5b5b-46bc-8fb5-675e25264c9f +--- +# WebBrowser Control (Windows Forms) +The Windows Forms `WebBrowser` control hosts webpages and provides web browsing capabilities to your application. + +## In This Section + [WebBrowser Control Overview](webbrowser-control-overview.md) + Explains what this control is and its key features and properties. + + [WebBrowser Security](webbrowser-security.md) + Explains security issues related to the control. + + [How to: Navigate to a URL with the WebBrowser Control](how-to-navigate-to-a-url-with-the-webbrowser-control.md) + Demonstrates how to use the control to navigate to a specific URL. + + [How to: Print with a WebBrowser Control](how-to-print-with-a-webbrowser-control.md) + Demonstrates how to print a Web page without displaying it. + + [How to: Add Web Browser Capabilities to a Windows Forms Application](how-to-add-web-browser-capabilities-to-a-windows-forms-application.md) + Describes how to initialize the control for use as a Web browser. + + [How to: Create an HTML Document Viewer in a Windows Forms Application](how-to-create-an-html-document-viewer-in-a-windows-forms-application.md) + Describes how to initialize the control for use as an HTML viewer. + + [How to: Implement Two-Way Communication Between DHTML Code and Client Application Code](implement-two-way-com-between-dhtml-and-client.md) + Describes how to set up two-way communication between your application code and DHTML in a Web page hosted by the control. + + [Using the Managed HTML Document Object Model](using-the-managed-html-document-object-model.md) + Provides topics that describe how to manipulate or create HTML pages hosted by the control. + +## Reference + class + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + + + Describes this delegate. + + + Describes this enumeration and all its values. + + + Describes this class and has links to all its members. + + + Describes this delegate. + + + Describes this class and has links to all its members. + + + Describes this delegate. + + + Describes this class and has links to all its members. + + + Describes this delegate. + + + Describes this enumeration and all its values. + + + Describes this enumeration and all its values. + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/webbrowser-security.md b/dotnet-desktop-guide/framework/winforms/controls/webbrowser-security.md new file mode 100644 index 0000000000..d946792f50 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/webbrowser-security.md @@ -0,0 +1,18 @@ +--- +title: "WebBrowser Security" +ms.date: "03/30/2017" +helpviewer_keywords: + - "WebBrowser control [Windows Forms], security" + - "security [Windows Forms], WebBrowser control" +ms.assetid: 0968846e-48ee-485a-9797-65b5b9a622f8 +--- +# WebBrowser Security +The control is designed to work in full trust only. The HTML content displayed in the control can come from external Web servers and may contain unmanaged code in the form of scripts or Web controls. If you use the control in this situation, the control is no less secure than Internet Explorer would be, but the managed control does not prevent such unmanaged code from running. + + For more information about security issues relating to the underlying ActiveX `WebBrowser` control, see [WebBrowser Control](https://docs.microsoft.com/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa752040(v=vs.85)). + +## See also + +- +- [WebBrowser Control Overview](webbrowser-control-overview.md) +- [WebBrowser Control](https://docs.microsoft.com/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa752040(v=vs.85)) diff --git a/dotnet-desktop-guide/framework/winforms/controls/when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md b/dotnet-desktop-guide/framework/winforms/controls/when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md new file mode 100644 index 0000000000..16f7d6d290 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md @@ -0,0 +1,29 @@ +--- +title: ComboBox vs. ListBox +description: Learn about using Windows Forms ComboBox and Windows Forms ListBox, and learn to how tell when one or the other is more appropriate for a task. +ms.date: "03/30/2017" +helpviewer_keywords: + - "ListBox control [Windows Forms], adding and removing items" + - "ListBox control [Windows Forms], vs. ComboBox" + - "bound controls [Windows Forms], combo boxes" + - "Windows Forms controls, data binding" + - "ComboBox control [Windows Forms], compared to ListBox" + - "combo boxes [Windows Forms], compared to list boxes" + - "ListBox control [Windows Forms], accessing items" + - "ListCount property" +ms.assetid: 7bcaea58-1cfa-46db-9baf-b75a69d8f9ec +--- +# When to Use a Windows Forms ComboBox Instead of a ListBox +The and the controls have similar behaviors, and in some cases may be interchangeable. There are times, however, when one or the other is more appropriate to a task. + + Generally, a combo box is appropriate when there is a list of suggested choices, and a list box is appropriate when you want to limit input to what is on the list. A combo box contains a text box field, so choices not on the list can be typed in. The exception is when the property is set to . In that case, the control will select an item if you type its first letter. + + In addition, combo boxes save space on a form. Because the full list is not displayed until the user clicks the down arrow, a combo box can easily fit in a small space where a list box would not fit. An exception is when the property is set to : the full list is displayed, and the combo box takes up more room than a list box would. + +## See also + +- +- +- [How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control](add-and-remove-items-from-a-wf-combobox.md) +- [How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control](sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md) +- [Windows Forms Controls Used to List Options](windows-forms-controls-used-to-list-options.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/windows-forms-control-development-basics.md b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-control-development-basics.md new file mode 100644 index 0000000000..c6d267023d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-control-development-basics.md @@ -0,0 +1,32 @@ +--- +title: Basics for developing controls +ms.date: "03/30/2017" +helpviewer_keywords: + - "custom controls [Windows Forms], derivation types" + - "programming concepts [Windows Forms], Windows Forms controls" + - "controls [Windows Forms], creating" +ms.assetid: 6277bb81-90f7-4c5b-9f4b-b02bb42dd316 +--- +# Windows Forms Control Development Basics +A Windows Forms control is a class that derives directly or indirectly from . The following list describes common scenarios for developing Windows Forms controls: + +- Combining existing controls to author a composite control. + + Composite controls encapsulate a user interface that can be reused as a control. An example of a composite control is a control that consists of a text box and a reset button. Visual designers offer rich support for creating composite controls. To author a composite control, derive from . The base class provides keyboard routing for child controls and enables child controls to work as a group. For more information, see [Developing a Composite Windows Forms Control](developing-a-composite-windows-forms-control.md). + +- Extending an existing control to customize it or to add to its functionality. + + A button whose color cannot be changed and a button that has an additional property that tracks how many times it has been clicked are examples of extended controls. You can customize any Windows Forms control by deriving from it and overriding or adding properties, methods, and events. + +- Authoring a control that does not combine or extend existing controls. + + In this scenario, derive your control from the base class . You can add as well as override properties, methods, and events of the base class. To get started, see [How to: Develop a Simple Windows Forms Control](how-to-develop-a-simple-windows-forms-control.md). + + The base class for Windows Forms controls, , provides the plumbing required for visual display in client-side Windows-based applications. provides a window handle, handles message routing, and provides mouse and keyboard events as well as many other user interface events. It provides advanced layout and has properties specific to visual display, such as , , , , and many others. Additionally, it provides security, threading support, and interoperability with ActiveX controls. Because so much of the infrastructure is provided by the base class, it is relatively easy to develop your own Windows Forms controls. + +## See also + +- [How to: Develop a Simple Windows Forms Control](how-to-develop-a-simple-windows-forms-control.md) +- [Developing a Composite Windows Forms Control](developing-a-composite-windows-forms-control.md) +- [How to: Create a Windows Forms Control That Shows Progress](how-to-create-a-windows-forms-control-that-shows-progress.md) +- [Varieties of Custom Controls](varieties-of-custom-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-by-function.md b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-by-function.md new file mode 100644 index 0000000000..ea5103679c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-by-function.md @@ -0,0 +1,84 @@ +--- +title: Controls by Function +ms.date: "03/30/2017" +helpviewer_keywords: + - "controls [Windows Forms], by function" + - "Windows Forms, controls by function" + - "Windows Forms controls, list of" +ms.assetid: 5e65a6c3-5d6f-480d-beb8-b28f865f07e3 +--- +# Windows Forms Controls by Function +Windows Forms offers controls and components that perform a number of functions. The following table lists the Windows Forms controls and components according to general function. In addition, where multiple controls exist that serve the same function, the recommended control is listed with a note regarding the control it superseded. In a separate subsequent table, the superseded controls are listed with their recommended replacements. + +> [!NOTE] +> The following tables do not list every control or component you can use in Windows Forms; for a more comprehensive list, see [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + +## Recommended Controls and Components by Function + +|Function|Control|Description| +|--------------|-------------|-----------------| +|Data display| control|The control provides a customizable table for displaying data. The class enables customization of cells, rows, columns, and borders. **Note:** The control provides numerous basic and advanced features that are missing in the control. For more information, see [Differences Between the Windows Forms DataGridView and DataGrid Controls](differences-between-the-windows-forms-datagridview-and-datagrid-controls.md)| +|Data binding and navigation| component|Simplifies binding controls on a form to data by providing currency management, change notification, and other services.| +|| control|Provides a toolbar-type interface to navigate and manipulate data on a form.| +|Text editing| control|Displays text entered at design time that can be edited by users at run time, or changed programmatically.| +|| control|Enables text to be displayed with formatting in plain text or rich-text format (RTF).| +|| control|Constrains the format of user input| +|Information display (read-only)| control|Displays text that users cannot directly edit.| +|| control|Displays text as a Web-style link and triggers an event when the user clicks the special text. Usually the text is a link to another window or a Web site.| +|| control|Displays information about the application's current state using a framed area, usually at the bottom of a parent form.| +|| control|Displays the current progress of an operation to the user.| +|Web page display| control|Enables the user to navigate Web pages inside your form.| +|Selection from a list| control|Displays a scrollable list of items, each accompanied by a check box.| +|| control|Displays a drop-down list of items.| +|| control|Displays a list of text items that users can scroll through with up and down buttons.| +|| control|Displays a list of text and graphical items (icons).| +|| control|Displays items in one of four different views. Views include text only, text with small icons, text with large icons, and a details view.| +|| control|Displays a list of numerals that users can scroll through with up and down buttons.| +|| control|Displays a hierarchical collection of node objects that can consist of text with optional check boxes or icons.| +|Graphics display| control|Displays graphical files, such as bitmaps and icons, in a frame.| +|Graphics storage| control|Serves as a repository for images. controls and the images they contain can be reused from one application to the next.| +|Value setting| control|Displays a check box and a label for text. Generally used to set options.| +|| control|Displays a scrollable list of items, each accompanied by a check box.| +|| control|Displays a button that can be turned on or off.| +|| control|Allows users to set values on a scale by moving a "thumb" along a scale.| +|Date setting| control|Displays a graphical calendar to allow users to select a date or a time.| +|| control|Displays a graphical calendar to allow users to select a range of dates.| +|Dialog boxes| control|Displays the color picker dialog box that allows users to set the color of an interface element.| +|| control|Displays a dialog box that allows users to set a font and its attributes.| +|| control|Displays a dialog box that allows users to navigate to and select a file.| +|| control|Displays a dialog box that allows users to select a printer and set its attributes.| +|| control|Displays a dialog box that displays how a control component will appear when printed.| +|| control|Displays a dialog that allows users to browse, create, and eventually select a folder| +|| control|Displays a dialog box that allows users to save a file.| +|Menu controls| control|Creates custom menus. **Note:** The is designed to replace the control.| +|| control|Creates custom context menus. **Note:** The is designed to replace the control.| +|Commands| control|Starts, stops, or interrupts a process.| +|| control|Displays text as a Web-style link and triggers an event when the user clicks the special text. Usually the text is a link to another window or a Web site.| +|| control|Displays an icon in the status notification area of the taskbar that represents an application running in the background.| +|| control|Creates toolbars that can have a Microsoft Windows XP, Microsoft Office, Microsoft Internet Explorer, or custom look and feel, with or without themes, and with support for overflow and run-time item reordering. **Note:** The control is designed to replace the control.| +|User Help| component|Provides pop-up or online Help for controls.| +|| component|Provides a pop-up window that displays a brief description of a control's purpose when the user rests the pointer on the control.| +|Grouping other controls| control|Groups a set of controls on an unlabeled, scrollable frame.| +|| control|Groups a set of controls (such as radio buttons) on a labeled, nonscrollable frame.| +|| control|Provides a tabbed page for organizing and accessing grouped objects efficiently.| +|| control|Provides two panels separated by a movable bar. **Note:** The control is designed to replace the control.| +|| control|Represents a panel that dynamically lays out its contents in a grid composed of rows and columns.| +|| control|Represents a panel that dynamically lays out its contents horizontally or vertically.| +|Audio| control|Plays sound files in the .wav format. Sounds can be loaded or played asynchronously.| + +## Superseded Controls and Components by Function + +|Function|Superseded control|Recommended replacement| +|--------------|------------------------|-----------------------------| +|Data display||| +|Information Display (Read-only controls)||| +|Menu controls||| +|||| +|Commands||| +|||| +|Form layout||| + +## See also + +- [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) +- [Developing Custom Windows Forms Controls with the .NET Framework](developing-custom-windows-forms-controls.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-padding-autosize.md b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-padding-autosize.md new file mode 100644 index 0000000000..d3cacbb63c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-padding-autosize.md @@ -0,0 +1,180 @@ +--- +title: Lay Out Controls with Padding, Margins, and the AutoSize Property +ms.date: "03/30/2017" +f1_keywords: + - "Margin.Bottom" + - "Margin.Left" + - "Margin.Top" + - "Margin.All" + - "Margin.Right" +helpviewer_keywords: + - "Margin property [Windows Forms], walkthroughs" + - "walkthroughs [Windows Forms], layout" + - "AutoSize property [Windows Forms], walkthroughs" + - "Padding property [Windows Forms], walkthroughs" + - "layout [Windows Forms], margins and padding" + - "Windows Forms, layout" +ms.assetid: f8ae2a6b-db13-4630-8e25-d104091205c7 +author: jillre +ms.author: jillfra +manager: jillfra +--- +# Walkthrough: Lay out controls with padding, margins, and the AutoSize property + +Precise placement of controls on your form is a high priority for many applications. The **Windows Forms Designer** in Visual Studio gives you many layout tools to accomplish this. Three of the most important are the , , and properties, which are present on all Windows Forms controls. + +The property defines the space around the control that keeps other controls a specified distance from the control's borders. + +The property defines the space in the interior of a control that keeps the control's content (for example, the value of its property) a specified distance from the control's borders. + +The following illustration shows the and properties on a control. + +![Padding And Margin for Windows Forms Controls](./media/vs-winformpadmargin.gif) + +The property tells a control to automatically size itself to its contents. It will not resize itself to be smaller than the value of its original property, and it will account for the value of its property. + +## Prerequisites + +You'll need Visual Studio to complete this walkthrough. + +## Create the project + +1. In Visual Studio, create a **Windows Application** project called `LayoutExample`. + +2. Select the form in the **Windows Forms Designer**. + +## Set margins for controls + +You can set the default distance between your controls using the property. When you move a control close enough to another control, you will see a snapline that shows the margins for the two controls. The control you are moving will also snap to the distance defined by the margins. + +### Arrange controls on your form using the Margin property + +1. Drag two controls from the **Toolbox** onto your form. + +2. Select one of the controls and move it close to the other, until they are almost touching. + + Observe the snapline that appears between them. This distance is the sum of the two controls' values. The control you are moving snaps to this distance. For details, see [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md). + +3. Change the property of one of the controls by expanding the entry in the **Properties** window and setting the property to **20**. + +4. Select one of the controls and move it close to the other. + + The snapline defining the sum of the margin values is longer and that the control snaps to a greater distance from the other control. + +5. Change the property of the selected control by expanding the entry in the **Properties** window and setting the property to **5**. + +6. Move the selected control below the other control and observe that the snapline is shorter. Move the selected control to the left of the other control and observe that the snapline retains the value observed in step 4. + +7. You can set each of the aspects of the property, , , , , to different values, or you can set them all to the same value with the property. + +## Set padding for controls + +To achieve the precise layout required for your application, your controls will often contain child controls. When you want to specify the proximity of the child control's border to the parent control's border, use the parent control's property in conjunction with the child control's property. The property is also used to control the proximity of a control's content (for example, a control's property) to its borders. + +### Arrange controls on your form using padding + +1. Drag a control from the **Toolbox** onto your form. + +2. Change the value of the control's property to **true**. + +3. Change the property by expanding the entry in the **Properties** window and setting the property to **5**. + + The control expands to provide room for the new padding. + +4. Drag a control from the **Toolbox** onto your form. Drag a control from the **Toolbox** into the control. Position the control so it is flush with the lower-right corner of the control. + + Observe the snaplines that appear as the control approaches the bottom and right borders of the control. These snaplines correspond to the property of the . + +5. Change the control's property by expanding the entry in the **Properties** window and setting the property to **20**. + +6. Select the control within the control and move it toward the center of the . + + The snaplines appear at a greater distance from the borders of the control. This distance is the sum of the control's property and the control's property. + +## Size controls automatically + +In some applications, the size of a control will not be the same at run time as it was at design time. The text of a control, for example, may be taken from a database, and its length are not known in advance. + +When the property is set to `true`, the control will size itself to its content. For more information, see [AutoSize Property Overview](autosize-property-overview.md). + +### Arrange controls on your form using the AutoSize property + +1. Drag a control from the **Toolbox** onto your form. + +2. Change the value of the control's property to **true**. + +3. Change the control's property to **This button has a long string for its Text property**. + + When you commit the change, the control resizes itself to fit the new text. + +4. Drag another control from the **Toolbox** onto your form. + +5. Change the control's property to "**This button has a long string for its Text property.**" + + When you commit the change, the control does not resize itself, and the text is clipped by the right edge of the control. + +6. Change the property by expanding the entry in the **Properties** window and setting the property to **5**. + + The text in the control's interior is clipped on all four sides. + +7. Change the control's property to **true**. + + The control resizes itself to encompass the entire string. Also, padding has been added around the text, causing the control to expand in all four directions. + +8. Drag a control from the **Toolbox** onto your form. Position it near the lower-right corner of the form. + +9. Change the value of the control's property to **true**. + +10. Set the control's property to , . + +11. Change the control's property to "**This button has a long string for its Text property.**" + + When you commit the change, the control resizes itself toward the left. In general, automatic sizing will increase the size of a control in the direction opposite its property setting. + +## AutoSize and AutoSizeMode properties + + Some controls support the `AutoSizeMode` property, which gives you more fine-grained control over the automatic sizing behavior of a control. + +### Use the AutoSizeMode property + +1. Drag a control from the **Toolbox** onto your form. + +2. Set the value of the control's property to **true**. + +3. Drag a control from the **Toolbox** into the control. + +4. Place the control near the lower-right corner of the control. + +5. Select the control and grab the lower-right sizing handle. Resize the control to be larger and smaller. + + > [!NOTE] + > You can freely resize the control, but you cannot size it smaller than the position of the control's lower-right corner. This behavior is specified by the default value of the `AutoSizeMode` property, which is . + +6. Set the value of the control's `AutoSizeMode` property to . + + The control sizes itself to surround the control. You cannot resize the control. + +7. Drag the control toward the upper-left corner of the control. + + The control resizes to the control's new position. + +## Next steps + +There are many other layout features for arranging controls in your Windows Forms applications. Here are some combinations you might try: + +- Build a form using a control. For details, see [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md). Try changing the values of the control's property, as well as the property on its child controls. + +- Try the same experiment using a control. For details, see [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md). + +- Experiment with docking child controls in a control. The property is a more general realization of the property, and you can satisfy yourself that this is the case by putting a child control in a control and setting the child control's property to . Set the control's property to various values and note the effect. + +## See also + +- +- +- +- +- [AutoSize Property Overview](autosize-property-overview.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-tablelayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel](walkthrough-arranging-controls-on-windows-forms-using-a-flowlayoutpanel.md) +- [Walkthrough: Arranging Controls on Windows Forms Using Snaplines](walkthrough-arranging-controls-on-windows-forms-using-snaplines.md) diff --git a/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-used-to-list-options.md b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-used-to-list-options.md new file mode 100644 index 0000000000..b545f07fd1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/controls/windows-forms-controls-used-to-list-options.md @@ -0,0 +1,52 @@ +--- +title: Controls Used to List Options +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms controls, listing options" + - "option lists in Windows Forms" +ms.assetid: 5bc064c7-bc1f-4b62-8f4b-252f864b118e +--- +# Windows Forms Controls Used to List Options +You can add a variety of controls to a Windows Form if you want to provide users with a list of options to choose from. Depending on how much you want to restrict your users' input, you can add a control, a control, or a control. Use the following links to determine which control best suits your needs. + +## In This Section + [When to Use a Windows Forms ComboBox Instead of a ListBox](when-to-use-a-windows-forms-combobox-instead-of-a-listbox.md) + Recommends an appropriate list-based control depending on the needs and restrictions of your Windows Form. + + [How to: Access Specific Items in a Windows Forms ComboBox, ListBox, or CheckedListBox Control](access-specific-items-in-a-wf-combobox-listbox-or-checkedlistbox.md) + Gives instructions for programmatically determining which item in a list appears in a given position. + + [How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control](add-and-remove-items-from-a-wf-combobox.md) + Gives instructions for adding or removing items from a control's list of items. + + [How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control](create-a-lookup-table-for-a-wf-combobox-listbox.md) + Gives directions for displaying and storing form data in useful formats. + + [How to: Bind a Windows Forms ComboBox or ListBox Control to Data](how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md) + Gives directions for binding a list-based control to a data source. + + [How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control](sort-the-contents-of-a-wf-combobox-listbox-or-checkedlistbox-control.md) + Explains how to sort list data at its data source. + +## Reference + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + + + Describes this class and has links to all its members. + +## Related Sections + [CheckedListBox Control Overview](checkedlistbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [ComboBox Control Overview](combobox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [ListBox Control Overview](listbox-control-overview-windows-forms.md) + Explains what this control is and its key features and properties. + + [Controls to Use on Windows Forms](controls-to-use-on-windows-forms.md) + Provides a complete list of Windows Forms controls, with links to information on their use. diff --git a/dotnet-desktop-guide/framework/winforms/creating-a-new-windows-form.md b/dotnet-desktop-guide/framework/winforms/creating-a-new-windows-form.md new file mode 100644 index 0000000000..e4b39d8a7b --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/creating-a-new-windows-form.md @@ -0,0 +1,38 @@ +--- +title: "Creating a New Windows Form" +description: Find topics that introduce basic vocabulary, guidelines, and instructions you should understand to when you start to create a Windows Forms application. +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, getting started" + - "Windows Forms, creating a new form" +ms.assetid: c725559c-803e-4725-80fa-96aba93de29a +--- +# Creating a New Windows Form +This topic contains links to topics that describe how to create your first Windows Forms application. Also, the topics in this section introduce some of the basic vocabulary and guidelines that you should understand when you start to create a Windows Forms application. To learn more about Windows Forms applications, the controls you can use on them, events and handling events, and how to handle input from the user, see the related topic list. + +## In This Section + [Windows Forms Coordinates](windows-forms-coordinates.md) + Describes client and screen coordinates. + + [How to: Create a Windows Forms Application from the Command Line](how-to-create-a-windows-forms-application-from-the-command-line.md) + Describes how to create a basic Windows Form and compile it from the command line. + +## Reference + + Describes this class and contains links to all its members. + + + Describes this class and contains links to all its members. + +## Related Sections + [Handling User Input](./controls/handling-user-input.md) + Contains links to topics that discuss user input and how to handle it in Windows Forms applications. + + [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) + Contains links to topics that describe how to handle events in Windows Forms applications. + + [Changing the Appearance of Windows Forms](changing-the-appearance-of-windows-forms.md) + Contains links to topics that show how to change the appearance of Windows Forms applications. + + [Windows Forms Controls by Function](./controls/windows-forms-controls-by-function.md) + Contains links to topics that describe the controls you can use in Windows Forms applications. diff --git a/dotnet-desktop-guide/framework/winforms/creating-event-handlers-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/creating-event-handlers-in-windows-forms.md new file mode 100644 index 0000000000..8f99590782 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/creating-event-handlers-in-windows-forms.md @@ -0,0 +1,43 @@ +--- +title: "Create Event Handlers" +description: Learn how events in Windows Forms can be assigned to multiple handlers, and how the methods that handle particular events can be changed dynamically. +ms.date: "03/30/2017" +helpviewer_keywords: + - "event handling [Windows Forms]" + - "Windows Forms controls, event handling" + - "Windows Forms, event handling" + - "events [Windows Forms], event handlers" + - "event handlers [Windows Forms]" +ms.assetid: 6514e530-c6b8-489c-a8d2-eda7b7072701 +--- +# Creating Event Handlers in Windows Forms + +An event handler is a procedure in your code that determines what actions are performed when an event occurs, such as when the user clicks a button or a message queue receives a message. When an event is raised, the event handler or handlers that receive the event are executed. Events can be assigned to multiple handlers, and the methods that handle particular events can be changed dynamically. You can also use the Windows Forms Designer in Visual Studio to create event handlers. + +## In This Section + + [Events Overview](events-overview-windows-forms.md)\ + Explains the event model and the role of delegates. + + [Event Handlers Overview](event-handlers-overview-windows-forms.md)\ + Describes how to handle events. + + [How to: Create Event Handlers at Run Time for Windows Forms](how-to-create-event-handlers-at-run-time-for-windows-forms.md)\ + Gives directions for responding to system or user events dynamically. + + [How to: Connect Multiple Events to a Single Event Handler in Windows Forms](how-to-connect-multiple-events-to-a-single-event-handler-in-windows-forms.md)\ + Gives directions for assigning the same functionality to multiple controls through events. + + [Order of Events in Windows Forms](order-of-events-in-windows-forms.md)\ + Describes the order in which events are raised in Windows Forms controls. + + [How to: Create Event Handlers Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/zwwsdtbk(v=vs.100)) + Describes how to use the Windows Forms Designer to create event handlers. + +## Related Sections + + [Events](https://docs.microsoft.com/dotnet/standard/events/index)\ + Provides links to topics on handling and raising events using the .NET Framework. + + [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers)\ + Lists common issues that occur with event handlers in inherited components. diff --git a/dotnet-desktop-guide/framework/winforms/data-binding-and-windows-forms.md b/dotnet-desktop-guide/framework/winforms/data-binding-and-windows-forms.md new file mode 100644 index 0000000000..69fb103ef9 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/data-binding-and-windows-forms.md @@ -0,0 +1,56 @@ +--- +title: Data Binding +description: Learn how to bind to an array of values that you calculate at runtime, read from a file, or derive from the values of other controls in Windows Forms. +ms.date: "03/30/2017" +helpviewer_keywords: + - "master-details lists" + - "data [Windows Forms], data binding" + - "reports [Windows Forms], Windows Forms" + - "lookup tables [Windows Forms], data binding" + - "data [Windows Forms], complex data binding" + - "data binding [Windows Forms], Windows Forms" + - "data [Windows Forms], simple data binding" + - "Windows Forms controls, data binding" + - "data-bound controls [Windows Forms], Windows Forms" +ms.assetid: 419aac5e-819b-4aad-88b0-73a2f8c0bd27 +--- +# Data Binding and Windows Forms +In Windows Forms, you can bind to not just traditional data sources, but also to almost any structure that contains data. You can bind to an array of values that you calculate at run time, read from a file, or derive from the values of other controls. + + In addition, you can bind any property of any control to the data source. In traditional data binding, you typically bind the display property—for example, the property of a control—to the data source. With the .NET Framework, you also have the option of setting other properties through binding as well. You might use binding to perform the following tasks: + +- Setting the graphic of an image control. + +- Setting the background color of one or more controls. + +- Setting the size of controls. + + Essentially, data binding is an automatic way of setting any run-time accessible property of any control on a form. + +## Types of Data Binding + Windows Forms can take advantage of two types of data binding: simple binding and complex binding. Each offers different advantages. + +|Type of data binding|Description| +|--------------------------|-----------------| +|Simple data binding|The ability of a control to bind to a single data element, such as a value in a column in a dataset table. This is the type of binding typical for controls such as a control or control, which are controls that typically only displays a single value. In fact, any property on a control can be bound to a field in a database. There is extensive support for this feature in Visual Studio.

For more information, see:

- [Interfaces Related to Data Binding](interfaces-related-to-data-binding.md)
- [How to: Navigate Data in Windows Forms](how-to-navigate-data-in-windows-forms.md)
- [How to: Create a Simple-Bound Control on a Windows Form](how-to-create-a-simple-bound-control-on-a-windows-form.md)| +|Complex data binding|The ability of a control to bind to more than one data element, typically more than one record in a database. Complex binding is also called list-based binding. Examples of controls that support complex binding are the , , and controls. For an example of complex data binding, see [How to: Bind a Windows Forms ComboBox or ListBox Control to Data](./controls/how-to-bind-a-windows-forms-combobox-or-listbox-control-to-data.md).| + +## BindingSource Component + To simplify data binding, Windows Forms enables you to bind a data source to the component and then bind controls to the . You can use the in simple or complex binding scenarios. In either case, the acts as an intermediary between the data source and bound controls providing change notification currency management and other services. + +## Common Scenarios That Employ Data Binding + Nearly every commercial application uses information read from data sources of one type or another, usually through data binding. The following list shows a few of the most common scenarios that utilize data binding as the method of data presentation and manipulation. + +|Scenario|Description| +|--------------|-----------------| +|Reporting|Reports provide a flexible way for you to display and summarize your data in a printed document. It is very common to create a report that prints selected contents of a data source either to the screen or to a printer. Common reports include lists, invoices, and summaries. Items are usually formatted into columns of lists, with sub-items organized under each list item, but you should choose the layout that best suits the data.| +|Data entry|A common way to enter large amounts of related data or to prompt users for information is through a data entry form. Users can enter information or select choices using text boxes, option buttons, drop-down lists, and check boxes. Information is then submitted and stored in a database, whose structure is based on the information entered.| +|Master/detail relationship|A master/detail application is one format for looking at related data. Specifically, there are two tables of data with a relation connecting them—in the classic business example, a "Customers" table and an "Orders" table with a relationship between them linking customers and their respective orders. For more information about creating a master/detail application with two Windows Forms controls, see [How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls](./controls/create-a-master-detail-form-using-two-datagridviews.md)| +|Lookup Table|Another common data presentation/manipulation scenario is the table lookup. Often, as part of a larger data display, a control is used to display and manipulate data. The key is that the data displayed in the control is different than the data written to the database. For example, if you have a control displaying the items available from a grocery store, you would probably like to see the names of the products (bread, milk, eggs). However, to ease information retrieval within the database and for database normalization, you would probably store the information for the specific items of a given order as item numbers (#501, #603, and so on). Thus, there is an implicit connection between the "friendly name" of the grocery item in the control on your form and the related item number that is present in an order. This is the essence of a table lookup. For more information, see [How to: Create a Lookup Table with the Windows Forms BindingSource Component](./controls/how-to-create-a-lookup-table-with-the-windows-forms-bindingsource-component.md).| + +## See also + +- +- [Windows Forms Data Binding](windows-forms-data-binding.md) +- [How to: Bind the Windows Forms DataGrid Control to a Data Source](./controls/how-to-bind-the-windows-forms-datagrid-control-to-a-data-source.md) +- [BindingSource Component](./controls/bindingsource-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/data-sources-supported-by-windows-forms.md b/dotnet-desktop-guide/framework/winforms/data-sources-supported-by-windows-forms.md new file mode 100644 index 0000000000..64cbcd8c7c --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/data-sources-supported-by-windows-forms.md @@ -0,0 +1,58 @@ +--- +title: Supported Data Sources +ms.date: "03/30/2017" +helpviewer_keywords: + - "collections [Windows Forms], binding to" + - "OLE DB providers [Windows Forms], Windows Forms" + - "DataTable class [Windows Forms], binding and Windows Forms" + - "Windows Forms, data binding" + - "DataView class [Windows Forms], binding and Windows Forms" + - "DataViewManager class [Windows Forms], binding and Windows Forms" + - "Windows Forms, source data" + - "arrays [Windows Forms]" + - "data sources [Windows Forms]" + - "data providers [Windows Forms]" + - "DataSet class [Windows Forms], binding and Windows Forms" + - "data [Windows Forms], data providers" +ms.assetid: 3d2c43f6-462b-4d35-9c86-13e9afe012e1 +--- +# Data Sources Supported by Windows Forms +Traditionally, data binding has been used within applications to take advantage of data stored in databases. With Windows Forms data binding, you can access data from databases as well as data in other structures, such as arrays and collections, so long as certain minimum requirements have been met. + +## Structures to Bind To + In Windows Forms, you can bind to a wide variety of structures, from simple objects (simple binding) to complex lists such as ADO.NET data tables (complex binding). For simple binding, Windows Forms supports binding to the public properties on the simple object. Windows Forms list-based binding generally requires that the object support the interface or the interface. Additionally, if you are binding with through a component, you can bind to an object that supports the interface. For more information about interfaces related to data binding, see [Interfaces Related to Data Binding](interfaces-related-to-data-binding.md). + + The following list shows the structures you can bind to in Windows Forms. + + + A is the most common Windows Forms data source and acts a proxy between a data source and Windows Forms controls. The general usage pattern is to bind your controls to the and bind the to the data source (for example, an ADO.NET data table or a business object). The provides services that enable and improve the level of data binding support. For example, Windows Forms list based controls such as the and do not directly support binding to data sources however, you can enable this scenario by binding through a . In this case, the will convert the data source to an . + + Simple objects + Windows Forms supports data binding control properties to public properties on the instance of an object using the type. Windows Forms also supports binding list based controls, such as a to an object instance when a is used. + + array or collection + To act as a data source, a list must implement the interface; one example would be an array that is an instance of the class. For more information on arrays, see [How to: Create an Array of Objects (Visual Basic)](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/487y7874(v=vs.100)). + + In general, you should use when you create lists of objects for data binding. is a generic version of the interface. The interface extends the interface by adding properties, methods and events necessary for two-way data binding. + + + Windows Forms controls can be bound to data sources that only support the interface if they are bound through a component. + + ADO.NET data objects + ADO.NET provides a number of data structures suitable for binding to. Each varies in its sophistication and complexity. + +- . A is the essential building block of a , in that a number of columns comprise a table. Each has a property that determines the kind of data the column holds (for example, the make of an automobile in a table describing cars). You can simple-bind a control (such as a control's property) to a column within a data table. + +- . A is the representation of a table, with rows and columns, in ADO.NET. A data table contains two collections: , representing the columns of data in a given table (which ultimately determine the kinds of data that can be entered into that table), and , representing the rows of data in a given table. You can complex-bind a control to the information contained in a data table (such as binding the control to a data table). However, when you bind to a , you are a really binding to the table's default view. + +- . A is a customized view of a single data table that may be filtered or sorted. A data view is the data "snapshot" used by complex-bound controls. You can simple-bind or complex-bind to the data within a data view, but be aware that you are binding to a fixed "picture" of the data rather than a clean, updating data source. + +- . A is a collection of tables, relationships, and constraints of the data in a database. You can simple-bind or complex-bind to the data within a dataset, but be aware that you are binding to the default for the (see the next bullet point). + +- . A is a customized view of the entire , analogous to a , but with relations included. With a collection, you can set default filters and sort options for any views that the has for a given table. + +## See also + +- [Change Notification in Windows Forms Data Binding](change-notification-in-windows-forms-data-binding.md) +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/dialog-boxes-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/dialog-boxes-in-windows-forms.md new file mode 100644 index 0000000000..0ea8e15183 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/dialog-boxes-in-windows-forms.md @@ -0,0 +1,25 @@ +--- +title: "Dialog Boxes" +ms.date: "03/30/2017" +helpviewer_keywords: + - "dialog boxes [Windows Forms], Windows Forms" + - "Windows Forms dialog boxes" + - "dialogs [Windows Forms], using in Windows Forms" +ms.assetid: d43d022b-451b-490d-9386-dc79d98fbf8a +--- +# Dialog Boxes in Windows Forms +Dialog boxes are used to interact with the user and retrieve information. In simple terms, a dialog box is a form with its enumeration property set to `FixedDialog`. You can construct your own custom dialog boxes by using the Windows Forms Designer in Visual Studio. Add controls such as `Label`, `Textbox`, and `Button` to customize dialog boxes to your specific needs. The .NET Framework also includes predefined dialog boxes, such as **File Open** and message boxes, which you can adapt for your own applications. For more information, see [Dialog-Box Controls and Components](./controls/dialog-box-controls-and-components-windows-forms.md). + +## In This Section + [How to: Display Dialog Boxes for Windows Forms](how-to-display-dialog-boxes-for-windows-forms.md) + Gives directions for showing dialog boxes. + +## Related Sections + [Dialog-Box Controls and Components](./controls/dialog-box-controls-and-components-windows-forms.md) + Lists the predefined dialog box controls. + + [Changing the Appearance of Windows Forms](changing-the-appearance-of-windows-forms.md) + Contains links to topics that describe how to change the appearance of Windows Forms applications. + + [TabControl Control Overview](./controls/tabcontrol-control-overview-windows-forms.md) + Explains how you incorporate the tab control into a dialog box. diff --git a/dotnet-desktop-guide/framework/winforms/drag-and-drop-functionality-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/drag-and-drop-functionality-in-windows-forms.md new file mode 100644 index 0000000000..44e398b8b6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/drag-and-drop-functionality-in-windows-forms.md @@ -0,0 +1,42 @@ +--- +title: "Drag-and-Drop Functionality" +ms.date: "03/30/2017" +helpviewer_keywords: + - "drag and drop [Windows Forms], Windows Forms" + - "Windows Forms, drag and drop" +ms.assetid: 65cd2c03-8782-474e-b958-cbe43eeb902c +--- +# Drag-and-Drop Functionality in Windows Forms +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. Also see [Drag-and-Drop Operations and Clipboard Support](./advanced/drag-and-drop-operations-and-clipboard-support.md). + +## Performing Drag-and-Drop Operations + To perform a drag-and-drop operation, use the method of the class. For more information about how a drag-and-drop operation is performed, see . To get the rectangle that the mouse pointer must be dragged over before a drag-and-drop operation begins, use the property of the class. + +## Events Related to Drag-and-Drop Operations + 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. + +### Events on the Current 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 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. + +## See also + +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/ensure-the-selected-row-in-a-child-table-correct.md b/dotnet-desktop-guide/framework/winforms/ensure-the-selected-row-in-a-child-table-correct.md new file mode 100644 index 0000000000..0fadbf8858 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/ensure-the-selected-row-in-a-child-table-correct.md @@ -0,0 +1,82 @@ +--- +title: "How to: Ensure the Selected Row in a Child Table Remains at the Correct Position" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "master-details view" + - "row position [Windows Forms]" + - "parent/child view [Windows Forms]" + - "resetting child position" + - "data binding [.NET Framework], row selection" + - "caching [.NET Framework], child position" + - "child position" + - "master/details view [Windows Forms]" + - "child tables row selection" + - "current child position" +ms.assetid: c5fa2562-43a4-46fa-a604-52d8526a87bd +--- +# How to: Ensure the Selected Row in a Child Table Remains at the Correct Position +Oftentimes when you work with data binding in Windows Forms, you will display data in what is called a parent/child or master/details view. This refers to a data-binding scenario where data from the same source is displayed in two controls. Changing the selection in one control causes the data displayed in the second control to change. For example, the first control might contain a list of customers and the second a list of orders related to the selected customer in the first control. + + Starting with the .NET Framework version 2.0, when you display data in a parent/child view you might have to take extra steps to make sure that the currently selected row in the child table is not reset to the first row of the table. In order to do this, you will have to cache the child table position and reset it after the parent table changes. Typically the child reset occurs the first time a field in a row of the parent table changes. + +### To Cache the Current Child Position + +1. Declare an integer variable to store the child list position and a Boolean variable to store whether to cache the child position. + + [!code-csharp[System.Windows.Forms.CurrencyManagerReset#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs#4)] + [!code-vb[System.Windows.Forms.CurrencyManagerReset#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb#4)] + +2. Handle the event for the binding's and check for a of . + +3. Check the current position of the . If it is greater than first entry in the list (typically 0), save it to a variable. + + [!code-csharp[System.Windows.Forms.CurrencyManagerReset#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.CurrencyManagerReset#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb#2)] + +4. Handle the parent list's event for the parent currency manager. In the handler, set the Boolean value to indicate it is not a caching scenario. If the occurs, the change to the parent is a list position change and not an item value change. + + [!code-csharp[System.Windows.Forms.CurrencyManagerReset#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs#5)] + [!code-vb[System.Windows.Forms.CurrencyManagerReset#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb#5)] + +### To Reset the Child Position + +1. Handle the event for the child binding's . + +2. Reset the child table position to the cached position saved in the previous procedure. + + [!code-csharp[System.Windows.Forms.CurrencyManagerReset#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.CurrencyManagerReset#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb#3)] + +## Example + The following example demonstrates how to save the current position on the .for a child table and reset the position after an edit is completed on the parent table. This example contains two controls bound to two tables in a using a component. A relation is established between the two tables and the relation is added to the . The position in the child table is initially set to the third row for demonstration purposes. + + [!code-csharp[System.Windows.Forms.CurrencyManagerReset#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.CurrencyManagerReset#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb#1)] + + To test the code example, perform the following steps: + +1. Run the example. + +2. Make sure the **Cache and reset position** check box is selected. + +3. Click the **Clear parent field** button to cause a change in a field of the parent table. Notice that the selected row in the child table does not change. + +4. Close and run the example again. You need to do this because the reset behavior occurs only on the first change in the parent row. + +5. Clear the **Cache and reset position** check box. + +6. Click the **Clear parent field** button. Notice that the selected row in the child table changes to the first row. + +## Compiling the Code + This example requires: + +- References to the System, System.Data, System.Drawing, System.Windows.Forms, and System.XML assemblies. + +## See also + +- [How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized](multiple-controls-bound-to-data-source-synchronized.md) +- [BindingSource Component](./controls/bindingsource-component.md) +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/event-handlers-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/event-handlers-overview-windows-forms.md new file mode 100644 index 0000000000..e12e6b52d5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/event-handlers-overview-windows-forms.md @@ -0,0 +1,48 @@ +--- +title: "Event Handlers Overview" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms, event handling" + - "event handling [Windows Forms], Windows Forms" + - "event handlers [Windows Forms], about event handlers" +ms.assetid: 228112e1-1711-42ee-8ffa-ff3555bffe66 +--- +# Event Handlers Overview (Windows Forms) +An event handler is a method that is bound to an event. When the event is raised, the code within the event handler is executed. Each event handler provides two parameters that allow you to handle the event properly. The following example shows an event handler for a control's event. + +```vb +Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click + +End Sub +``` + +```csharp +private void button1_Click(object sender, System.EventArgs e) +{ + +} +``` + +```cpp +private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + + } +``` + + The first parameter,`sender`, provides a reference to the object that raised the event. The second parameter, `e`, in the example above, passes an object specific to the event that is being handled. By referencing the object's properties (and, sometimes, its methods), you can obtain information such as the location of the mouse for mouse events or data being transferred in drag-and-drop events. + + Typically each event produces an event handler with a different event-object type for the second parameter. Some event handlers, such as those for the and events, have the same object type for their second parameter. For these types of events, you can use the same event handler to handle both events. + + You can also use the same event handler to handle the same event for different controls. For example, if you have a group of controls on a form, you could create a single event handler for the event and have each control's event bound to the single event handler. For more information, see [How to: Connect Multiple Events to a Single Event Handler in Windows Forms](how-to-connect-multiple-events-to-a-single-event-handler-in-windows-forms.md). + +## See also + +- [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) +- [Events Overview](events-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/events-overview-windows-forms.md b/dotnet-desktop-guide/framework/winforms/events-overview-windows-forms.md new file mode 100644 index 0000000000..34925561c6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/events-overview-windows-forms.md @@ -0,0 +1,43 @@ +--- +title: "Events Overview" +ms.date: "03/30/2017" +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" +ms.assetid: 814a6a43-a312-4791-88d8-f75f9a4f8c4c +--- +# Events Overview (Windows Forms) +An event is an action which 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. + + 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 is code in the 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 [Events](https://docs.microsoft.com/dotnet/standard/events/index). + +## Delegates and Their Role + Delegates are classes commonly used within the .NET Framework 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. In addition, 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 [Events](https://docs.microsoft.com/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 (or the Windows) 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 would not logically repeat multiple times per event. For information about how to create a multicast delegate, see [How to combine delegates (Multicast Delegates)](https://docs.microsoft.com/dotnet/csharp/programming-guide/delegates/how-to-combine-delegates-multicast-delegates). + + A multicast delegate maintains an invocation list of the methods it is 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 does not 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 + +- [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) +- [Event Handlers Overview](event-handlers-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/getting-started-with-windows-forms.md b/dotnet-desktop-guide/framework/winforms/getting-started-with-windows-forms.md new file mode 100644 index 0000000000..b015b3c779 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/getting-started-with-windows-forms.md @@ -0,0 +1,55 @@ +--- +title: "Getting Started" +description: Learn how to use Windows Forms to create powerful Windows-based applications that display data, handle user input, and help you deploy your applications. +ms.date: "03/30/2017" +f1_keywords: + - "Designer_System.Windows.Forms.Design.FormDocumentDesigner" + - "vb.wfc.formdesigner" +helpviewer_keywords: + - "Windows Forms, getting started" + - "getting started [Windows Forms], Windows Forms" +ms.assetid: a031aa58-5027-4082-b590-df7c12c77dec +--- +# Getting Started with Windows Forms +With Windows Forms, you can create powerful Windows-based applications. The following topics describe in-depth how to harness the power of Windows Forms to display data, handle user input, and deploy your applications easily and with enhanced security. + +## In This Section + [Windows Forms Overview](windows-forms-overview.md) + Contains an overview of Windows Forms and smart client applications. + + [Creating a New Windows Form](creating-a-new-windows-form.md) + Contains links to topics that describe basic concepts for creating Windows Forms applications. + + [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) + Contains links to topics that describe how to create Windows Forms event handlers. + + [Adjusting the Size and Scale of Windows Forms](adjusting-the-size-and-scale-of-windows-forms.md) + Contains links to topics that show how to adjust the size and scale of Windows Forms. + + [Changing the Appearance of Windows Forms](changing-the-appearance-of-windows-forms.md) + Contains links to topics that show how to change the appearance of Windows Forms applications. + + [Windows Forms Controls](./controls/index.md) + Contains links to topics that describe and show how to use Windows Forms controls and components. + + [User Input in Windows Forms](user-input-in-windows-forms.md) + Contains links to topics that describe and show how to handle input from the user in Windows Forms applications. + + [Dialog Boxes in Windows Forms](dialog-boxes-in-windows-forms.md) + Contains links to topics that describe the different dialog boxes for use in Windows Forms. + + [Windows Forms Data Binding](windows-forms-data-binding.md) + Contains links to topics that describe the Windows Forms data binding architecture and how to use it in Windows Forms applications. + + [Windows Forms Security](windows-forms-security.md) + Contains links to topics that describe how to build Windows Forms applications that have enhanced security. + + [ClickOnce Deployment for Windows Forms](clickonce-deployment-for-windows-forms.md) + Contains links to topics that describe how to easily deploy Windows Forms applications. + + [How to: Access Keyed Collections in Windows Forms](how-to-access-keyed-collections-in-windows-forms.md) + Demonstrates how to access collections with keys rather than indexes. + +## Related Sections + [Enhancing Windows Forms Applications](./advanced/index.md) + Contains links to topics that describe more advanced concepts for creating Windows Forms applications. diff --git a/dotnet-desktop-guide/framework/winforms/high-dpi-support-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/high-dpi-support-in-windows-forms.md new file mode 100644 index 0000000000..db79452cea --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/high-dpi-support-in-windows-forms.md @@ -0,0 +1,130 @@ +--- +title: "High DPI support" +description: Learn about support in Windows Forms for common high DPI and dynamic DPI scenarios. Also learn how to configure Windows Forms applications for high DPI support. +ms.date: "05/16/2017" +helpviewer_keywords: + - "High DPI in Windows Forms" + - "Dynamic rescaling in Windows Forms" + - "Windows Forms layout" + - "Windows Forms dynamic resizing" +ms.assetid: 075ea4c3-900c-4f8a-9dd2-13ea6804346b +--- + +# High DPI support in Windows Forms + +Starting with the .NET Framework 4.7, Windows Forms includes enhancements for common high DPI and dynamic DPI scenarios. These include: + +- Improvements in the scaling and layout of a number of Windows Forms controls, such as the control and the control. + +- Single-pass scaling. In the .NET Framework 4.6 and earlier versions, scaling was performed through multiple passes, which caused some controls to be scaled more than was necessary. + +- Support for dynamic DPI scenarios in which the user changes the DPI or scale factor after a Windows Forms application has been launched. + +In versions of the .NET Framework starting with the .NET Framework 4.7, enhanced high DPI support is an opt-in feature. You must configure your application to take advantage of it. + +## Configuring your Windows Forms app for high DPI support + +The new Windows Forms features that support high DPI awareness are available only in applications that target the .NET Framework 4.7 and are running on Windows operating systems starting with the Windows 10 Creators Update. + +In addition, to configure high DPI support in your Windows Forms application, you must do the following: + +- Declare compatibility with Windows 10. + + To do this, add the following to your manifest file: + + ```xml + + + + + + + ``` + +- Enable per-monitor DPI awareness in the *app.config* file. + + Windows Forms introduces a new [``](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/winforms/index) element to support new features and customizations added starting with the .NET Framework 4.7. To take advantage of the new features that support high DPI, add the following to your application configuration file. + + ```xml + + + + ``` + + > [!IMPORTANT] + > In previous versions of the .NET Framework, you used the manifest to add high DPI support. This approach is no longer recommended, since it overrides settings defined on the app.config file. + +- Call the static method. + + This should be the first method call in your application entry point. For example: + + ```csharp + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form2()); + } + ``` + +## Opting out of individual high DPI features + +Setting the `DpiAwareness` value to `PerMonitorV2` enables all high DPI awareness features supported by .NET Framework versions starting with the .NET Framework 4.7. Typically, this is adequate for most Windows Forms applications. However, you may want to opt out of one or more individual features. The most important reason for doing this is that your existing application code already handles that feature. For example, if your application handles auto scaling, you might want to disable the auto-resizing feature as follows: + +```xml + + + + +``` + +For a list of individual keys and their values, see [Windows Forms Add Configuration Element](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/winforms/windows-forms-add-configuration-element). + +## New DPI change events + +Starting with the .NET Framework 4.7, three new events allow you to programmatically handle dynamic DPI changes: + +- , which is fired when the DPI setting for a control is changed programmatically after a DPI change event for it's parent control or form has occurred. +- , which is fired when the DPI setting for a control is changed programmatically before a DPI change event for its parent control or form has occurred. +- , which is fired when the DPI setting changes on the display device where the form is currently displayed. + +## New helper methods and properties + +The .NET Framework 4.7 also adds a number of new helper methods and properties that provide information about DPI scaling and allow you to perform DPI scaling. These include: + +- , which converts a value from logical to device pixels. + +- , which scales a bitmap image to the logical DPI for a device. + +- , which returns the DPI for the current device. + +## Versioning considerations + +In addition to running on .NET Framework 4.7 and Windows 10 Creators Update, your application may also run in an environment in which it isn't compatible with high DPI improvements. In this case, you'll need to develop a fallback for your application. You can do this to perform [custom drawing](./controls/user-drawn-controls.md) to handle scaling. + +To do this, you also need to determine the operating system on which your app is running. You can do that with code like the following: + +```csharp +// Create a reference to the OS version of Windows 10 Creators Update. +Version OsMinVersion = new Version(10, 0, 15063, 0); + +// Access the platform/version of the current OS. +Console.WriteLine(Environment.OSVersion.Platform.ToString()); +Console.WriteLine(Environment.OSVersion.VersionString); + +// Compare the current version to the minimum required version. +Console.WriteLine(Environment.OSVersion.Version.CompareTo(OsMinVersion)); +``` + +Note that your application won't successfully detect Windows 10 if it wasn't listed as a supported operating system in the application manifest. + +You can also check the version of the .NET Framework that the application was built against: + +```csharp +Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName); +``` + +## See also + +- [Windows Forms Add Configuration Element](https://docs.microsoft.com/dotnet/framework/configure-apps/file-schema/winforms/windows-forms-add-configuration-element) +- [Adjusting the Size and Scale of Windows Forms](adjusting-the-size-and-scale-of-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-keyboard-input-works.md b/dotnet-desktop-guide/framework/winforms/how-keyboard-input-works.md new file mode 100644 index 0000000000..a8582f943d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-keyboard-input-works.md @@ -0,0 +1,72 @@ +--- +title: "How Keyboard Input Works" +ms.date: "03/30/2017" +helpviewer_keywords: + - "keyboard input [Windows Forms], about keyboard input" + - "keyboards [Windows Forms], keyboard input" + - "Windows Forms, keyboard input" +ms.assetid: 9a29433c-a180-49bb-b74c-d187786584c8 +--- +# How Keyboard Input Works +Windows Forms processes keyboard input by raising keyboard events in response to Windows messages. Most Windows Forms applications process keyboard input exclusively by handling the keyboard events. However, you need to understand how keyboard messages work so you can implement more advanced keyboard-input scenarios, such as intercepting keys before they reach a control. This topic describes the types of key data that Windows Forms recognizes and provides an overview of how keyboard messages are routed. For information about keyboard events, see [Using Keyboard Events](using-keyboard-events.md). + +## 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. Alternatively, you can use , exposed by Visual Basic programming interface, to discover which keys were pressed and send keys. For more information, see [Accessing the Keyboard](https://docs.microsoft.com/dotnet/visual-basic/developing-apps/programming/computer-resources/accessing-the-keyboar). + +## 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: + +1. The user pushes the "a" key, the key is preprocessed, dispatched, and a event occurs. + +2. 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. + +3. 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 [Overriding properties and methods in derived classes](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/objects-and-classes/inheritance-basics#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 + +- +- +- +- [My.Computer.Keyboard Object](https://docs.microsoft.com/dotnet/visual-basic/language-reference/objects/my-computer-keyboard-object) +- [Accessing the Keyboard](https://docs.microsoft.com/dotnet/visual-basic/developing-apps/programming/computer-resources/accessing-the-keyboar) +- [Using Keyboard Events](using-keyboard-events.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-mouse-input-works-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-mouse-input-works-in-windows-forms.md new file mode 100644 index 0000000000..db02ca2d11 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-mouse-input-works-in-windows-forms.md @@ -0,0 +1,53 @@ +--- +title: "How Mouse Input Works" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, mouse input" + - "mouse [Windows Forms], input" +ms.assetid: 48fc5240-75a6-44bf-9fce-6aa21b49705a +--- +# How Mouse Input Works in Windows Forms +Receiving and handling mouse input is an important part of every Windows application. You can handle mouse events to perform an action in your application, or use mouse location information to perform hit testing or other actions. In addition, you can change the way the controls in your application handle mouse input. This topic describes these mouse events in detail, and how to obtain and change system settings for the mouse. For more information about the data provided with the mouse events and the order in which the mouse click events are raised, see [Mouse Events in Windows Forms](mouse-events-in-windows-forms.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 subsequently use mouse location information to perform 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 perform a specific action. + +## 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 are 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.| + +## Changing Mouse Input and Detecting System 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 or double-click behavior or if the control will handle its own mouse processing. In addition, 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 operating system to consider the mouse action 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.| + +## See also + +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) +- [Mouse Capture in Windows Forms](mouse-capture-in-windows-forms.md) +- [Mouse Pointers in Windows Forms](mouse-pointers-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-access-keyed-collections-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-access-keyed-collections-in-windows-forms.md new file mode 100644 index 0000000000..4ea714f2c7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-access-keyed-collections-in-windows-forms.md @@ -0,0 +1,52 @@ +--- +title: "How to: Access Keyed Collections" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "keyed collections [Windows Forms]" + - "collections [Windows Forms], accessing with keys" +ms.assetid: b9b79b8b-d9bf-4f8c-b9d6-9578bc3219d3 +--- +# How to: Access Keyed Collections in Windows Forms + +- You can access individual collection items by key. This functionality has been added to many collection classes that are typically used by Windows Forms applications. The following list shows some of the collection classes that have accessible keyed collections: + +- + +- + +- + +- + +- + + The key associated with an item in a collection is typically the name of the item. The following procedures show you how to use collection classes to perform common tasks. + +### To find and give focus to a nested control in a control collection + +- Use the and methods to specify the name of the control to find and give focus to. + + [!code-csharp[System.Windows.Forms.KeyedCollectionsEx#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.KeyedCollectionsEx#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/VB/Form1.vb#1)] + +### To access an image in an image collection + +- Use the property to specify the name of the image you want to access. + + [!code-csharp[System.Windows.Forms.KeyedCollectionsEx#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.KeyedCollectionsEx#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/VB/Form1.vb#2)] + +### To set a tab page as the selected tab + +- Use the property together with the property to specify the name of the tab page to set as the selected tab. + + [!code-csharp[System.Windows.Forms.KeyedCollectionsEx#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.KeyedCollectionsEx#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/VB/Form1.vb#3)] + +## See also + +- [Getting Started with Windows Forms](getting-started-with-windows-forms.md) +- [How to: Add or Remove Images with the Windows Forms ImageList Component](./controls/how-to-add-or-remove-images-with-the-windows-forms-imagelist-component.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-apply-the-propertynamechanged-pattern.md b/dotnet-desktop-guide/framework/winforms/how-to-apply-the-propertynamechanged-pattern.md new file mode 100644 index 0000000000..5fa2298e92 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-apply-the-propertynamechanged-pattern.md @@ -0,0 +1,29 @@ +--- +title: "How to: Apply the PropertyNameChanged Pattern" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "custom controls [Windows Forms], property changes (using code)" + - "data binding [Windows Forms], custom controls" + - "PropertyNameChanged pattern [Windows Forms], applying" +ms.assetid: aa47ddf6-5223-40c4-833f-a78992194836 +--- +# How to: Apply the PropertyNameChanged Pattern +The following code example demonstrates how to apply the *PropertyName*Changed pattern to a custom control. Apply this pattern when you implement custom controls that are used with the Windows Forms data binding engine. + +## Example + [!code-csharp[System.Windows.Forms.ChangeNotification#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.ChangeNotification#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/VB/Form1.vb#3)] + +## Compiling the Code + To compile the previous code example: + +- Paste the code into an empty code file. You must use the custom control on a Windows Form that contains a `Main` method. + +## See also + +- [How to: Implement the INotifyPropertyChanged Interface](how-to-implement-the-inotifypropertychanged-interface.md) +- [Change Notification in Windows Forms Data Binding](change-notification-in-windows-forms-data-binding.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-change-the-borders-of-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-change-the-borders-of-windows-forms.md new file mode 100644 index 0000000000..a72af15e15 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-change-the-borders-of-windows-forms.md @@ -0,0 +1,44 @@ +--- +title: Change form borders +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms, changing the borders" +ms.assetid: b3d5fa56-80c6-4b10-b505-f9672307ed55 +--- +# How to: Change the Borders of Windows Forms +You have several border styles to choose from when you are determining the appearance and behavior of your Windows Forms. By changing the property, you can control the resizing behavior of the form. In addition, setting the affects how the caption bar is displayed as well as what buttons might appear on it. For more information, see . + + There is extensive support for this task in Visual Studio. + + See also [How to: Change the Borders of Windows Forms Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/yettzh3e(v=vs.100)). + +### To set the border style of Windows Forms programmatically + +- Set the property to the style you want. The following code example sets the border style of form `DlgBx1` to . + + ```vb + DlgBx1.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog + ``` + + ```csharp + DlgBx1.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + ``` + + ```cpp + DlgBx1->FormBorderStyle = + System::Windows::Forms::FormBorderStyle::FixedDialog; + ``` + + Also see [How to: Create Dialog Boxes at Design Time](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/55cz5x2c(v=vs.100)). + + Additionally, if you have chosen a border style for the form that provides optional **Minimize** and **Maximize** buttons, you can specify whether you want either or both of these buttons to be functional. These buttons are useful when you want to closely control the user experience. The **Minimize** and **Maximize** buttons are enabled by default, and their functionality is manipulated through the **Properties** window. + +## See also + +- +- +- [Getting Started with Windows Forms](getting-started-with-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-connect-multiple-events-to-a-single-event-handler-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-connect-multiple-events-to-a-single-event-handler-in-windows-forms.md new file mode 100644 index 0000000000..b7502e8a19 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-connect-multiple-events-to-a-single-event-handler-in-windows-forms.md @@ -0,0 +1,61 @@ +--- +title: "How to: Connect Multiple Events to a Single Event Handler" +description: Learn how to connect multiple events to a single event handler in Windows Forms by using the Events view of the Properties window in C#. +ms.date: "03/30/2017" +dev_langs: + - "vb" +helpviewer_keywords: + - "events [Windows Forms], connecting multiple to single event handler" + - "event handlers [Windows Forms], connecting events to" + - "menus [Windows Forms], event-handling methods for multiple menu items" + - "Windows Forms controls, events" + - "menu items [Windows Forms], multicasting event-handling methods" +ms.assetid: 5a20749a-41b5-4acc-8eb1-9e5040b0a2c4 +--- +# How to: Connect Multiple Events to a Single Event Handler in Windows Forms +In your application design, you may find it necessary to use a single event handler for multiple events or have multiple events perform the same procedure. For example, it is often a powerful time-saver to have a menu command raise the same event as a button on your form does if they expose the same functionality. You can do this by using the Events view of the Properties window in C# or using the `Handles` keyword and the **Class Name** and **Method Name** drop-down boxes in the Visual Basic Code Editor. + +### To connect multiple events to a single event handler in Visual Basic + +1. Right-click the form and choose **View Code**. + +2. From the **Class Name** drop-down box, select one of the controls that you want to have the event handler handle. + +3. From the **Method Name** drop-down box, select one of the events that you want the event handler to handle. + +4. The Code Editor inserts the appropriate event handler and positions the insertion point within the method. In the example below, it is the event for the control. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + ' Add event-handler code here. + End Sub + ``` + +5. Append the other events you would like handled to the `Handles` clause. + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click + ' Add event-handler code here. + End Sub + ``` + +6. Add the appropriate code to the event handler. + +### To connect multiple events to a single event handler in C\# + +1. Select the control to which you want to connect an event handler. + +2. In the Properties window, click the **Events** button (![Events Button](./media/vxeventsbutton-propertieswindow.png "vxEventsButton_PropertiesWindow")). + +3. Click the name of the event that you want to handle. + +4. In the value section next to the event name, click the drop-down button to display a list of existing event handlers that match the method signature of the event you want to handle. + +5. Select the appropriate event handler from the list. + + Code will be added to the form to bind the event to the existing event handler. + +## See also + +- [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) +- [Event Handlers Overview](event-handlers-overview-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-create-a-bound-control-and-format-the-displayed-data.md b/dotnet-desktop-guide/framework/winforms/how-to-create-a-bound-control-and-format-the-displayed-data.md new file mode 100644 index 0000000000..eee980cb52 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-create-a-bound-control-and-format-the-displayed-data.md @@ -0,0 +1,51 @@ +--- +title: "How to: Create a Bound Control and Format the Displayed Data" +ms.date: "03/30/2017" +helpviewer_keywords: + - "data [Windows Forms], formatting" + - "bound controls [Windows Forms], creating" + - "bound controls [Windows Forms], formatting data" +ms.assetid: d5a56228-899d-41d9-8af8-87b3f4ec2f94 +--- +# How to: Create a Bound Control and Format the Displayed Data + +With Windows Forms data binding, you can format the data displayed in a data-bound control by using the **Formatting and Advanced Binding** dialog box. + +## To bind a control and format the displayed data + +1. Connect to a data source. For more information, see [Connecting to a Data Source](https://docs.microsoft.com/dotnet/framework/data/adonet/connecting-to-a-data-source). + +2. In Visual Studio, select the control on the form, and then open the **Properties** window. + +3. Expand the **(DataBindings)** property, and then in the **(Advanced)** box, click the ellipsis button (![The Ellipsis button (...) in the Properties window of Visual Studio](./media/how-to-create-a-bound-control-and-format-the-displayed-data/visual-studio-ellipsis-button.png)) to display the **Formatting and Advanced Binding** dialog box, which has a complete list of properties for that control. + +4. Select the property you want to bind, and then select the **Binding** arrow. + + A list of available data sources is displayed. + +5. Expand the data source you want to bind to until you find the single data element you want. + + For example, if you are binding to a column value in a dataset's table, expand the name of the dataset, and then expand the table name to display column names. + +6. Select the name of an element to bind to. + +7. In the **Format type** box, select the format you want to apply to the data displayed in the control. + + In every case, you can specify the value displayed in the control if the data source contains . Otherwise, the options vary slightly, depending on the format type you choose. The following table shows the format types and options. + + |Format type|Formatting option| + |-----------------|-----------------------| + |No Formatting|No options.| + |Numeric|Specify number of decimal places by using **Decimal places** up-down control.| + |Currency|Specify number of decimal places by using **Decimal places** up-down control.| + |Date Time|Select how the date and time should be displayed by selecting one of the items in the **Type** selection box.| + |Scientific|Specify number of decimal places by using **Decimal places** up-down control.| + |Custom|Specify a custom format string using.

For more information, see [Formatting Types](https://docs.microsoft.com/dotnet/standard/base-types/formatting-types). **Note:** Custom format strings are not guaranteed to successfully round trip between the data source and bound control. Instead handle the or event for the binding and apply custom formatting in the event-handling code.| + +8. Select **OK** to close the **Formatting and Advanced Binding** dialog box and return to the Properties window. + +## See also + +- [How to: Create a Simple-Bound Control on a Windows Form](how-to-create-a-simple-bound-control-on-a-windows-form.md) +- [User Input Validation in Windows Forms](user-input-validation-in-windows-forms.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-create-a-simple-bound-control-on-a-windows-form.md b/dotnet-desktop-guide/framework/winforms/how-to-create-a-simple-bound-control-on-a-windows-form.md new file mode 100644 index 0000000000..2a44d142a8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-create-a-simple-bound-control-on-a-windows-form.md @@ -0,0 +1,44 @@ +--- +title: "How to: Create a Simple-Bound Control on a Windows Form" +ms.date: "03/30/2017" +helpviewer_keywords: + - "data binding [Windows Forms], simple data binding" + - "Windows Forms controls, data binding" +ms.assetid: 3bcaded8-0f1a-4cc0-8830-f59be253bf4e +--- +# How to: Create a simple-bound control on a Windows Form + +With *simple binding*, you can display a single data element, such as a column value from a dataset table, in a control. You can simple-bind any property of a control to a data value. + +## To simple-bind a control + +1. Connect to a data source. For more information, see [Connecting to a Data Source](https://docs.microsoft.com/dotnet/framework/data/adonet/connecting-to-a-data-source). + +2. In Visual Studio, select the control on the form and display the **Properties** window. + +3. Expand the **(DataBindings)** property. + + The properties most often bound are displayed underneath the **(DataBindings)** property. For example, in most controls, the **Text** property is most frequently bound. + +4. If the property you want to bind is not one of the commonly bound properties, click the **Ellipsis** button (![The Ellipsis button (...) in the Properties window of Visual Studio.](./media/how-to-create-a-simple-bound-control-on-a-windows-form/visual-studio-ellipsis-button.png)) in the **(Advanced)** box to display the **Formatting and Advanced Binding** dialog box with a complete list of properties for that control. + +5. Select the property you want to bind and click the drop-down arrow under **Binding**. + + A list of available data sources is displayed. + +6. Expand the data source you want to bind to until you find the single data element you want. For example, if you are binding to a column value in a dataset's table, expand the name of the dataset, and then expand the table name to display column names. + +7. Click the name of an element to bind to. + +8. If you were working in the **Formatting and Advanced Binding** dialog box, click **OK** to return to the **Properties** window. + +9. If you want to bind additional properties of the control, repeat steps 3 through 7. + + > [!NOTE] + > Because simple-bound controls show only a single data element, it is very typical to include navigation logic in a Windows Form with simple-bound controls. + +## See also + +- +- [Windows Forms Data Binding](windows-forms-data-binding.md) +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-create-a-windows-forms-application-from-the-command-line.md b/dotnet-desktop-guide/framework/winforms/how-to-create-a-windows-forms-application-from-the-command-line.md new file mode 100644 index 0000000000..2106c71ed6 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-create-a-windows-forms-application-from-the-command-line.md @@ -0,0 +1,115 @@ +--- +title: Create a Windows Forms application from the command line +titleSuffix: "" +description: Learn how to complete the basic steps to create and run a Windows Forms application from the command line. +ms.date: "03/14/2018" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, application development from command line" + - "Windows Forms, getting started" + - "Windows Forms, creating basic form" +ms.assetid: 45ad3f8b-1c26-4c9f-91a9-3bb0759a47a4 +--- +# How to: Create a Windows Forms application from the command line + +The following procedures describe the basic steps that you must complete to create and run a Windows Forms application from the command line. There is extensive support for these procedures in Visual Studio. Also see [Walkthrough: Hosting a Windows Forms Control in WPF](https://docs.microsoft.com/dotnet/framework/wpf/advanced/walkthrough-hosting-a-windows-forms-control-in-wpf). + +## Procedure + +#### To create the form + +1. In an empty code file, type the following `Imports` or `using` statements: + + [!code-csharp[System.Windows.Forms.BasicForm#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.BasicForm#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb#2)] + +2. Declare a class named `Form1` that inherits from the Form class: + + [!code-csharp[System.Windows.Forms.BasicForm#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.BasicForm#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb#3)] + +3. Create a parameterless constructor for `Form1`. + + You will add more code to the constructor in a subsequent procedure. + + [!code-csharp[System.Windows.Forms.BasicForm#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs#4)] + [!code-vb[System.Windows.Forms.BasicForm#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb#4)] + +4. Add a `Main` method to the class. + + 1. Apply the to the C# `Main` method to specify your Windows Forms application is a single-threaded apartment. (The attribute is not necessary in Visual Basic, since Windows forms applications developed with Visual Basic use a single-threaded apartment model by default.) + + 2. Call to apply operating system styles to your application. + + 3. Create an instance of the form and run it. + + [!code-csharp[System.Windows.Forms.BasicForm#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs#5)] + [!code-vb[System.Windows.Forms.BasicForm#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb#5)] + +#### To compile and run the application + +1. At the .NET Framework command prompt, navigate to the directory you created the `Form1` class. + +2. Compile the form. + + - If you are using C#, type: `csc form1.cs` + + `-or-` + + - If you are using Visual Basic, type: `vbc form1.vb` + +3. At the command prompt, type: `Form1.exe` + +## Adding a control and handling an event + +The previous procedure steps demonstrated how to just create a basic Windows Form that compiles and runs. The next procedure will show you how to create and add a control to the form, and handle an event for the control. For more information about the controls you can add to Windows Forms, see [Windows Forms Controls](./controls/index.md). + + In addition to understanding how to create Windows Forms applications, you should understand event-based programming and how to handle user input. For more information, see [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md), and [Handling User Input](./controls/handling-user-input.md) + +#### To declare a button control and handle its click event + +1. Declare a button control named `button1`. + +2. In the constructor, create the button and set its , and properties. + +3. Add the button to the form. + + The following code example demonstrates how to declare the button control: + + [!code-csharp[System.Windows.Forms.FormWithButton#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.FormWithButton#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb#2)] + +4. Create a method to handle the event for the button. + +5. In the click event handler, display a with the message, "Hello World". + + The following code example demonstrates how to handle the button control's click event: + + [!code-csharp[System.Windows.Forms.FormWithButton#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.FormWithButton#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb#3)] + +6. Associate the event with the method you created. + + The following code example demonstrates how to associate the event with the method. + + [!code-csharp[System.Windows.Forms.FormWithButton#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs#4)] + [!code-vb[System.Windows.Forms.FormWithButton#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb#4)] + +7. Compile and run the application as described in the previous procedure. + +## Example + +The following code example is the complete example from the previous procedures: + + [!code-csharp[System.Windows.Forms.FormWithButton#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.FormWithButton#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb#1)] + +## See also + +- +- +- [Changing the Appearance of Windows Forms](changing-the-appearance-of-windows-forms.md) +- [Enhancing Windows Forms Applications](./advanced/index.md) +- [Getting Started with Windows Forms](getting-started-with-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-create-event-handlers-at-run-time-for-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-create-event-handlers-at-run-time-for-windows-forms.md new file mode 100644 index 0000000000..b46ef9e0ec --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-create-event-handlers-at-run-time-for-windows-forms.md @@ -0,0 +1,75 @@ +--- +title: "How to: Create Event Handlers at Run Time" +description: Learn how to create an event handler at run time with the Windows Forms Designer in Visual Studio. This action allows you to connect event handlers at run time. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms, event handling" + - "event handlers [Windows Forms], creating" + - "run time [Windows Forms], creating event handlers at" + - "examples [Windows Forms], event handling" + - "Button control [Windows Forms], event handlers" +ms.assetid: 2e7c9e1a-61fe-444d-8113-3c5bacf1c8cb +--- +# How to: Create Event Handlers at Run Time for Windows Forms + +In addition to creating events using the Windows Forms Designer in Visual Studio, you can also create an event handler at run time. This action allows you to connect event handlers based on conditions in code at run time as opposed to having them connected when the program initially starts. + +## Create an event handler at run time + +1. Open the form that you want to add an event handler to. + +2. Add a method to your form with the method signature for the event that you want to handle. + + For example, if you were handling the event of a control, you would create a method such as the following: + + ```vb + Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) + ' Add event handler code here. + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + // Add event handler code here. + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + // Add event handler code here. + } + ``` + +3. Add code to the event handler as appropriate to your application. + +4. Determine which form or control you want to create an event handler for. + +5. In a method within your form's class, add code that specifies the event handler to handle the event. For example, the following code specifies the event handler `button1_Click` handles the event of a control: + + ```vb + AddHandler Button1.Click, AddressOf Button1_Click + ``` + + ```csharp + button1.Click += new EventHandler(button1_Click); + ``` + + ```cpp + button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click); + ``` + + The method demonstrated in the Visual Basic code above establishes a click event handler for the button. + +## See also + +- [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) +- [Event Handlers Overview](event-handlers-overview-windows-forms.md) +- [Troubleshooting Inherited Event Handlers in Visual Basic](https://docs.microsoft.com/dotnet/visual-basic/programming-guide/language-features/events/troubleshooting-inherited-event-handlers) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-determine-which-modifier-key-was-pressed.md b/dotnet-desktop-guide/framework/winforms/how-to-determine-which-modifier-key-was-pressed.md new file mode 100644 index 0000000000..20de638fb1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-determine-which-modifier-key-was-pressed.md @@ -0,0 +1,47 @@ +--- +title: "How to: Determine Which Modifier Key Was Pressed" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +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" +ms.assetid: 1e184048-0ae3-4067-a200-d4ba31dbc2cb +--- +# How to: Determine Which Modifier Key Was Pressed +When you create an application that accepts the user's keystrokes, you may also want to monitor for modifier keys such as the SHIFT, ALT, and CTRL keys. When a modifier key is pressed in combination with other keys, or with mouse clicks, your application can respond appropriately. For example, if the letter S is pressed, this may simply cause an "s" to appear on the screen, but if the keys CTRL+S are pressed, the current document may be saved. If you handle the event, the property of the received by the event handler specifies which modifier keys are pressed. Alternatively, the property of specifies the character that was pressed as well as any modifier keys combined with a bitwise OR. However, if you are handling the event or a mouse event, the event handler does not receive this information. In this case, you must use the property of the class. In either case, you must perform a bitwise AND of the appropriate value and the value you are testing. The enumeration offers variations of each modifier key, so it is important that you perform the bitwise AND with the correct value. For example, the SHIFT key is represented by , , and 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. + +> [!NOTE] +> Visual Basic programmers can also access key information through the property + +### To determine which modifier key was pressed + +- Use the bitwise `AND` operator with the property and a value of the enumeration to determine whether a particular modifier key is pressed. The following code example shows how to determine whether the SHIFT key is pressed within a event handler. + + [!code-cpp[System.Windows.Forms.DetermineModifierKey#5](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/form1.cpp#5)] + [!code-csharp[System.Windows.Forms.DetermineModifierKey#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/CS/form1.cs#5)] + [!code-vb[System.Windows.Forms.DetermineModifierKey#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/VB/form1.vb#5)] + +## See also + +- +- +- [Keyboard Input in a Windows Forms Application](keyboard-input-in-a-windows-forms-application.md) +- [How to: Determine If CapsLock is On in Visual Basic](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/9c9d1fz9(v=vs.100)) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-display-dialog-boxes-for-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-display-dialog-boxes-for-windows-forms.md new file mode 100644 index 0000000000..3def002ba0 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-display-dialog-boxes-for-windows-forms.md @@ -0,0 +1,47 @@ +--- +title: "How to: Display Dialog Boxes" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms, displaying" + - "Windows Forms dialog boxes [Windows Forms], displaying" + - "Windows Forms, calling one form from another" + - "dialog boxes [Windows Forms], displaying for Windows Forms" +ms.assetid: aaac1b38-c651-495a-8d3d-5a9bfb32fee3 +--- +# How to: Display Dialog Boxes for Windows Forms +You display a dialog box in the same way you display any other form in an application. The startup form loads automatically when the application is run. To make a second form or dialog box appear in the application, write code to load and display it. Similarly, to make the form or dialog box disappear, write code to unload or hide it. + +### To display a dialog box + +1. Navigate to the event handler with which you want to open the dialog box. This can happen when a menu command is selected, when a button is clicked, or when any other event occurs. + +2. In the event handler, add code to open the dialog box. In this example, a button-click event is used to show the dialog box: + + ```vb + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + Dim dlg1 as new Form() + dlg1.ShowDialog() + End Sub + ``` + + ```csharp + private void button1_Click(object sender, System.EventArgs e) + { + Form dlg1 = new Form(); + dlg1.ShowDialog(); + } + ``` + + ```cpp + private: + void button1_Click(System::Object ^ sender, + System::EventArgs ^ e) + { + Form ^ dlg1 = gcnew Form(); + dlg1->ShowDialog(); + } + ``` diff --git a/dotnet-desktop-guide/framework/winforms/how-to-distinguish-between-clicks-and-double-clicks.md b/dotnet-desktop-guide/framework/winforms/how-to-distinguish-between-clicks-and-double-clicks.md new file mode 100644 index 0000000000..f0d04cd430 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-distinguish-between-clicks-and-double-clicks.md @@ -0,0 +1,39 @@ +--- +title: "How to: Distinguish Between Clicks and Double-Clicks" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "mouse [Windows Forms], click" + - "mouse [Windows Forms], double-click" + - "mouse clicks [Windows Forms], single versus double" +ms.assetid: d836ac8c-85bc-4f3a-a761-8aee03dc682c +--- +# How to: Distinguish Between Clicks and Double-Clicks +Typically, a single *click* initiates a user interface (UI) 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. 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. + + [!code-csharp[System.Windows.Forms.ButtonDoubleClick#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.ButtonDoubleClick#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/VB/Form1.vb#1)] + +### To distinguish between clicks in the MouseDown event + +- Handle the event and determine the location and time span between clicks using the appropriate properties 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-cpp[System.Windows.Forms.SingleVersusDoubleClick#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/form1.cpp#0)] + [!code-csharp[System.Windows.Forms.SingleVersusDoubleClick#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/CS/form1.cs#0)] + [!code-vb[System.Windows.Forms.SingleVersusDoubleClick#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/VB/form1.vb#0)] + +## Compiling the Code + These examples require: + +- References to the System, System.Drawing, and System.Windows.Forms assemblies. + +## See also + +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-handle-keyboard-input-at-the-form-level.md b/dotnet-desktop-guide/framework/winforms/how-to-handle-keyboard-input-at-the-form-level.md new file mode 100644 index 0000000000..bebebba1a2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-handle-keyboard-input-at-the-form-level.md @@ -0,0 +1,40 @@ +--- +title: "How to: 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: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "keyboard input [Windows Forms], at form level" + - "Windows Forms, handling keyboard input" + - "keyboards [Windows Forms], form-level input" +ms.assetid: d7f8b390-dc91-42d2-ae0f-2ffa388127ad +--- +# How to: Handle Keyboard Input at the Form Level +Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control. This topic shows how to accomplish this task. + +### To handle a keyboard message at the form level + +- Handle the or event of the startup form, and set the property of the form to `true` so that keyboard messages are 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-cpp[System.Windows.Forms.KeyboardInputForm#10](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/form1.cpp#10)] + [!code-csharp[System.Windows.Forms.KeyboardInputForm#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/CS/form1.cs#10)] + [!code-vb[System.Windows.Forms.KeyboardInputForm#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/VB/form1.vb#10)] + +## Example + The following code example is the entire application for the above example. The application includes a along with several other controls that allow you to move focus from the . The event of the main consumes '1', '4', and '7', and the event of the consumes '2', '5', and '8' while displaying the remaining keys. Compare the output when you press a number key while the has focus with the output when you press a number key while focus is on one of the other controls. + + [!code-cpp[System.Windows.Forms.KeyBoardInputForm#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/form1.cpp#0)] + [!code-csharp[System.Windows.Forms.KeyBoardInputForm#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/CS/form1.cs#0)] + [!code-vb[System.Windows.Forms.KeyBoardInputForm#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/VB/form1.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [Keyboard Input in a Windows Forms Application](keyboard-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-handle-user-input-events-in-windows-forms-controls.md b/dotnet-desktop-guide/framework/winforms/how-to-handle-user-input-events-in-windows-forms-controls.md new file mode 100644 index 0000000000..8c1b03f3f5 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-handle-user-input-events-in-windows-forms-controls.md @@ -0,0 +1,28 @@ +--- +title: Handle User Input Events in Controls +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "Windows Forms controls, user input" + - "user input [Windows Forms], Windows Forms controls" +ms.assetid: 3de74dcf-fae3-42d0-92b5-bc04a61a6888 +--- +# How to: Handle User Input Events in Windows Forms Controls +This example demonstrates how to handle most keyboard, mouse, focus, and validation events that can occur in a Windows Forms control. The text box named `TextBoxInput` receives the events when it has focus, and information about each event is written in the text box named `TextBoxOutput` in the order in which the events are raised. The application also includes a set of check boxes that can be used to filter which events to report. + +## Example + [!code-cpp[System.Windows.Forms.UserInputWalkthrough#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/form1.cpp#0)] + [!code-csharp[System.Windows.Forms.UserInputWalkthrough#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/CS/form1.cs#0)] + [!code-vb[System.Windows.Forms.UserInputWalkthrough#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/VB/form1.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [User Input in Windows Forms](user-input-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-implement-the-ilistsource-interface.md b/dotnet-desktop-guide/framework/winforms/how-to-implement-the-ilistsource-interface.md new file mode 100644 index 0000000000..71d5670442 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-implement-the-ilistsource-interface.md @@ -0,0 +1,41 @@ +--- +title: "How to: Implement the IListSource Interface" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "data binding [Windows Forms], implementing" + - "IListSource interface" +ms.assetid: 63ce27aa-2e23-4fbd-8228-0c1726f6c421 +--- +# How to: Implement the IListSource Interface +Implement the interface to create a bindable class that does not implement but instead provides a list from another location. + +## Example + The following code example demonstrates how to implement the interface. A component named `EmployeeListSource` exposes an for data binding by implementing the method. + + [!code-csharp[System.ComponentModel.IListSource#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/EmployeeListSource.cs#1)] + [!code-vb[System.ComponentModel.IListSource#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/EmployeeListSource.vb#1)] + + [!code-csharp[System.ComponentModel.IListSource#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Employee.cs#10)] + [!code-vb[System.ComponentModel.IListSource#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Employee.vb#10)] + + [!code-csharp[System.ComponentModel.IListSource#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/BusinessObjectBase.cs#100)] + [!code-vb[System.ComponentModel.IListSource#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/BusinessObjectBase.vb#100)] + + [!code-csharp[System.ComponentModel.IListSource#1000](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Form1.cs#1000)] + [!code-vb[System.ComponentModel.IListSource#1000](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Form1.vb#1000)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-implement-the-inotifypropertychanged-interface.md b/dotnet-desktop-guide/framework/winforms/how-to-implement-the-inotifypropertychanged-interface.md new file mode 100644 index 0000000000..5b70a1fdba --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-implement-the-inotifypropertychanged-interface.md @@ -0,0 +1,24 @@ +--- +title: "How to: Implement the INotifyPropertyChanged Interface" +description: Learn how to implement the INotifyPropertyChanged interface on business objects that are used in Windows Forms data binding. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "INotifyPropertyChanged interface [Windows Forms], implementing" +ms.assetid: eac428af-b43b-46ac-80d9-1a5f88658725 +--- +# How to: Implement the INotifyPropertyChanged Interface +The following code example demonstrates how to implement the interface. Implement this interface on business objects that are used in Windows Forms data binding. When implemented, the interface communicates to a bound control the property changes on a business object. + +## Example + [!code-csharp[System.ComponentModel.IPropertyChangeExample#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/CS/Form1.cs#1)] + [!code-vb[System.ComponentModel.IPropertyChangeExample#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/VB/Form1.vb#1)] + +## See also + +- [How to: Apply the PropertyNameChanged Pattern](how-to-apply-the-propertynamechanged-pattern.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) +- [How to: Raise Change Notifications Using a BindingSource and the INotifyPropertyChanged Interface](./controls/raise-change-notifications--bindingsource.md) +- [Change Notification in Windows Forms Data Binding](change-notification-in-windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-implement-the-itypedlist-interface.md b/dotnet-desktop-guide/framework/winforms/how-to-implement-the-itypedlist-interface.md new file mode 100644 index 0000000000..7d82cda932 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-implement-the-itypedlist-interface.md @@ -0,0 +1,39 @@ +--- +title: "How to: Implement the ITypedList Interface" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "ITypedList interface" + - "BindingList(Of T) class" + - "data binding [Windows Forms], implementing" + - "IBindingList interface" +ms.assetid: 834cc15c-50bc-4a8b-a610-313d6a217357 +--- +# How to: Implement the ITypedList Interface +Implement the interface to enable discovery of the schema for a bindable list. + +## Example + The following code example demonstrates how to implement the interface. A generic type named `SortableBindingList` derives from the class and implements the interface. A simple class named `Customer` provides data, which is bound to the header of a control. + + [!code-csharp[System.ComponentModel.ITypedList#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/SortableBindingList.cs#1)] + [!code-vb[System.ComponentModel.ITypedList#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/SortableBindingList.vb#1)] + + [!code-csharp[System.ComponentModel.ITypedList#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Customer.cs#10)] + [!code-vb[System.ComponentModel.ITypedList#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Customer.vb#10)] + + [!code-csharp[System.ComponentModel.ITypedList#100](~/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Form1.cs#100)] + [!code-vb[System.ComponentModel.ITypedList#100](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Form1.vb#100)] + +## Compiling the Code + This example requires: + +- References to the System.Drawing and System.Windows.Forms assemblies. + +## See also + +- +- +- +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-modify-keyboard-input-to-a-standard-control.md b/dotnet-desktop-guide/framework/winforms/how-to-modify-keyboard-input-to-a-standard-control.md new file mode 100644 index 0000000000..bb415d06d2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-modify-keyboard-input-to-a-standard-control.md @@ -0,0 +1,66 @@ +--- +title: "How to: Modify Keyboard Input to a Standard Control" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "keyboard input [Windows Forms], modifying" + - "modifying keyboard input" + - "Windows Forms, modifying keyboard input" + - "keyboards [Windows Forms], keyboard input" +ms.assetid: 626d3712-d866-4988-bcda-a2d5b36ec0ba +--- +# How to: Modify Keyboard Input to a Standard Control +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 do not receive the key value. 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 topic shows how to accomplish these tasks. + +### To 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 is an excerpt from a `switch` statement that examines the property of the received by a event handler. This code consumes the 'A' and 'a' character keys. + + [!code-csharp[System.Windows.Forms.KeyBoardInput#6](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs#6)] + [!code-vb[System.Windows.Forms.KeyBoardInput#6](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb#6)] + +### To 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 is an excerpt from a `switch` statement that modifies 'B' to 'A' and 'b' to 'a'. Note that the property of the parameter is set to `false`, so that the new key value is propagated to other methods and events in the message queue. + + [!code-csharp[System.Windows.Forms.KeyBoardInput#7](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs#7)] + [!code-vb[System.Windows.Forms.KeyBoardInput#7](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb#7)] + +### To modify a noncharacter key + +- Override a method that processes Windows messages, detect the WM_KEYDOWN or WM_SYSKEYDOWN message, and set the property of the parameter to the value that represents the new noncharacter key. + + The following code example demonstrates how to override the method of a control to detect keys F1 through F9 and modify any F3 key press to F1. For more information on methods that you can override to intercept keyboard messages, see [User Input in a Windows Forms Application](user-input-in-a-windows-forms-application.md) and [How Keyboard Input Works](how-keyboard-input-works.md). + + [!code-csharp[System.Windows.Forms.KeyBoardInput#12](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs#12)] + [!code-vb[System.Windows.Forms.KeyBoardInput#12](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb#12)] + +## Example + The following code example is the complete application for the code examples in the previous sections. The application uses a custom control derived from the class to consume and modify keyboard input. + + [!code-csharp[System.Windows.Forms.KeyBoardInput#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs#0)] + [!code-vb[System.Windows.Forms.KeyBoardInput#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb#0)] + +## Compiling the Code + This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [Keyboard Input in a Windows Forms Application](keyboard-input-in-a-windows-forms-application.md) +- [User Input in a Windows Forms Application](user-input-in-a-windows-forms-application.md) +- [How Keyboard Input Works](how-keyboard-input-works.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-navigate-data-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-navigate-data-in-windows-forms.md new file mode 100644 index 0000000000..b64852747e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-navigate-data-in-windows-forms.md @@ -0,0 +1,52 @@ +--- +title: "How to: Navigate Data" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "cursors [Windows Forms], data sources" + - "data sources [Windows Forms], Windows Forms" + - "Windows Forms, navigating" + - "CurrencyManager class [Windows Forms], navigating Windows Forms data" + - "data [Windows Forms], navigating" +ms.assetid: 97360f7b-b181-4084-966a-4c62518f735b +--- +# How to: Navigate Data in Windows Forms +In a Windows application, the easiest way to navigate through records in a data source is to bind a component to the data source and then bind controls to the . You can then use the built-in navigation method on the such a , , and . Using these methods will adjust the and properties of the appropriately. You can also find an item and set it as the current item by setting the property. + +### To increment the position in a data source + +1. Set the property of the for your bound data to the record position to go to. The following example illustrates using the method of the to increment the property when the `nextButton` is clicked. The is associated with the `Customers` table of a dataset `Northwind`. + + > [!NOTE] + > Setting the property to a value beyond the first or last record does not result in an error, as the .NET Framework will not allow you to set the position to a value outside the bounds of the list. If it is important in your application to know whether you have gone past the first or last record, include logic to test whether you will exceed the data element count. + + [!code-csharp[System.Windows.Forms.NavigatingData#4](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/CS/Form1.cs#4)] + [!code-vb[System.Windows.Forms.NavigatingData#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/VB/Form1.vb#4)] + +### To check whether you have passed the end or beginning + +1. Create an event handler for the event. In the handler, you can test whether the proposed position value has exceeded the actual data element count. + + The following example illustrates how you can test whether you have reached the last data element. In the example, if you are at the last element, the **Next** button on the form is disabled. + + > [!NOTE] + > Be aware that, should you change the list you are navigating in code, you should re-enable the **Next** button, so that users may browse the entire length of the new list. Additionally, be aware that the above event for the specific you are working with needs to be associated with its event-handling method. The following is an example of a method for handling the event: + + [!code-csharp[System.Windows.Forms.NavigatingData#3](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/CS/Form1.cs#3)] + [!code-vb[System.Windows.Forms.NavigatingData#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/VB/Form1.vb#3)] + +### To find an item and set it as the current item + +1. Find the record you wish to set as the current item. You can do this using the method of the , if your data source implements . Some examples of data sources that implement are and . + + [!code-csharp[System.Windows.Forms.NavigatingData#2](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/CS/Form1.cs#2)] + [!code-vb[System.Windows.Forms.NavigatingData#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/VB/Form1.vb#2)] + +## See also + +- [Data Sources Supported by Windows Forms](data-sources-supported-by-windows-forms.md) +- [Change Notification in Windows Forms Data Binding](change-notification-in-windows-forms-data-binding.md) +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-resize-windows-forms.md b/dotnet-desktop-guide/framework/winforms/how-to-resize-windows-forms.md new file mode 100644 index 0000000000..68dedd3370 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-resize-windows-forms.md @@ -0,0 +1,114 @@ +--- +title: Resize form +description: Learn how to resize both the height and width of the form by setting a new value for the Size property, or adjust the Height or Width properties individually. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "resizing Windows Forms" + - "Windows Forms, resizing" +ms.assetid: 5d9dd47e-e68c-48c9-a0a3-a9ff34ba009d +--- +# How to: Resize Windows Forms + +You can specify the size of your Windows Form in several ways. You can change both the height and the width of the form programmatically by setting a new value for the property, or adjust the or properties individually. If you're using Visual Studio, you can change the size using the Windows Forms Designer. Also see [How to: Resize Windows Forms Using the Designer](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2010/37k2zkwx(v=vs.100)). + +## Resize a form programmatically + +Define the size of a form at run time by setting the property of the form. + +The following code example shows the form size set to 100 × 100 pixels. + +```vb +Form1.Size = New System.Drawing.Size(100, 100) +``` + +```csharp +Form1.Size = new System.Drawing.Size(100, 100); +``` + +```cpp +Form1->Size = System::Drawing::Size(100, 100); +``` + +## Change form width and height programmatically + +After the is defined, change either the form height or width by using the or properties. + +The following code example shows the width of the form set to 300 pixels from the left edge of the form, whereas the height stays constant. + +```vb +Form1.Width = 300 +``` + +```csharp +Form1.Width = 300; +``` + +```cpp +Form1->Width = 300; +``` + +-or- + +Change or by setting the property. + +However, as the following code example shows, this approach is more cumbersome than just setting or properties. + +```vb +Form1.Size = New Size(300, Form1.Size.Height) +``` + +```csharp +Form1.Size = new Size(300, Form1.Size.Height); +``` + +```cpp +Form1->Size = System::Drawing::Size(300, Form1->Size.Height); +``` + +## Change form size by increments programmatically + +To increment the size of the form, set the and properties. + +The following code example shows the width of the form set to 200 pixels wider than the current setting. + +```vb +Form1.Width += 200 +``` + +```csharp +Form1.Width += 200; +``` + +```cpp +Form1->Width += 200; +``` + +> [!CAUTION] +> Always use the or property to change a dimension of a form, unless you are setting both height and width dimensions at the same time by setting the property to a new structure. The property returns a structure, which is a value type. You cannot assign a new value to the property of a value type. Therefore, the following code example will not compile. + +```vb +' NOTE: CODE WILL NOT COMPILE +Dim f As New Form() +f.Size.Width += 100 +``` + +```csharp +// NOTE: CODE WILL NOT COMPILE +Form f = new Form(); +f.Size.Width += 100; +``` + +```cpp +// NOTE: CODE WILL NOT COMPILE +Form^ f = gcnew Form(); +f->Size->X += 100; +``` + +## See also + +- [Getting Started with Windows Forms](getting-started-with-windows-forms.md) +- [Enhancing Windows Forms Applications](./advanced/index.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-respond-to-font-scheme-changes-in-a-windows-forms-application.md b/dotnet-desktop-guide/framework/winforms/how-to-respond-to-font-scheme-changes-in-a-windows-forms-application.md new file mode 100644 index 0000000000..63943a537a --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-respond-to-font-scheme-changes-in-a-windows-forms-application.md @@ -0,0 +1,65 @@ +--- +title: Respond to Font Scheme Changes in a Windows Forms app +titleSuffix: "" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "Windows Forms, font scheme changes" +ms.assetid: 4db27702-22e7-43bf-a07d-9a004549853c +--- +# How to: Respond to Font Scheme Changes in a Windows Forms Application +In the Windows operating systems, a user can change the system-wide font settings to make the default font appear larger or smaller. Changing these font settings is critical for users who are visually impaired and require larger type to read the text on their screens. You can adjust your Windows Forms application to react to these changes by increasing or decreasing the size of the form and all contained text whenever the font scheme changes. If you want your form to accommodate changes in font sizes dynamically, you can add code to your form. + + Typically, the default font used by Windows Forms is the font returned by the namespace call to `GetStockObject(DEFAULT_GUI_FONT)`. The font returned by this call only changes when the screen resolution changes. As shown in the following procedure, your code must change the default font to to respond to changes in font size. + +### To use the desktop font and respond to font scheme changes + +1. Create your form, and add the controls you want to it. For more information, see [How to: Create a Windows Forms Application from the Command Line](how-to-create-a-windows-forms-application-from-the-command-line.md) and [Controls to Use on Windows Forms](./controls/controls-to-use-on-windows-forms.md). + +2. Add a reference to the namespace to your code. + + [!code-csharp[WinFormsAutoScaling#2](~/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs#2)] + [!code-vb[WinFormsAutoScaling#2](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb#2)] + +3. Add the following code to the constructor of your form to hook up required event handlers, and to change the default font in use for the form. + + [!code-csharp[WinFormsAutoScaling#3](~/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs#3)] + [!code-vb[WinFormsAutoScaling#3](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb#3)] + +4. Implement a handler for the event that causes the form to scale automatically when the category changes. + + [!code-csharp[WinFormsAutoScaling#4](~/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs#4)] + [!code-vb[WinFormsAutoScaling#4](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb#4)] + +5. Finally, implement a handler for the event that detaches the event handler. + + > [!IMPORTANT] + > Failure to include this code will cause your application to leak memory. + + [!code-csharp[WinFormsAutoScaling#5](~/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs#5)] + [!code-vb[WinFormsAutoScaling#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb#5)] + +6. Compile and run the code. + +### To manually change the font scheme in Windows XP + +1. While your Windows Forms application is running, right-click the Windows desktop and choose **Properties** from the shortcut menu. + +2. In the **Display Properties** dialog box, click the **Appearance** tab. + +3. From the **Font Size** drop-down list box, select a new font size. + + You'll notice that the form now reacts to run-time changes in the desktop font scheme. When the user changes between **Normal**, **Large Fonts**, and **Extra Large Fonts**, the form changes font and scales correctly. + +## Example + [!code-csharp[WinFormsAutoScaling#1](~/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs#1)] + [!code-vb[WinFormsAutoScaling#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb#1)] + + The constructor in this code example contains a call to `InitializeComponent`, which is defined when you create a new Windows Forms project in Visual Studio. Remove this line of code if you are building your application on the command line. + +## See also + +- +- [Automatic Scaling in Windows Forms](automatic-scaling-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/how-to-simulate-mouse-and-keyboard-events-in-code.md b/dotnet-desktop-guide/framework/winforms/how-to-simulate-mouse-and-keyboard-events-in-code.md new file mode 100644 index 0000000000..ebbddb6bcb --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/how-to-simulate-mouse-and-keyboard-events-in-code.md @@ -0,0 +1,92 @@ +--- +title: "How to: Simulate Mouse and Keyboard Events in Code" +description: Learn how to use the options Windows Forms provides to programmatically simulate mouse and keyboard inputs. +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" + - "cpp" +helpviewer_keywords: + - "keyboards [Windows Forms], event simulation" + - "user input [Windows Forms], simulating" + - "SendKeys [Windows Forms], using" + - "mouse clicks [Windows Forms], simulating" + - "mouse [Windows Forms], event simulation" +ms.assetid: 6abcb67e-3766-4af2-9590-bf5dabd17e41 +--- +# How to: Simulate Mouse and Keyboard Events in Code + +Windows Forms provides several options for programmatically simulating mouse and keyboard input. This topic provides an overview of these options. + +## Simulating Mouse Input + +The best way to simulate mouse events is to call the `On`*EventName* method that raises the mouse event you want to simulate. This option is usually possible only within custom controls and forms, because the methods that raise events are protected and cannot be accessed outside the control or form. For example, the following steps illustrate how to simulate clicking the right mouse button in code. + +#### To programmatically click the right mouse button + +1. Create a whose property is set to the value. + +2. Call the method with this as the argument. + +For more information on custom controls, see [Developing Windows Forms Controls at Design Time](./controls/developing-windows-forms-controls-at-design-time.md). + +There are other ways to simulate mouse input. For example, you can programmatically set a control property that represents a state that is typically set through mouse input (such as the property of the control), or you can directly call the delegate that is attached to the event you want to simulate. + +## Simulating Keyboard Input + +Although you can simulate keyboard input by using the strategies discussed above for mouse input, Windows Forms also provides the class for sending keystrokes to the active 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. + +> [!NOTE] +> The class has been updated for the .NET Framework 3.0 to enable its use in applications that run on Windows Vista. The enhanced security of Windows Vista (known as User Account Control or UAC) prevents the previous implementation from working as expected. +> +> The class is susceptible to timing issues, which some developers have had to work around. The updated implementation is still susceptible to timing issues, but is slightly faster and may require changes to the workarounds. The class tries to use the previous implementation first, and if that fails, uses the new implementation. As a result, the class may behave differently on different operating systems. Additionally, when the class uses the new implementation, the method will not wait for messages to be processed when they are sent to another process. +> +> 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 use the previous implementation, use the value `"JournalHook"` instead. + +#### To send a keystroke to the same application + +1. 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 to simulate pressing the ENTER key when the user double-clicks the surface of the form. This example assumes a with a single control that has a tab index of 0. + + [!code-cpp[System.Windows.Forms.SimulateKeyPress#10](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/form1.cpp#10)] + [!code-csharp[System.Windows.Forms.SimulateKeyPress#10](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/CS/form1.cs#10)] + [!code-vb[System.Windows.Forms.SimulateKeyPress#10](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/VB/form1.vb#10)] + +#### To send a keystroke to a different application + +1. Activate the application window that will receive the keystrokes, and then call the or method. Because there is no managed method to activate another application, you must use native Windows methods to force focus on other applications. The following code example uses platform invoke to call the `FindWindow` and `SetForegroundWindow` methods to activate the Calculator application window, and then calls to issue a series of calculations to the Calculator application. + + > [!NOTE] + > The correct parameters of the `FindWindow` call that locates the Calculator application vary based on your version of Windows. The following code finds the Calculator application on Windows 7. On Windows Vista, change the first parameter to "SciCalc". You can use the Spy++ tool, included with Visual Studio, to determine the correct parameters. + + [!code-cpp[System.Windows.Forms.SimulateKeyPress#5](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/form1.cpp#5)] + [!code-csharp[System.Windows.Forms.SimulateKeyPress#5](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/CS/form1.cs#5)] + [!code-vb[System.Windows.Forms.SimulateKeyPress#5](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/VB/form1.vb#5)] + +## Example + +The following code example is the complete application for the previous code examples. + +[!code-cpp[System.Windows.Forms.SimulateKeyPress#0](~/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/form1.cpp#0)] +[!code-csharp[System.Windows.Forms.SimulateKeyPress#0](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/CS/form1.cs#0)] +[!code-vb[System.Windows.Forms.SimulateKeyPress#0](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/VB/form1.vb#0)] + +## Compiling the Code + +This example requires: + +- References to the System, System.Drawing and System.Windows.Forms assemblies. + +## See also + +- [User Input in Windows Forms](user-input-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/index.yml b/dotnet-desktop-guide/framework/winforms/index.yml new file mode 100644 index 0000000000..06c168406d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/index.yml @@ -0,0 +1,62 @@ +### YamlMime:Landing + +title: .NET Desktop Guide for Windows Forms +summary: Learn about using Windows Forms on Windows with either .NET Framework, .NET 5 and above, or .NET Core 3.1. + +metadata: + title: Windows Forms for .NET documentation + description: Learn about using Windows Forms (WinForms), a graphical user interface for Windows and .NET. + ms.topic: landing-page + ms.date: 08/30/2020 + +# linkListType: architecture | concept | deploy | download | get-started | how-to-guide | learn | overview | quickstart +# reference | sample | tutorial | video | whats-new + +landingContent: + + # Card + - title: WinForms for .NET Framework + linkLists: + - linkListType: overview + links: + - text: Windows Forms overview + url: windows-forms-overview.md + - linkListType: get-started + links: + - text: Get started with Windows Forms Designer + url: /visualstudio/designers/walkthrough-windows-forms-designer + - text: Create a WinForms app from the command-line + url: how-to-create-a-windows-forms-application-from-the-command-line.md + + - title: Controls + linkLists: + - linkListType: overview + links: + - text: Developing your own controls + url: controls/developing-windows-forms-controls-at-design-time.md + - text: Developing controls + url: controls/developing-windows-forms-controls-at-design-time.md + - linkListType: how-to-guide + links: + - text: Add Controls to Windows Forms + url: controls/how-to-add-controls-to-windows-forms.md + - text: Position controls on Windows Forms + url: controls/how-to-position-controls-on-windows-forms.md + - linkListType: reference + links: + - text: Windows Forms Controls by Function + url: controls/windows-forms-controls-by-function.md + + - title: Events + linkLists: + - linkListType: overview + links: + - text: Events in Windows Forms + url: events-overview-windows-forms.md + - text: Event handlers in Windows Forms + url: event-handlers-overview-windows-forms.md + - linkListType: concept + links: + - text: Order in which events are raised + url: order-of-events-in-windows-forms.md + \ No newline at end of file diff --git a/dotnet-desktop-guide/framework/winforms/interfaces-related-to-data-binding.md b/dotnet-desktop-guide/framework/winforms/interfaces-related-to-data-binding.md new file mode 100644 index 0000000000..fe13323713 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/interfaces-related-to-data-binding.md @@ -0,0 +1,154 @@ +--- +title: "Interfaces Related to Data Binding" +ms.date: "03/30/2017" +helpviewer_keywords: + - "data [Windows Forms], data-binding interfaces" + - "INotifyPropertyChanged interface" + - "IBindingListView interface" + - "IList interface [Windows Forms], Windows Forms data binding" + - "IBindingList interface [Windows Forms], Windows Forms data binding" + - "interfaces [Windows Forms], Windows Forms data binding" + - "IEditableObject interface [Windows Forms], Windows Forms data binding" + - "data binding [Windows Forms], interfaces" + - "IDataErrorInfo interface [Windows Forms], Windows Forms data binding" +ms.assetid: 14e49a2e-3e46-47ca-b491-70d546333277 +--- +# Interfaces Related to Data Binding + +With ADO.NET, you can create many different data structures to suit the binding needs of your application and the data you are working with. You may want to create your own classes that provide or consume data in Windows Forms. These objects can offer varying levels of functionality and complexity, from basic data binding, to providing design-time support, error checking, change notification, or even support for a structured rollback of the changes made to the data itself. + +## Consumers of Data-Binding Interfaces + +The following sections describe two groups of interface objects. The first group lists interfaces that are implemented on data sources by data source authors. These interfaces are designed to be consumed by data source consumers, which are in most cases Windows Forms controls or components. The second group lists interfaces designed for use by component authors. Component authors use these interfaces when they are creating a component that supports data binding to be consumed by the Windows Forms data-binding engine. You can implement these interfaces within classes associated with your form to enable data binding; each case presents a class that implements an interface that enables interaction with data. Visual Studio rapid application development (RAD) data design experience tools already take advantage of this functionality. + +### Interfaces for Implementation by Data Source Authors + +The following interfaces are designed to be consumed by Windows Forms controls: + +- interface + + A class that implements the interface could be an , , or . These are indexed lists of items of type . These lists must contain homogenous types, because the first item of the index determines the type. would be available for binding only at run time. + + > [!NOTE] + > If you want to create a list of business objects for binding with Windows Forms, you should consider using the . The is an extensible class that implements the primary interfaces required for two-way Windows Forms data binding. + +- interface + + A class that implements the interface provides a much higher level of data-binding functionality. This implementation offers you basic sorting capabilities and change notification, both for when the list items change (for example, the third item in a list of customers has a change to the Address field), as well as when the list itself changes (for example, the number of items in the list increases or decreases). Change notification is important if you plan to have multiple controls bound to the same data, and you want data changes made in one of the controls to propagate to the other bound controls. + + > [!NOTE] + > Change notification is enabled for the interface through the property which, when `true`, raises a event, indicating the list changed or an item in the list changed. + + The type of change is described by the property of the parameter. Hence, whenever the data model is updated, any dependent views, such as other controls bound to the same data source, will also be updated. However, objects contained within the list will have to notify the list when they change so that the list can raise the event. + + > [!NOTE] + > The provides a generic implementation of the interface. + +- interface + + A class that implements the interface provides all the functionality of an implementation of , as well as filtering and advanced sorting functionality. This implementation offers string-based filtering, and multicolumn sorting with property descriptor-direction pairs. + +- interface + + A class that implements the interface allows an object to control when changes to that object are made permanent. This implementation affords you the , , and methods, which enable you to roll back changes made to the object. Following is a brief explanation of the functioning of the , , and methods and how they work in conjunction with one another to enable a possible rollback of changes made to the data: + + - The method signals the start of an edit on an object. An object that implements this interface will need to store any updates after the method call in such a way that the updates can be discarded if the method is called. In data binding Windows Forms, you can call multiple times within the scope of a single edit transaction (for example, , , ). Implementations of should keep track of whether has already been called and ignore subsequent calls to . Because this method can be called multiple times, it is important that subsequent calls to it are nondestructive; that is, subsequent calls cannot destroy the updates that have been made or change the data that was saved on the first call. + + - The method pushes any changes since was called into the underlying object, if the object is currently in edit mode. + + - The method discards any changes made to the object. + + For more information about how the , , and methods work, see [Save data back to the database](/visualstudio/data-tools/save-data-back-to-the-database). + + This transactional notion of data functionality is used by the control. + +- interface + + A class that implements the interface usually implements the interface and allows you to roll back an addition made to the data source with the method. If your data source implements the interface, you should also have it implement the interface. + +- interface + + A class that implements the interface allows objects to offer custom error information to bound controls: + + - The property returns general error message text (for example, "An error has occurred"). + + - The property returns a string with the specific error message from the column (for example, "The value in the `State` column is invalid"). + +- interface + + A class that implements the interface is typically consumed by ASP.NET. Windows Forms support for this interface is only available through the component. + + > [!NOTE] + > The component copies all items into a separate list for binding purposes. + +- interface + + A collections class that implements the interface provides the ability to control the order and the set of properties exposed to the bound control. + + > [!NOTE] + > When you implement the method, and the array is not null, the last entry in the array will be the property descriptor that describes the list property that is another list of items. + +- interface + + A class that implements the interface provides dynamic information about itself. This interface is similar to but is used for objects rather than lists. This interface is used by to project the schema of the underlying rows. A simple implementation of is provided by the class. + + > [!NOTE] + > To support design-time binding to types that implement , the type must also implement and exist as an instance on the Form. + +- interface + + A class that implements the interface enables list-based binding on non-list objects. The method of is used to return a bindable list from an object that does not inherit from . is used by the class. + +- interface + + A class that implements the interface is a bindable list that also implements the interface. This interface is used to indicate if your type raises events of type through its property. + + > [!NOTE] + > You should implement the if your data source provides the property to list event conversion described previously and is interacting with the component. Otherwise, the will also perform property to list event conversion resulting in slower performance. + +- interface + + A component that implements the interface takes advantages of batch optimizations for setting properties and initializing co-dependent properties. The contains two methods: + + - signals that object initialization is starting. + + - signals that object initialization is finishing. + +- interface + + A component that implements the interface also implements the interface. This interface allows you to notify other components that initialization is complete. The interface contains two members: + + - returns a `boolean` value indicating whether the component is initialized. + + - occurs when is called. + +- interface + + A class that implements this interface is a type that raises an event when any of its property values change. This interface is designed to replace the pattern of having a change event for each property of a control. When used in a , a business object should implement the interface and the BindingList\`1 will convert events to events of type . + + > [!NOTE] + > For change notification to occur in a binding between a bound client and a data source your bound data-source type should either implement the interface (preferred) or you can provide *propertyName*`Changed` events for the bound type, but you shouldn't do both. + +### Interfaces for Implementation by Component Authors + +The following interfaces are designed for consumption by the Windows Forms data-binding engine: + +- interface + + A class that implements this interface is a non-control component that supports data binding. This class returns the data bindings and binding context of the component through the and properties of this interface. + + > [!NOTE] + > If your component inherits from , you do not need to implement the interface. + +- interface + + A class that implements the interface is a component that provides its own to manage the bindings associated with this particular component. Access to the custom is provided by the property. + + > [!NOTE] + > A class that inherits from manages bindings automatically through its property, so cases in which you need to implement the are fairly rare. + +## See also + +- [Data Binding and Windows Forms](data-binding-and-windows-forms.md) +- [How to: Create a Simple-Bound Control on a Windows Form](how-to-create-a-simple-bound-control-on-a-windows-form.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/keyboard-input-in-a-windows-forms-application.md b/dotnet-desktop-guide/framework/winforms/keyboard-input-in-a-windows-forms-application.md new file mode 100644 index 0000000000..1889635082 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/keyboard-input-in-a-windows-forms-application.md @@ -0,0 +1,27 @@ +--- +title: Keyboard input +ms.date: "03/30/2017" +helpviewer_keywords: + - "keyboard input [Windows Forms], using in Windows Forms" + - "keyboards [Windows Forms], keyboard input" + - "Windows Forms, keyboard input" +ms.assetid: 68f5bc70-14d5-45c9-b288-7d7b1493ee79 +--- +# Keyboard Input in a Windows Forms Application +Windows Forms includes standard keyboard events that allow you to respond to specific key presses, and also provides ways for you to intercept, modify, and consume key presses at the application, form, and control level. + +## In This Section + [How Keyboard Input Works](how-keyboard-input-works.md) + Describes how keyboard messages are processed and transformed into keyboard events. + + [Using Keyboard Events](using-keyboard-events.md) + Provides information on the types of keyboard events and the information that is received by the keyboard event handlers. + + [How to: Modify Keyboard Input to a Standard Control](how-to-modify-keyboard-input-to-a-standard-control.md) + Presents a code example that shows how to modify key values before they reach a control. + + [How to: Determine Which Modifier Key Was Pressed](how-to-determine-which-modifier-key-was-pressed.md) + Demonstrates how to find out whether SHIFT, ALT, or CTRL was pressed in addition to another key. + + [How to: Handle Keyboard Input at the Form Level](how-to-handle-keyboard-input-at-the-form-level.md) + Presents a code example that shows how to intercept keys before they reach a control. diff --git a/dotnet-desktop-guide/framework/winforms/media/how-to-create-a-bound-control-and-format-the-displayed-data/visual-studio-ellipsis-button.png b/dotnet-desktop-guide/framework/winforms/media/how-to-create-a-bound-control-and-format-the-displayed-data/visual-studio-ellipsis-button.png new file mode 100644 index 0000000000..d69ca5e3b0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/media/how-to-create-a-bound-control-and-format-the-displayed-data/visual-studio-ellipsis-button.png differ diff --git a/dotnet-desktop-guide/framework/winforms/media/how-to-create-a-simple-bound-control-on-a-windows-form/visual-studio-ellipsis-button.png b/dotnet-desktop-guide/framework/winforms/media/how-to-create-a-simple-bound-control-on-a-windows-form/visual-studio-ellipsis-button.png new file mode 100644 index 0000000000..d69ca5e3b0 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/media/how-to-create-a-simple-bound-control-on-a-windows-form/visual-studio-ellipsis-button.png differ diff --git a/dotnet-desktop-guide/framework/winforms/media/vxeventsbutton-propertieswindow.png b/dotnet-desktop-guide/framework/winforms/media/vxeventsbutton-propertieswindow.png new file mode 100644 index 0000000000..d8614bb1f5 Binary files /dev/null and b/dotnet-desktop-guide/framework/winforms/media/vxeventsbutton-propertieswindow.png differ diff --git a/dotnet-desktop-guide/framework/winforms/more-secure-file-and-data-access-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/more-secure-file-and-data-access-in-windows-forms.md new file mode 100644 index 0000000000..e8a4295936 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/more-secure-file-and-data-access-in-windows-forms.md @@ -0,0 +1,362 @@ +--- +title: "More Secure File and Data Access" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "security [Windows Forms], file access" + - "registry [Windows Forms]" + - "data access [Windows Forms]" + - "database access (Windows Forms security)" + - "data [Windows Forms], secure access" + - "file access [Windows Forms]" + - "security [Windows Forms], data access" +ms.assetid: 3cd3e55b-2f5e-40dd-835d-f50f7ce08967 +--- +# More Secure File and Data Access in Windows Forms +The .NET Framework uses permissions to help protect resources and data. Where your application can read or write data depends on the permissions granted to the application. When your application runs in a partial trust environment, you might not have access to your data or you might have to change the way you access the data. + + When you encounter a security restriction, you have two options: assert the permission (assuming it has been granted to your application), or use a version of the feature written to work in partial trust. The following sections discuss how to work with file, database, and registry access from applications that are running in a partial trust environment. + +> [!NOTE] +> By default, tools that generate ClickOnce deployments default these deployments to requesting Full Trust from the computers on which they run. If you decide you want the added security benefits of running in partial trust, you must change this default in either Visual Studio or one of the Windows SDK tools (Mage.exe or MageUI.exe). For more information about Windows Forms security, and on how to determine the appropriate trust level for your application, see [Security in Windows Forms Overview](security-in-windows-forms-overview.md). + +## File Access + The class controls file and folder access in the .NET Framework. By default, the security system does not grant the to partial trust environments such as the local intranet and Internet zones. However, an application that requires file access can still function in these environments if you modify the design of your application or use different methods to access files. By default, the local intranet zone is granted the right to have same site access and same directory access, to connect back to the site of its origin, and to read from its installation directory. By default, the Internet zone, is only granted the right to connect back to the site of its origin. + +### User-Specified Files + One way to deal with not having file access permission is to prompt the user to provide specific file information by using the or class. This user interaction helps provide some assurance that the application cannot maliciously load private files or overwrite important files. The and methods provide read and write file access by opening the file stream for the file that the user specified. The methods also help protect the user's file by obscuring the file's path. + +> [!NOTE] +> These permissions differ depending on whether your application is in the Internet zone or Intranet zone. Internet zone applications can only use the , whereas Intranet applications have unrestricted file dialog permission. + + The class specifies what type of file dialog box your application can use. The following table shows the value you must have to use each class. + +|Class|Required access value| +|-----------|---------------------------| +||| +||| + +> [!NOTE] +> The specific permission is not requested until the method is actually called. + + Permission to display a file dialog box does not grant your application full access to all members of the , , and classes. For the exact permissions that are required to call each method, see the reference topic for that method in the .NET Framework class library documentation. + + The following code example uses the method to open a user-specified file into a control. The example requires and the associated enumeration value. The example demonstrates how to handle the to determine whether the save feature should be disabled. This example requires that your has a control named `ButtonOpen`, and a control named `RtfBoxMain`. + +> [!NOTE] +> The programming logic for the save feature is not shown in the example. + +```vb +Private Sub ButtonOpen_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles ButtonOpen.Click + + Dim editingFileName as String = "" + Dim saveAllowed As Boolean = True + + ' Displays the OpenFileDialog. + If (OpenFileDialog1.ShowDialog() = DialogResult.OK) Then + Dim userStream as System.IO.Stream + Try + ' Opens the file stream for the file selected by the user. + userStream =OpenFileDialog1.OpenFile() + Me.RtfBoxMain.LoadFile(userStream, _ + RichTextBoxStreamType.PlainText) + Finally + userStream.Close() + End Try + + ' Tries to get the file name selected by the user. + ' Failure means that the application does not have + ' unrestricted permission to the file. + Try + editingFileName = OpenFileDialog1.FileName + Catch ex As Exception + If TypeOf ex Is System.Security.SecurityException Then + ' The application does not have unrestricted permission + ' to the file so the save feature will be disabled. + saveAllowed = False + Else + Throw ex + End If + End Try + End If +End Sub +``` + +```csharp +private void ButtonOpen_Click(object sender, System.EventArgs e) +{ + String editingFileName = ""; + Boolean saveAllowed = true; + + // Displays the OpenFileDialog. + if (openFileDialog1.ShowDialog() == DialogResult.OK) + { + // Opens the file stream for the file selected by the user. + using (System.IO.Stream userStream = openFileDialog1.OpenFile()) + { + this.RtfBoxMain.LoadFile(userStream, + RichTextBoxStreamType.PlainText); + userStream.Close(); + } + + // Tries to get the file name selected by the user. + // Failure means that the application does not have + // unrestricted permission to the file. + try + { + editingFileName = openFileDialog1.FileName; + } + catch (Exception ex) + { + if (ex is System.Security.SecurityException) + { + // The application does not have unrestricted permission + // to the file so the save feature will be disabled. + saveAllowed = false; + } + else + { + throw ex; + } + } + } +} +``` + +> [!NOTE] +> In Visual C#, ensure that you add code to enable the event handler. By using the code from the previous example, the following code shows how to enable the event handler.`this.ButtonOpen.Click += newSystem.Windows.Forms.EventHandler(this.ButtonOpen_Click);` + +### Other Files + Sometimes you will need to read or write to files that the user does not specify, such as when you must persist application settings. In the local intranet and Internet zones, your application will not have permission to store data in a local file. However, your application will be able to store data in isolated storage. Isolated storage is an abstract data compartment (not a specific storage location) that contains one or more isolated storage files, called stores, that contain the actual directory locations where data is stored. File access permissions like are not required; instead, the class controls the permissions for isolated storage. By default, applications that are running in the local intranet and Internet zones can store data using isolated storage; however, settings like disk quota can vary. For more information about isolated storage, see [Isolated Storage](https://docs.microsoft.com/dotnet/standard/io/isolated-storage). + + The following example uses isolated storage to write data to a file located in a store. The example requires and the enumeration value. The example demonstrates reading and writing certain property values of the control to a file in isolated storage. The `Read` function would be called after the application starts and the `Write` function would be called before the application ends. The example requires that the `Read` and `Write` functions exist as members of a that contains a control named `MainButton`. + +```vb +' Reads the button options from the isolated storage. Uses Default values +' for the button if the options file does not exist. +Public Sub Read() + Dim isoStore As System.IO.IsolatedStorage.IsolatedStorageFile = _ + System.IO.IsolatedStorage.IsolatedStorageFile. _ + GetUserStoreForDomain() + + Dim filename As String = "options.txt" + Try + ' Checks to see if the options.txt file exists. + If (isoStore.GetFileNames(filename).GetLength(0) <> 0) Then + + ' Opens the file because it exists. + Dim isos As New System.IO.IsolatedStorage.IsolatedStorageFileStream _ + (filename, IO.FileMode.Open,isoStore) + Dim reader as System.IO.StreamReader + Try + reader = new System.IO.StreamReader(isos) + + ' Reads the values stored. + Dim converter As System.ComponentModel.TypeConverter + converter = System.ComponentModel.TypeDescriptor.GetConverter _ + (GetType(Color)) + + Me.MainButton.BackColor = _ + CType(converter.ConvertFromString _ + (reader.ReadLine()), Color) + me.MainButton.ForeColor = _ + CType(converter.ConvertFromString _ + (reader.ReadLine()), Color) + + converter = System.ComponentModel.TypeDescriptor.GetConverter _ + (GetType(Font)) + me.MainButton.Font = _ + CType(converter.ConvertFromString _ + (reader.ReadLine()), Font) + + Catch ex As Exception + Debug.WriteLine("Cannot read options " + _ + ex.ToString()) + Finally + reader.Close() + End Try + End If + + Catch ex As Exception + Debug.WriteLine("Cannot read options " + ex.ToString()) + End Try +End Sub + +' Writes the button options to the isolated storage. +Public Sub Write() + Dim isoStore As System.IO.IsolatedStorage.IsolatedStorageFile = _ + System.IO.IsolatedStorage.IsolatedStorageFile. _ + GetUserStoreForDomain() + + Dim filename As String = "options.txt" + Try + ' Checks if the file exists, and if it does, tries to delete it. + If (isoStore.GetFileNames(filename).GetLength(0) <> 0) Then + isoStore.DeleteFile(filename) + End If + Catch ex As Exception + Debug.WriteLine("Cannot delete file " + ex.ToString()) + End Try + + ' Creates the options.txt file and writes the button options to it. + Dim writer as System.IO.StreamWriter + Try + Dim isos As New System.IO.IsolatedStorage.IsolatedStorageFileStream _ + (filename, IO.FileMode.CreateNew, isoStore) + + writer = New System.IO.StreamWriter(isos) + Dim converter As System.ComponentModel.TypeConverter + + converter = System.ComponentModel.TypeDescriptor.GetConverter _ + (GetType(Color)) + writer.WriteLine(converter.ConvertToString( _ + Me.MainButton.BackColor)) + writer.WriteLine(converter.ConvertToString( _ + Me.MainButton.ForeColor)) + + converter = System.ComponentModel TypeDescriptor.GetConverter _ + (GetType(Font)) + writer.WriteLine(converter.ConvertToString( _ + Me.MainButton.Font)) + + Catch ex as Exception + Debug.WriteLine("Cannot write options " + ex.ToString()) + + Finally + writer.Close() + End Try +End Sub +``` + +```csharp +// Reads the button options from the isolated storage. Uses default values +// for the button if the options file does not exist. +public void Read() +{ + System.IO.IsolatedStorage.IsolatedStorageFile isoStore = + System.IO.IsolatedStorage.IsolatedStorageFile. + GetUserStoreForDomain(); + + string filename = "options.txt"; + try + { + // Checks to see if the options.txt file exists. + if (isoStore.GetFileNames(filename).GetLength(0) != 0) + { + // Opens the file because it exists. + System.IO.IsolatedStorage.IsolatedStorageFileStream isos = + new System.IO.IsolatedStorage.IsolatedStorageFileStream + (filename, System.IO.FileMode.Open,isoStore); + System.IO.StreamReader reader = null; + try + { + reader = new System.IO.StreamReader(isos); + + // Reads the values stored. + TypeConverter converter ; + converter = TypeDescriptor.GetConverter(typeof(Color)); + + this.MainButton.BackColor = + (Color)(converter.ConvertFromString(reader.ReadLine())); + this.MainButton.ForeColor = + (Color)(converter.ConvertFromString(reader.ReadLine())); + + converter = TypeDescriptor.GetConverter(typeof(Font)); + this.MainButton.Font = + (Font)(converter.ConvertFromString(reader.ReadLine())); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine + ("Cannot read options " + ex.ToString()); + } + finally + { + reader.Close(); + } + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine + ("Cannot read options " + ex.ToString()); + } +} + +// Writes the button options to the isolated storage. +public void Write() +{ + System.IO.IsolatedStorage.IsolatedStorageFile isoStore = + System.IO.IsolatedStorage.IsolatedStorageFile. + GetUserStoreForDomain(); + + string filename = "options.txt"; + try + { + // Checks if the file exists and, if it does, tries to delete it. + if (isoStore.GetFileNames(filename).GetLength(0) != 0) + { + isoStore.DeleteFile(filename); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine + ("Cannot delete file " + ex.ToString()); + } + + // Creates the options file and writes the button options to it. + System.IO.StreamWriter writer = null; + try + { + System.IO.IsolatedStorage.IsolatedStorageFileStream isos = new + System.IO.IsolatedStorage.IsolatedStorageFileStream(filename, + System.IO.FileMode.CreateNew,isoStore); + + writer = new System.IO.StreamWriter(isos); + TypeConverter converter ; + + converter = TypeDescriptor.GetConverter(typeof(Color)); + writer.WriteLine(converter.ConvertToString( + this.MainButton.BackColor)); + writer.WriteLine(converter.ConvertToString( + this.MainButton.ForeColor)); + + converter = TypeDescriptor.GetConverter(typeof(Font)); + writer.WriteLine(converter.ConvertToString( + this.MainButton.Font)); + + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine + ("Cannot write options " + ex.ToString()); + } + finally + { + writer.Close(); + } +} +``` + +## Database Access + The permissions required to access a database vary based on the database provider; however, only applications that are running with the appropriate permissions can access a database through a data connection. For more information about the permissions that are required to access a database, see [Code Access Security and ADO.NET](https://docs.microsoft.com/dotnet/framework/data/adonet/code-access-security). + + If you cannot directly access a database because you want your application to run in partial trust, you can use a Web service as an alternative means to access your data. A Web service is a piece of software that can be programmatically accessed over a network. With Web services, applications can share data across code group zones. By default, applications in the local intranet and Internet zones are granted the right to access their sites of origin, which enables them to call a Web service hosted on the same server. For more information see [Web Services in ASP.NET AJAX](https://docs.microsoft.com/previous-versions/aspnet/bb398785(v=vs.100)) or [Windows Communication Foundation](https://docs.microsoft.com/dotnet/framework/wcf/index). + +## Registry Access + The class controls access to the operating system registry. By default, only applications that are running locally can access the registry. only grants an application the right to try registry access; it does not guarantee access will succeed, because the operating system still enforces security on the registry. + + Because you cannot access the registry under partial trust, you may need to find other methods of storing your data. When you store application settings, use isolated storage instead of the registry. Isolated storage can also be used to store other application-specific files. You can also store global application information about the server or site of origin, because by default an application is granted the right to access the site of its origin. + +## See also + +- [More Secure Printing in Windows Forms](more-secure-printing-in-windows-forms.md) +- [Additional Security Considerations in Windows Forms](additional-security-considerations-in-windows-forms.md) +- [Security in Windows Forms Overview](security-in-windows-forms-overview.md) +- [Windows Forms Security](windows-forms-security.md) +- [Mage.exe (Manifest Generation and Editing Tool)](https://docs.microsoft.com/dotnet/framework/tools/mage-exe-manifest-generation-and-editing-tool) +- [MageUI.exe (Manifest Generation and Editing Tool, Graphical Client)](https://docs.microsoft.com/dotnet/framework/tools/mageui-exe-manifest-generation-and-editing-tool-graphical-client) diff --git a/dotnet-desktop-guide/framework/winforms/more-secure-printing-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/more-secure-printing-in-windows-forms.md new file mode 100644 index 0000000000..cd9ff08c6e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/more-secure-printing-in-windows-forms.md @@ -0,0 +1,28 @@ +--- +title: "More Secure Printing" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, printing" + - "PrintingPermission class [Windows Forms], Windows Forms security" + - "printing [Windows Forms], security" + - "security [Windows Forms], printing" +ms.assetid: 48fd36ac-872f-4de0-902a-e52969cd4367 +--- +# More Secure Printing in Windows Forms +Windows Forms applications frequently include printing abilities. The .NET Framework uses the class to control access to printing capabilities and the associated enumeration value to indicate the level of access. By default, printing is enabled by default in the Local Intranet and Internet zones; however, the level of access is restricted in both zones. Whether your application can print, requires user interaction, or cannot print depends upon the permission value granted to the application. By default, the Local Intranet zone receives access and the Intranet zone receives access. + + The following table shows the functionality available at each printing permission level. + +|PrintingPermissionLevel|Description| +|-----------------------------|-----------------| +||Provides full access to all installed printers.| +||Enables programmatic printing to the default printer and safer printing through a restrictive printing dialog box. is a subset of .| +||Provides printing only from a more-restricted dialog box. is a subset of .| +||Prevents access to printers. is a subset of .| + +## See also + +- [More Secure File and Data Access in Windows Forms](more-secure-file-and-data-access-in-windows-forms.md) +- [Additional Security Considerations in Windows Forms](additional-security-considerations-in-windows-forms.md) +- [Security in Windows Forms Overview](security-in-windows-forms-overview.md) +- [Windows Forms Security](windows-forms-security.md) diff --git a/dotnet-desktop-guide/framework/winforms/mouse-capture-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/mouse-capture-in-windows-forms.md new file mode 100644 index 0000000000..3c39faba9d --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/mouse-capture-in-windows-forms.md @@ -0,0 +1,20 @@ +--- +title: "Mouse Capture" +ms.date: "03/30/2017" +helpviewer_keywords: + - "mouse [Windows Forms], capture" +ms.assetid: 8911d4b0-a4f8-4f93-8246-371aebd27d0c +--- +# Mouse Capture in Windows Forms +*Mouse capture* refers to when a control takes command of all mouse input. When a control has captured the mouse, it receives mouse input whether or not the pointer is within its borders. + +## Setting Mouse Capture + In Windows Forms the mouse is captured by the control when the user presses a mouse button on a control, and the mouse is released by the control when the user releases the mouse button. + + The property of the class specifies whether a control has captured the mouse. To determine when a control loses mouse capture, handle the event. + + Only the foreground window can capture the mouse. When a background window attempts to capture the mouse, the window receives messages only for mouse events that occur when the mouse pointer is within the visible portion of the window. Also, even if the foreground window has captured the mouse, the user can still click another window, bringing it to the foreground. When the mouse is captured, shortcut keys do not work. + +## See also + +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/mouse-events-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/mouse-events-in-windows-forms.md new file mode 100644 index 0000000000..d5a3784790 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/mouse-events-in-windows-forms.md @@ -0,0 +1,150 @@ +--- +title: "Mouse Events" +description: Learn how to get the mouse location from mouse events, and understand the order in which mouse click events are raised in Windows Forms controls. +ms.date: "03/30/2017" +helpviewer_keywords: + - "MouseLeave event [Windows Forms]" + - "events [Windows Forms], mouse" + - "Click event [Windows Forms], raising order" + - "Windows Forms controls, click events" + - "MouseDoubleClick event [Windows Forms]" + - "MouseEnter event [Windows Forms]" + - "MouseHover event [Windows Forms]" + - "MouseDown event [Windows Forms]" + - "MouseClick event [Windows Forms]" + - "MouseMove event [Windows Forms]" + - "mouse [Windows Forms], events" + - "MouseUp event" +ms.assetid: 8cf0070d-793b-4876-b09e-d20d28280fab +--- +# Mouse Events in Windows Forms + +When you handle mouse input, you usually want to know the location of the mouse pointer and the state of the mouse buttons. This topic provides details on how to get this information from mouse events, and explains the order in which mouse click events are raised in Windows Forms controls. For a list and description of all of the mouse events, see [How Mouse Input Works in Windows Forms](how-mouse-input-works-in-windows-forms.md). Also see [Event Handlers Overview (Windows Forms)](event-handlers-overview-windows-forms.md) and [Events Overview (Windows Forms)](events-overview-windows-forms.md). + +## 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 simply notify 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 a mouse button is pressed and released (regardless of which mouse button), 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: + +1. event. + +2. event. + +3. event. + +4. event. + +The following is the order of events raised for a double mouse-button click: + +1. event. + +2. event. + +3. event. + +4. event. + +5. event. + +6. 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.) + +7. event. + +8. event. + +For a code example that demonstrates the order of the mouse click events, see [How to: Handle User Input Events in Windows Forms Controls](how-to-handle-user-input-events-in-windows-forms-controls.md). + +### Individual Controls + +The following controls do not 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: + +1. The user presses the mouse button. + +2. The control paints in the pressed state. + +3. The event is raised. + +4. The user releases the mouse button. + +5. The control paints in the raised state. + +6. The event is raised. + +7. The event is raised. + +8. 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 + +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/mouse-input-in-a-windows-forms-application.md b/dotnet-desktop-guide/framework/winforms/mouse-input-in-a-windows-forms-application.md new file mode 100644 index 0000000000..92d05db5f1 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/mouse-input-in-a-windows-forms-application.md @@ -0,0 +1,32 @@ +--- +title: Mouse input +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, mouse input" +ms.assetid: 743c2f3c-219e-4a52-b6b8-2657096a2da6 +--- +# Mouse Input in a Windows Forms Application +Windows Forms includes a variety of mouse events and additional support for customized mouse cursors, mouse capture, and drag-and-drop behavior. + +## In This Section + [How Mouse Input Works in Windows Forms](how-mouse-input-works-in-windows-forms.md) + Provides information about the mouse events and how to get current information and system settings for the mouse. + + [Mouse Events in Windows Forms](mouse-events-in-windows-forms.md) + Provides information about the order in which the mouse events occur and how the mouse events are raised within specific controls. + + [How to: Distinguish Between Clicks and Double-Clicks](how-to-distinguish-between-clicks-and-double-clicks.md) + Demonstrates how to use single and double clicks to initiate incompatible actions. + + [Mouse Pointers in Windows Forms](mouse-pointers-in-windows-forms.md) + Describes how to change the mouse cursor. + + [Mouse Capture in Windows Forms](mouse-capture-in-windows-forms.md) + Describes how a control can capture the mouse. + + [Drag-and-Drop Functionality in Windows Forms](drag-and-drop-functionality-in-windows-forms.md) + Describes how to implement drag-and-drop behavior. + +## Related Sections + [Accessing the Mouse](https://docs.microsoft.com/dotnet/visual-basic/developing-apps/programming/computer-resources/accessing-the-mouse) + Lists topics for accessing the mouse using Visual Basic. diff --git a/dotnet-desktop-guide/framework/winforms/mouse-pointers-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/mouse-pointers-in-windows-forms.md new file mode 100644 index 0000000000..f3ef945a26 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/mouse-pointers-in-windows-forms.md @@ -0,0 +1,31 @@ +--- +title: "Mouse Pointers" +ms.date: "03/30/2017" +helpviewer_keywords: + - "pointers [Windows Forms], setting" + - "mouse pointers" + - "mouse cursors" + - "mouse pointers [Windows Forms], setting" + - "cursors [Windows Forms], setting" + - "mouse [Windows Forms], cursors" +ms.assetid: c3400d85-de5b-42e8-abc3-d6088d69ee53 +--- +# Mouse Pointers in Windows Forms +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. + +## 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. + +## 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. + +## 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. 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 + +- +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) +- [Drag-and-Drop Functionality in Windows Forms](drag-and-drop-functionality-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/multiple-controls-bound-to-data-source-synchronized.md b/dotnet-desktop-guide/framework/winforms/multiple-controls-bound-to-data-source-synchronized.md new file mode 100644 index 0000000000..324cd268fa --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/multiple-controls-bound-to-data-source-synchronized.md @@ -0,0 +1,42 @@ +--- +title: "How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized" +ms.date: "03/30/2017" +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "controls [Windows Forms], binding multiple" + - "controls [Windows Forms], synchronizing with data source" +ms.assetid: c2f0ecc6-11e6-4c2c-a1ca-0759630c451e +--- +# How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized +Oftentimes when working with data binding in Windows Forms, multiple controls are bound to the same data source. In some cases, it may be necessary to take extra steps to ensure that the bound properties of the controls remain synchronized with each other and the data source. These steps are necessary in two situations: + +- If the data source does not implement , and therefore generate events of type . + +- If the data source implements . + + In the former case, you can use a to bind the data source to the controls. In the latter case, you use a and handle the event and call on the associated . + +## Example + The following code example demonstrates how to bind three controls—two text-box controls and a control—to the same column in a using a component. This example demonstrates how to handle the event and ensure that when the text value of one text box is changed, the additional text box and the control are updated with the correct value. + + The example uses a to bind the data source and the controls. Alternatively, you can bind the controls directly to the data source and retrieve the for the binding from the form's and then handle the event for the . For an example of how to do this, see the Help page about the event of . + + [!code-csharp[System.Windows.Forms.BindingSourceMultipleControls#1](~/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/CS/Form1.cs#1)] + [!code-vb[System.Windows.Forms.BindingSourceMultipleControls#1](~/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/VB/Form1.vb#1)] + +## Compiling the Code + +- This code example requires + +- References to the , , and assemblies. + +- A form with the event handled and a call to the `InitializeControlsAndDataSource` method in the example from the form's event handler. + +## See also + +- [How to: Share Bound Data Across Forms Using the BindingSource Component](./controls/how-to-share-bound-data-across-forms-using-the-bindingsource-component.md) +- [Change Notification in Windows Forms Data Binding](change-notification-in-windows-forms-data-binding.md) +- [Interfaces Related to Data Binding](interfaces-related-to-data-binding.md) +- [Windows Forms Data Binding](windows-forms-data-binding.md) diff --git a/dotnet-desktop-guide/framework/winforms/order-of-events-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/order-of-events-in-windows-forms.md new file mode 100644 index 0000000000..0eb600ea8f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/order-of-events-in-windows-forms.md @@ -0,0 +1,80 @@ +--- +title: "Order of Events" +description: Learn details regarding the order of events in Windows Forms during several important stages in the lifetime of applications and controls. +ms.date: "03/30/2017" +helpviewer_keywords: + - "events [Windows Forms], order of" + - "focus event order" + - "application shutdown event order" + - "sequence [Windows Forms], of events" + - "validation events [Windows Forms], order of" + - "application startup event order" +ms.assetid: e81db09b-4453-437f-b78a-62d7cd5c9829 +--- +# Order of Events in Windows Forms +The order in which events are raised in Windows Forms applications is of particular interest to developers concerned with handling each of these events in turn. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. This topic provides some details on the order of events during several important stages in the lifetime of applications and controls. For specific details about the order of mouse input events, see [Mouse Events in Windows Forms](mouse-events-in-windows-forms.md). For an overview of events in Windows Forms, see [Events Overview](events-overview-windows-forms.md). For details about the makeup of event handlers, see [Event Handlers Overview](event-handlers-overview-windows-forms.md). + +## Application Startup and Shutdown Events + The and classes expose a set of events related to application startup and shutdown. When a Windows Forms application starts, the startup events of the main form are raised in the following order: + +- + +- + +- + +- + +- + +- + + When an application closes, the shutdown events of the main form are raised in the following order: + +- + +- + +- + +- + +- + + The event of the class is raised after the shutdown events of the main form. + +> [!NOTE] +> Visual Basic 2005 includes additional application events, such as and . + +## Focus and Validation Events + When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the or methods, or by setting the property to the current form, focus events of the class occur in the following order: + +- + +- + +- + +- + +- + +- + + When you change the focus by using the mouse or by calling the method, focus events of the class occur in the following order: + +- + +- + +- + +- + +- + +- + +## See also + +- [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md) diff --git a/dotnet-desktop-guide/framework/winforms/security-in-windows-forms-overview.md b/dotnet-desktop-guide/framework/winforms/security-in-windows-forms-overview.md new file mode 100644 index 0000000000..85757c19c2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/security-in-windows-forms-overview.md @@ -0,0 +1,89 @@ +--- +title: Security overview +ms.date: "03/30/2017" +helpviewer_keywords: + - "code access security [Windows Forms], Windows Forms" + - "permissions [Windows Forms], Windows Forms" + - "Windows Forms, security" + - "security [Windows Forms], about security" + - "access control [Windows Forms], Windows Forms" +ms.assetid: 4810dc9f-ea23-4ce1-8ea1-657f0ff1d820 +--- +# Security in Windows Forms Overview + +Before the release of the .NET Framework, all code running on a user's computer had the same rights or permissions to access resources that a user of the computer had. For example, if the user was allowed to access the file system, the code was allowed to access the file system; if the user was allowed to access a database, the code was allowed to access that database. Although these rights or permissions may be acceptable for code in executables that the user has explicitly installed on the local computer, they may not be acceptable for potentially malicious code coming from the Internet or a local Intranet. This code should not be able to access the user's computer resources without permission. + +The .NET Framework introduces an infrastructure called Code Access Security that lets you differentiate the permissions, or rights, that code has from the rights that the user has. By default, code coming from the Internet and the Intranet can only run in what is known as partial trust. Partial trust subjects an application to a series of restrictions: among other things, an application is restricted from accessing the local hard disk, and cannot run unmanaged code. The .NET Framework controls the resources that code is allowed to access based on the identity of that code: where it came from, whether it has a [Strong-Named Assemblies](https://docs.microsoft.com/dotnet/standard/assembly/strong-name), whether it is signed with a certificate, and so on. + +ClickOnce technology, which you use to deploy Windows Forms applications, helps make it easier for you to develop applications that run in partial trust, in full trust, or in partial trust with elevated permissions. ClickOnce provides features such as Permission Elevation and Trusted Application Deployment so that your application can request full trust or elevated permissions from the local user in a responsible manner. + +## Understanding Security in the .NET Framework + +Code access security allows code to be trusted to varying degrees, depending on where the code originates and on other aspects of the code's identity. For more information about the evidence the common language runtime uses to determine security policy, see [Evidence](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/7y5x1hcd(v=vs.100)). It helps protect computer systems from malicious code and helps protect trusted code from intentionally or accidentally compromising security. Code access security also gives you more control over what actions your application can perform, because you can specify only those permissions you need your application to have. Code access security affects all managed code that targets the common language runtime, even if that code does not make a single code-access-security permission check. For more information about security in the .NET Framework, see [Key Security Concepts](https://docs.microsoft.com/dotnet/standard/security/key-security-concepts) and [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics). + +If the user run a Windows Forms executable file directly off of a Web server or a file share, the degree of trust granted to your application depends on where the code resides, and how it is started. When an application runs, it is automatically evaluated and it receives a named permission set from the common language runtime. By default, the code from the local computer is granted the Full Trust permission set, code from a local network is granted the Local Intranet permission set, and code from the Internet is granted the Internet permission set. + +> [!NOTE] +> In the .NET Framework version 1.0 Service Pack 1 and Service Pack 2, the Internet zone code group receives the Nothing permission set. In all other releases of the .NET Framework, the Internet zone code group receives the Internet permissions set. +> +> The default permissions granted in each of these permission sets are listed in the [Default Security Policy](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/03kwzyfc(v=vs.100)) topic. Depending on the permissions that the application receives, it either runs correctly or generates a security exception. +> +> Many Windows Forms applications will be deployed using ClickOnce. The tools used for generating a ClickOnce deployment have different security defaults than what was discussed earlier. For more information, see the following discussion. + +The actual permissions granted to your application can be different from the default values, because the security policy can be modified; this means that your application can have permission on one computer, but not on another. + +## Developing a More Secure Windows Forms Application + +Security is important in all steps of application development. Start by reviewing and following the [Secure Coding Guidelines](https://docs.microsoft.com/dotnet/standard/security/secure-coding-guidelines). + +Next, decide whether your application must run in full trust, or whether it should run in partial trust. Running your application in full trust makes it easier to access resources on the local computer, but exposes your application and its users to high security risks if you do not design and develop your application strictly according to the Secure Coding Guidelines topic. Running your application in partial trust makes it easier to develop a more secure application and reduces much risk, but requires more planning in how to implement certain features. + +If you choose partial trust (that is, either the Internet or Local Intranet permission sets), decide how you want your application to behave in this environment. Windows Forms provides alternative, more secure ways to implement features when in a semi-trusted environment. Certain parts of your application, such as data access, can be designed and written differently for both partial trust and full trust environments. Some Windows Forms features, such as application settings, are designed to work in partial trust. For more information, see [Application Settings Overview](./advanced/application-settings-overview.md). + +If your application needs more permissions than partial trust allows, but you do not want to run in full trust, you can run in partial trust while asserting only those additional permissions you need. For example, if you want to run in partial trust, but must grant your application read-only access to a directory on the user's file system, you can request only for that directory. Used correctly, this approach can give your application increased functionality and minimize security risks to your users. + +When you develop an application that will run in partial trust, keep track of what permissions your application must run and what permissions your application could optionally use. When all the permissions are known, you should make a declarative request for permission at the application level. Requesting permissions informs the .NET Framework run time about which permissions your application needs and which permissions it specifically does not want. For more information about requesting permissions, see [Requesting Permissions](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/yd267cce(v=vs.100)). + +When you request optional permissions, you must handle security exceptions that will be generated if your application performs an action that requires permissions not granted to it. Appropriate handling of the will ensure that your application can continue to operate. Your application can use the exception to determine whether a feature should become disabled for the user. For example, an application can disable the **Save** menu option if the required file permission is not granted. + +Sometimes, it is difficult to know if you have asserted all the appropriate permissions. A method call which looks innocuous on the surface, for example, may access the file system at some point during its execution. If you do not deploy your application with all the required permissions, it may test fine when you debug it on your desktop, but fail when deployed. Both the .NET Framework 2.0 SDK and Visual Studio 2005 contain tools for calculating the permissions an application needs: the MT.exe command line tool and the Calculate Permissions feature of Visual Studio, respectively. + +The following topics describe additional Windows Forms security features. + +|Topic|Description| +|-----------|-----------------| +|- [More Secure File and Data Access in Windows Forms](more-secure-file-and-data-access-in-windows-forms.md)|Describes how to access files and data in a partial trust environment.| +|- [More Secure Printing in Windows Forms](more-secure-printing-in-windows-forms.md)|Describes how to access printing features in a partial trust environment.| +|- [Additional Security Considerations in Windows Forms](additional-security-considerations-in-windows-forms.md)|Describes performing window manipulation, using the Clipboard, and making calls to unmanaged code in a partial trust environment.| + +### Deploying an Application with the Appropriate Permissions + +The most common means of deploying a Windows Forms application to a client computer is with ClickOnce, a deployment technology that describes all of the components your application needs to run. ClickOnce uses XML files called manifests to describe the assemblies and files that make up your application, and also the permissions your application requires. + +ClickOnce has two technologies for requesting elevated permissions on a client computer. Both technologies rely on the use of Authenticode certificates. The certificates help provide some assurance to your users that the application has come from a trusted source. + +The following table describes these technologies. + +|Elevated permission technology|Description| +|------------------------------------|-----------------| +|Permission Elevation|Prompts the user with a security dialog box the first time your application runs. The **Permission Elevation** dialog box informs the user about who published the application, so that the user can make an informed decision about whether to grant it additional trust| +|Trusted Application Deployment|Involves a system administrator performing a one-time installation of a publisher's Authenticode certificate on a client computer. From that point on, any applications signed with the certificate are regarded as trusted, and can run at full trust on the local computer without additional prompting.| + +Which technology you choose will depend on your deployment environment. For more information, see [Choosing a ClickOnce Deployment Strategy](/visualstudio/deployment/choosing-a-clickonce-deployment-strategy). + +By default, ClickOnce applications deployed using either Visual Studio or the .NET Framework SDK tools (Mage.exe and MageUI.exe) are configured to run on a client computer that has Full Trust. If you are deploying your application by using partial trust or by using only some additional permissions, you will have to change this default. You can do this with either Visual Studio or the .NET Framework SDK tool MageUI.exe when you configure your deployment. For more information about how to use MageUI.exe, see [Walkthrough: Manually deploying a ClickOnce application](/visualstudio/deployment/walkthrough-manually-deploying-a-clickonce-application). Also see [How to: Set Custom Permissions for a ClickOnce Application](https://docs.microsoft.com/previous-versions/visualstudio/visual-studio-2012/hafybdaa(v=vs.110)) or [How to: Set Custom Permissions for a ClickOnce Application](/visualstudio/deployment/how-to-set-custom-permissions-for-a-clickonce-application). + +For more information about the security aspects of ClickOnce and Permission Elevation, see [Securing ClickOnce Applications](/visualstudio/deployment/securing-clickonce-applications). For more information about Trusted Application Deployment, see [Trusted Application Deployment Overview](/visualstudio/deployment/trusted-application-deployment-overview). + +### Testing the Application + +If you have deployed your Windows Forms application by using Visual Studio, you can enable debugging in partial trust or a restricted permission set from the development environment. Also see [How to: Debug a ClickOnce Application with Restricted Permissions](/visualstudio/deployment/how-to-debug-a-clickonce-application-with-restricted-permissions). + +## See also + +- [Windows Forms Security](windows-forms-security.md) +- [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics) +- [ClickOnce Security and Deployment](/visualstudio/deployment/clickonce-security-and-deployment) +- [Trusted Application Deployment Overview](/visualstudio/deployment/trusted-application-deployment-overview) +- [Mage.exe (Manifest Generation and Editing Tool)](https://docs.microsoft.com/dotnet/framework/tools/mage-exe-manifest-generation-and-editing-tool) +- [MageUI.exe (Manifest Generation and Editing Tool, Graphical Client)](https://docs.microsoft.com/dotnet/framework/tools/mageui-exe-manifest-generation-and-editing-tool-graphical-client) diff --git a/dotnet-desktop-guide/framework/winforms/toc.yml b/dotnet-desktop-guide/framework/winforms/toc.yml new file mode 100644 index 0000000000..eca63471d8 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/toc.yml @@ -0,0 +1,138 @@ +- name: Windows Forms + href: index.yml + items: + - name: Getting Started with Windows Forms + href: getting-started-with-windows-forms.md + - name: Windows Forms Overview + href: windows-forms-overview.md + - name: Creating a New Windows Form + href: creating-a-new-windows-form.md + items: + - name: "How to: Create a Windows Forms Application from the Command Line" + href: how-to-create-a-windows-forms-application-from-the-command-line.md + - name: Windows Forms Coordinates + href: windows-forms-coordinates.md + - name: Creating Event Handlers in Windows Forms + href: creating-event-handlers-in-windows-forms.md + items: + - name: Events Overview + href: events-overview-windows-forms.md + - name: Event Handlers Overview + href: event-handlers-overview-windows-forms.md + - name: "How to: Create Event Handlers at Run Time for Windows Forms" + href: how-to-create-event-handlers-at-run-time-for-windows-forms.md + - name: "How to: Connect Multiple Events to a Single Event Handler in Windows Forms" + href: how-to-connect-multiple-events-to-a-single-event-handler-in-windows-forms.md + - name: Order of Events in Windows Forms + href: order-of-events-in-windows-forms.md + - name: Adjusting the Size and Scale of Windows Forms + href: adjusting-the-size-and-scale-of-windows-forms.md + items: + - name: "How to: Resize Windows Forms" + href: how-to-resize-windows-forms.md + - name: Automatic Scaling in Windows Forms + href: automatic-scaling-in-windows-forms.md + items: + - name: "How to: Respond to Font Scheme Changes in a Windows Forms Application" + href: how-to-respond-to-font-scheme-changes-in-a-windows-forms-application.md + - name: High DPI Support In Windows Forms + href: high-dpi-support-in-windows-forms.md + - name: Changing the Appearance of Windows Forms + href: changing-the-appearance-of-windows-forms.md + items: + - name: "How to: Change the Borders of Windows Forms" + href: how-to-change-the-borders-of-windows-forms.md + - name: Windows Forms Controls + href: ./controls/ + - name: User Input in Windows Forms + href: user-input-in-windows-forms.md + items: + - name: User Input in a Windows Forms Application + href: user-input-in-a-windows-forms-application.md + - name: Keyboard Input in a Windows Forms Application + href: keyboard-input-in-a-windows-forms-application.md + items: + - name: How Keyboard Input Works + href: how-keyboard-input-works.md + - name: Using Keyboard Events + href: using-keyboard-events.md + - name: "How to: Modify Keyboard Input to a Standard Control" + href: how-to-modify-keyboard-input-to-a-standard-control.md + - name: "How to: Determine Which Modifier Key Was Pressed" + href: how-to-determine-which-modifier-key-was-pressed.md + - name: "How to: Handle Keyboard Input at the Form Level" + href: how-to-handle-keyboard-input-at-the-form-level.md + - name: Mouse Input in a Windows Forms Application + href: mouse-input-in-a-windows-forms-application.md + items: + - name: How Mouse Input Works in Windows Forms + href: how-mouse-input-works-in-windows-forms.md + - name: Mouse Events in Windows Forms + href: mouse-events-in-windows-forms.md + - name: "How to: Distinguish Between Clicks and Double-Clicks" + href: how-to-distinguish-between-clicks-and-double-clicks.md + - name: Mouse Pointers in Windows Forms + href: mouse-pointers-in-windows-forms.md + - name: Mouse Capture in Windows Forms + href: mouse-capture-in-windows-forms.md + - name: Drag-and-Drop Functionality in Windows Forms + href: drag-and-drop-functionality-in-windows-forms.md + - name: "How to: Simulate Mouse and Keyboard Events in Code" + href: how-to-simulate-mouse-and-keyboard-events-in-code.md + - name: "How to: Handle User Input Events in Windows Forms Controls" + href: how-to-handle-user-input-events-in-windows-forms-controls.md + - name: User Input Validation in Windows Forms + href: user-input-validation-in-windows-forms.md + - name: Dialog Boxes in Windows Forms + href: dialog-boxes-in-windows-forms.md + items: + - name: "How to: Display Dialog Boxes for Windows Forms" + href: how-to-display-dialog-boxes-for-windows-forms.md + - name: Windows Forms Data Binding + href: windows-forms-data-binding.md + items: + - name: Data Binding and Windows Forms + href: data-binding-and-windows-forms.md + - name: Data Sources Supported by Windows Forms + href: data-sources-supported-by-windows-forms.md + - name: Interfaces Related to Data Binding + href: interfaces-related-to-data-binding.md + - name: Change Notification in Windows Forms Data Binding + href: change-notification-in-windows-forms-data-binding.md + - name: "How to: Apply the PropertyNameChanged Pattern" + href: how-to-apply-the-propertynamechanged-pattern.md + - name: "How to: Create a Bound Control and Format the Displayed Data" + href: how-to-create-a-bound-control-and-format-the-displayed-data.md + - name: "How to: Create a Simple-Bound Control on a Windows Form" + href: how-to-create-a-simple-bound-control-on-a-windows-form.md + - name: "How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized" + href: multiple-controls-bound-to-data-source-synchronized.md + - name: "How to: Ensure the Selected Row in a Child Table Remains at the Correct Position" + href: ensure-the-selected-row-in-a-child-table-correct.md + - name: "How to: Implement the IListSource Interface" + href: how-to-implement-the-ilistsource-interface.md + - name: "How to: Implement the INotifyPropertyChanged Interface" + href: how-to-implement-the-inotifypropertychanged-interface.md + - name: "How to: Implement the ITypedList Interface" + href: how-to-implement-the-itypedlist-interface.md + - name: "How to: Navigate Data in Windows Forms" + href: how-to-navigate-data-in-windows-forms.md + - name: Windows Forms Security + href: windows-forms-security.md + items: + - name: Security in Windows Forms Overview + href: security-in-windows-forms-overview.md + - name: More Secure File and Data Access in Windows Forms + href: more-secure-file-and-data-access-in-windows-forms.md + - name: More Secure Printing in Windows Forms + href: more-secure-printing-in-windows-forms.md + - name: Additional Security Considerations in Windows Forms + href: additional-security-considerations-in-windows-forms.md + - name: ClickOnce Deployment for Windows Forms + href: clickonce-deployment-for-windows-forms.md + - name: Accessibility improvements with .NET Core 3.0 + href: windows-forms-accessibility-improvements.md + - name: "How to: Access Keyed Collections in Windows Forms" + href: how-to-access-keyed-collections-in-windows-forms.md + - name: Enhancing Windows Forms Applications + href: ./advanced/ diff --git a/dotnet-desktop-guide/framework/winforms/user-input-in-a-windows-forms-application.md b/dotnet-desktop-guide/framework/winforms/user-input-in-a-windows-forms-application.md new file mode 100644 index 0000000000..74961abbef --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/user-input-in-a-windows-forms-application.md @@ -0,0 +1,32 @@ +--- +title: User input in a Windows Forms app +titleSuffix: "" +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms, user input" +ms.assetid: 9d61fa96-70f7-4754-885a-49a4a6316bdb +--- +# User Input in a Windows Forms Application +In Windows Forms, user input is sent to applications in the form of Windows messages. A series of overridable methods process these messages at the application, form, and control level. When these methods receive mouse and keyboard messages, they raise events that can be handled to get information about the mouse or 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. + +## Mouse and 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, or a control can handle the event to determine the location of a mouse click. For more information on the mouse and keyboard events, see [Using Keyboard Events](using-keyboard-events.md) and [Mouse Events in Windows Forms](mouse-events-in-windows-forms.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 [How Keyboard Input Works](how-keyboard-input-works.md) and [How Mouse Input Works in Windows Forms](how-mouse-input-works-in-windows-forms.md). + +## See also + +- [User Input in Windows Forms](user-input-in-windows-forms.md) +- [Keyboard Input in a Windows Forms Application](keyboard-input-in-a-windows-forms-application.md) +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/user-input-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/user-input-in-windows-forms.md new file mode 100644 index 0000000000..d16251bbb4 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/user-input-in-windows-forms.md @@ -0,0 +1,34 @@ +--- +title: "User Input" +ms.date: "03/30/2017" +helpviewer_keywords: + - "keyboard input [Windows Forms], using in Windows Forms" + - "Windows Forms, user input" + - "mouse input [Windows Forms], using in Windows Forms" + - "keyboards [Windows Forms], keyboard input" +ms.assetid: 1486075f-1e06-4c9e-82c6-f948331db6d6 +--- +# User Input in Windows Forms +Windows Forms includes a user input model based on events that are raised while processing related Windows messages. The topics in this section provide information on mouse and keyboard user input, including code examples that demonstrate how to perform specific tasks. + +## In This Section + [User Input in a Windows Forms Application](user-input-in-a-windows-forms-application.md) + Provides an overview of user input events and the methods that process Windows messages. + + [Keyboard Input in a Windows Forms Application](keyboard-input-in-a-windows-forms-application.md) + Provides information on keyboard message handling, the different types of keys, and the keyboard events. + + [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) + Provides information on the mouse events and other mouse-related features, including mouse cursors and mouse capture. + + [How to: Simulate Mouse and Keyboard Events in Code](how-to-simulate-mouse-and-keyboard-events-in-code.md) + Demonstrates several different ways to programmatically simulate mouse and keyboard input. + + [How to: Handle User Input Events in Windows Forms Controls](how-to-handle-user-input-events-in-windows-forms-controls.md) + Presents a code example that handles most user input events and reports information about each event. + + [User Input Validation in Windows Forms](user-input-validation-in-windows-forms.md) + Describes the methods to validate user input in Windows Forms applications. + +## Related Sections + Also see [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md). diff --git a/dotnet-desktop-guide/framework/winforms/user-input-validation-in-windows-forms.md b/dotnet-desktop-guide/framework/winforms/user-input-validation-in-windows-forms.md new file mode 100644 index 0000000000..ec5a92a2d7 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/user-input-validation-in-windows-forms.md @@ -0,0 +1,94 @@ +--- +title: "User Input Validation" +description: Learn about several ways that you can use Windows Forms to validate user input in your applications. +ms.date: "03/30/2017" +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" +ms.assetid: 4ec07681-1dee-4bf9-be5e-718f635a33a1 +--- +# User Input Validation in Windows Forms +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 be formatted as a telephone number or other type of well-formed data, or that a string not contain any unsafe characters that could be used to compromise the security of a database. Windows Forms provides several ways for you to validate input in your application. + +## Validation with the 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 very 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. + + For more information, see [MaskedTextBox Control](./controls/maskedtextbox-control-windows-forms.md). + +## Event-Driven Validation + If you want full programmatic control over validation, or need to perform complex validation checks, you should use the validation events 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 perform the validation in the following ways: + +- If the postal code must belong to a specific group of zip codes, you can perform 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 Framework Regular Expressions](https://docs.microsoft.com/dotnet/standard/base-types/regular-expressions) and [Regular Expression Examples](https://docs.microsoft.com/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 is not valid, you can cancel the event by setting this object's property to `true`. If you do not 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 . + +### Data Binding and Event-Driven Validation + Validation is very 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 does not 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 will not be synchronized with the data source. + +> [!IMPORTANT] +> If you have custom validation that takes place after the event, it will not 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 **Data Source Update Mode** property (**under (Databindings)**\\**(Advanced)**) from **OnValidation** to **Never**, and add *Control*`.DataBindings["`*\*`"].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. You can validate the data as the data is entered in a control by reading the keys as they are pressed, or more commonly whenever the user takes the input focus away from one control and moves to the next. This approach is useful when you want to give the user immediate feedback about the data as they are 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 that 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 input. If you assigned , the event will not 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 will 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 Windows Forms 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 is impossible to close the parent form in one of the usual ways: + +- By clicking the **Close** button. + +- By selecting **Close** in the **System** 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 do not validate the contents of controls when they are closed. You can still use control validation to lock focus to a control, but you do not have to be concerned about the behavior associated with closing the form. + +## See also + +- +- +- +- [MaskedTextBox Control](./controls/maskedtextbox-control-windows-forms.md) +- [Regular Expression Examples](https://docs.microsoft.com/dotnet/standard/base-types/regular-expression-example-scanning-for-hrefs) diff --git a/dotnet-desktop-guide/framework/winforms/using-keyboard-events.md b/dotnet-desktop-guide/framework/winforms/using-keyboard-events.md new file mode 100644 index 0000000000..34d36736d3 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/using-keyboard-events.md @@ -0,0 +1,39 @@ +--- +title: "Using Keyboard Events" +ms.date: "03/30/2017" +helpviewer_keywords: + - "KeyPress event [Windows Forms]" + - "keyboards [Windows Forms], keyboard events" + - "KeyUp event" + - "KeyDown event" + - "keyboard events" + - "events [Windows Forms], keyboard" +ms.assetid: d3f3e14b-a459-4ee6-9875-8957e34f8ee9 +--- +# Using Keyboard Events +Most Windows Forms programs process keyboard input by handling the keyboard events. This topic provides an overview of the keyboard events, including details on when to use each event and the data that is supplied for each event. Also see [Event Handlers Overview (Windows Forms)](event-handlers-overview-windows-forms.md) and [Events Overview (Windows Forms)](events-overview-windows-forms.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 [How Keyboard Input Works](how-keyboard-input-works.md). + + 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 + +- [Keyboard Input in a Windows Forms Application](keyboard-input-in-a-windows-forms-application.md) +- [How Keyboard Input Works](how-keyboard-input-works.md) +- [Mouse Input in a Windows Forms Application](mouse-input-in-a-windows-forms-application.md) diff --git a/dotnet-desktop-guide/framework/winforms/windows-forms-accessibility-improvements.md b/dotnet-desktop-guide/framework/winforms/windows-forms-accessibility-improvements.md new file mode 100644 index 0000000000..559c0168e2 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/windows-forms-accessibility-improvements.md @@ -0,0 +1,98 @@ +--- +title: "Windows Forms Accessibility Improvements" +description: Learn about the ways in which .NET Core Windows Forms attempts to improve accessibility in comparison with .NET Framework Windows Forms. +ms.date: "04/20/2020" +helpviewer_keywords: + - "Windows Forms accessibility" + - "accessibility" +author: "M-Lipin" +--- +# Accessibility improvements in Windows Forms controls for .NET Core 3.0 + +Windows Forms is continuing to improve how it works with accessibility technologies to better support Windows Forms customers. These improvements include the following changes: + +- Changes in various areas of interaction with accessibility client applications, including Narrator. +- Changes in the Accessible hierarchy (improving navigation through the UI Automation tree). +- Changes in keyboard navigation. + +> [!IMPORTANT] +> Accessibility changes made in .NET Framework 4.7.1 through .NET Framework 4.8 are included in .NET Core 3.0 and above, and are enabled by default. The .NET Framework supported compatibility switches that allowed applications to opt out of the new accessibility behavior. On the other hand, .NET Core doesn't support these settings and doesn't allow applications to opt out of accessibility behavior. + +Starting with .NET Core 3.0, Windows Forms applications benefit from all the new accessibility features (introduced in .NET Framework 4.7.1 - 4.8) without additional configuration. + +## ListBox Accessibility support + +The following changes apply to the control: + +- Enabled UI Automation support for `ListBox` control. +- Improved `ListBox` accessibility support by adding the to `ListBox` items and by enhancing the accessibility event raising and handling and Narrator navigation through the items (caps lock navigation isn't correct and doesn't throw the navigation outside the control unintentionally). + +## CheckedListBox Accessibility support + +The following changes apply to the control: + +- Corrected `CheckedListBox` Bounds provided by accessibility properties for entries. +- Improved overall `ListBox` and `CheckedListBox` accessibility: corrected property values and event model. + +## ComboBox Accessibility support + +The following changes apply to the control: + +- Updated the process of getting `ComboBox` items' accessibility objects to enable generating IDs for items instead of getting hash codes from items, which may be unsafe in case the function is overridden. + +## DataGridView Accessibility support + +The following changes apply to the control: + +- Corrected `DataGridView.Bounds` provided by accessibility properties for columns, rows, cells and corresponding headers, improved performance of bounding rectangle calculation. All accessibility bounds are represented correctly taking into account the bounds of entire control, along with its viewport. +- Corrected `Value.IsReadOnly` property value providing for accessible client applications. The property now shows correct `IsReadOnly` status for cells. +- Fixed the issue with event raising for the first cell change. Cell value can be changed without any issues including the first `DataGridView` control interaction. +- Improved `DataGridView` background color contrast when using Windows High Contrast themes. Changed `DataGridView` default back color when using HC#1, HC#2, and HC Black themes. + +## PropertyGrid Accessibility support + +The following changes apply to the control: + +- Corrected `PropertyGrid.Bounds` provided by accessibility properties for grid entries, improved performance of bounding rectangle calculation. For now all accessibility bounds are represented correctly taking into account the bounds of entire control, along with its viewport. +- Corrected accessible names and descriptions of subcontrols to not include control type names and to avoid double announcement for control type names. + +## ToolStrip Accessibility support + +The following changes apply to the control: + +- Improved navigation through `ToolStrip`, `MenuStrip`, and `StatusStrip` items. Corrected `ToolStrip` and `MenuStrip` shift-tab navigation, back-looping the menu items when shift-tab up-arrow is pressed, which navigates to the bottom menu element. +- Improved `MenuStrip` accessible navigation, corrected menu accessible control types for submenus to make submenus of type 'Menu' instead of 'MenuItem'. + +## PrintPreviewControl and PrintPreviewDialog Accessibility support + +The following changes apply to the print controls: + +- Improved accessible navigation (including Narrator navigation) through menu items. +- Improved High Contrast themes support and made the control element more contrasted. + +## StringCollectionEditor Accessibility support + +Windows Forms designer now uses the string collection editor with improved accessibility support. + +## MonthCalendar Accessibility support (available in .NET Core 3.1) + +The following changes apply to the control: + +- Added UI Automation server providers to `MonthCalendar` control, added UI Automation Grid pattern and Table pattern providers. +- Changed _table_ accessible control type to _calendar_ accessible control type for `MonthCalendar` except the case when the control has a preceding label control that defines `MonthCalendar` control accessible name, in this specific case accessible control type becomes _table_. +- Improved announcement of selected date for `MonthCalendar` control. +- Improved `MonthCalendar` control support for screen readers and other accessibility tools. At this moment, users can navigate the control elements and interact with these elements using keyboard-only input. With Narrator, use CAPS + arrow keys to navigation through the control elements and CAPS + Enter to invoke element default action. +- Improved arrow key navigation across `MonthCalendar` child elements with a focusing rectangle: blue focus rectangle for Narrator. +- Improved accessibility for hit test action for `MonthCalendar` control elements to allow getting `MonthCalendar` child accessible element by provided coordinates. + +## ToolTips accessibility (available in .NET Core 3.1) + +- Added ability to announce a tooltip text by screen reader applications such as NVDA and Narrator. Screen reader application can now announce the text of keyboard or mouse tooltip of any Windows Forms control that configured to show tooltips. + +## UI automation support for DataGridView, PropertyGrid, ListBox, ComboBox, ToolStrip, and other controls + +UI Automation support is enabled for controls at runtime but isn't used during design time. For an overview of UI automation, see the [UI Automation Overview](https://docs.microsoft.com/dotnet/framework/ui-automation/ui-automation-overview). + +## See also + +- [Accessibility Best Practices](https://docs.microsoft.com/dotnet/framework/ui-automation/accessibility-best-practices). diff --git a/dotnet-desktop-guide/framework/winforms/windows-forms-coordinates.md b/dotnet-desktop-guide/framework/winforms/windows-forms-coordinates.md new file mode 100644 index 0000000000..cb4a75046e --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/windows-forms-coordinates.md @@ -0,0 +1,28 @@ +--- +title: Coordinates +ms.date: "03/30/2017" +helpviewer_keywords: + - "Windows Forms coordinates" + - "screen coordinates" + - "client coordinates" + - "coordinates [Windows Forms], Windows Forms" +ms.assetid: cc06e61f-43b6-4408-a676-2542dcfcd96e +--- +# Windows Forms Coordinates +The coordinate system for a Windows Form is based on device coordinates, and the basic unit of measure when drawing in Windows Forms is the device unit (typically, the pixel). Points on the screen are described by x- and y-coordinate pairs, with the x-coordinates increasing to the right and the y-coordinates increasing from top to bottom. The location of the origin, relative to the screen, will vary depending on whether you are specifying screen or client coordinates. + +## Screen Coordinates + A Windows Forms application specifies the position of a window on the screen in screen coordinates. For screen coordinates, the origin is the upper-left corner of the screen. The full position of a window is often described by a structure containing the screen coordinates of two points that define the upper-left and lower-right corners of the window. + +## Client Coordinates + A Windows Forms application specifies the position of points in a form or control using client coordinates. The origin for client coordinates is the upper-left corner of the client area of the control or form. Client coordinates ensure that an application can use consistent coordinate values while drawing in a form or control, regardless of the position of the form or control on the screen. + + The dimensions of the client area are also described by a structure that contains client coordinates for the area. In all cases, the upper-left coordinate of the rectangle is included in the client area, while the lower-right coordinate is excluded. Graphics operations do not include the right and lower edges of a client area. For example the method will fill up to the right and lower edge of the specified rectangle, but will not include these edges. + +## Mapping From One Type of Coordinate to Another + Occasionally, you may need to map from screen coordinates to client coordinates. You can easily accomplish this by using the and methods available in the class. For example, the property of is reported in screen coordinates, but you may want to convert these to client coordinates. + +## See also + +- +- diff --git a/dotnet-desktop-guide/framework/winforms/windows-forms-data-binding.md b/dotnet-desktop-guide/framework/winforms/windows-forms-data-binding.md new file mode 100644 index 0000000000..db4808877f --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/windows-forms-data-binding.md @@ -0,0 +1,65 @@ +--- +title: Data Binding +description: Learn how to use data binding in Windows Forms to display and make changes to information from a data source in controls on the form. +ms.date: "03/30/2017" +helpviewer_keywords: + - "data [Windows Forms]" + - "Windows Forms, data binding" + - "data [Windows Forms], architecture" + - "Windows Forms controls, data binding" +ms.assetid: c3826d8e-ea25-4ad4-a669-45bfb19192aa +--- +# Windows Forms Data Binding +Data binding in Windows Forms gives you the means to display and make changes to information from a data source in controls on the form. You can bind to both traditional data sources as well as almost any structure that contains data. + +## In This Section + [Data Binding and Windows Forms](data-binding-and-windows-forms.md) + Provides an overview of data binding in Windows Forms. + + [Data Sources Supported by Windows Forms](data-sources-supported-by-windows-forms.md) + Describes the data sources that can be used with Windows Forms. + + [Interfaces Related to Data Binding](interfaces-related-to-data-binding.md) + Describes several of the interfaces used with Windows Forms data binding. + + [How to: Navigate Data in Windows Forms](how-to-navigate-data-in-windows-forms.md) + Shows how to navigate through items in a data source. + + [Change Notification in Windows Forms Data Binding](change-notification-in-windows-forms-data-binding.md) + Describes different types of change notification for Windows Forms data binding. + + [How to: Implement the INotifyPropertyChanged Interface](how-to-implement-the-inotifypropertychanged-interface.md) + Shows how to implement the interface. The interface communicates to a bound control the property changes on a business object + + [How to: Apply the PropertyNameChanged Pattern](how-to-apply-the-propertynamechanged-pattern.md) + Shows how to apply the *PropertyName*Changed pattern to properties of a Windows Forms user control. + + [How to: Implement the ITypedList Interface](how-to-implement-the-itypedlist-interface.md) + Shows how to enable discovery of the schema for a bindable list by implementing the interface. + + [How to: Implement the IListSource Interface](how-to-implement-the-ilistsource-interface.md) + Shows how to implement the interface to create a bindable class does not implement , but provides a list from another location. + + [How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized](multiple-controls-bound-to-data-source-synchronized.md) + Shows how to handle the event to ensure all controls bound to a data source remain synchronized. + + [How to: Ensure the Selected Row in a Child Table Remains at the Correct Position](ensure-the-selected-row-in-a-child-table-correct.md) + Shows how to ensure the selected row of a child table does not change, when a change is made to a field of the parent table. + + Also see [Interfaces Related to Data Binding](interfaces-related-to-data-binding.md), [How to: Navigate Data in Windows Forms](how-to-navigate-data-in-windows-forms.md), and [How to: Create a Simple-Bound Control on a Windows Form](how-to-create-a-simple-bound-control-on-a-windows-form.md). + +## Reference + + Describes the class that represents the binding between a bindable component and a data source. + + + Describes the class that encapsulates a data source for binding to controls. + +## Related Sections + [BindingSource Component](./controls/bindingsource-component.md) + Contains a list of topics that demonstrate how to use the component. + + [DataGridView Control](./controls/datagridview-control-windows-forms.md) + Provides a list of topics that demonstrate how to use a bindable datagrid control. + + Also see [Accessing Data in Visual Studio](/visualstudio/data-tools/accessing-data-in-visual-studio). diff --git a/dotnet-desktop-guide/framework/winforms/windows-forms-overview.md b/dotnet-desktop-guide/framework/winforms/windows-forms-overview.md new file mode 100644 index 0000000000..1aafe7a710 --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/windows-forms-overview.md @@ -0,0 +1,107 @@ +--- +title: Overview +description: Learn how you can use Windows Forms to build smart clients that meet the needs of today's enterprises and end users. +ms.date: "03/30/2017" +helpviewer_keywords: + - "smart clients" + - "Windows Forms, about Windows Forms" +ms.assetid: 3a2b6284-c8d6-4e1c-8c69-0bed38f38cd4 +--- +# Windows Forms overview + +The following overview discusses the advantages of smart client applications, the main features of Windows Forms programming, and how you can use Windows Forms to build smart clients that meet the needs of today's enterprises and end users. + +## Windows Forms and smart client apps + + With Windows Forms you develop smart clients. *Smart clients* are graphically rich applications that are easy to deploy and update, can work when they are connected to or disconnected from the Internet, and can access resources on the local computer in a more secure manner than traditional Windows-based applications. + +### Build rich, interactive user interfaces + + Windows Forms is a smart client technology for the .NET Framework, a set of managed libraries that simplify common application 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 applications 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 applications by adding controls to forms and developing responses to user actions, such as mouse clicks or key presses. A *control* is a discrete user interface (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 application reacts to these events by using code, and processes the events when they occur. For more information, see [Creating Event Handlers in Windows Forms](creating-event-handlers-in-windows-forms.md). + + 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 Web pages. For a list of all the controls you can use on a form, see [Controls to Use on Windows Forms](./controls/controls-to-use-on-windows-forms.md). If an existing control does not 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 applications like Microsoft Office. When you use the and control, 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 applications. Just select the controls with your cursor and add 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. And whether you use Visual Studio or compile at the command line, 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. + +> [!NOTE] +> Windows Forms controls are not designed to be marshaled across application domains. For this reason, Microsoft does not support passing a Windows Forms control across an boundary, even though the base type of would seem to indicate that this is possible. Windows Forms applications that have multiple application domains are supported as long as no Windows Forms controls are passed across application domain boundaries. + +#### Create forms and controls + +For step-by-step information about how to use these features, see the following Help topics. + +|Description|Help topic| +|-----------------|----------------| +|Using controls on forms|[How to: Add Controls to Windows Forms](./controls/how-to-add-controls-to-windows-forms.md)| +|Using the Control|[How to: Create a Basic ToolStrip with Standard Items Using the Designer](./controls/create-a-basic-wf-toolstrip-with-standard-items-using-the-designer.md)| +|Creating graphics with |[Getting Started with Graphics Programming](./advanced/getting-started-with-graphics-programming.md)| +|Creating custom controls|[How to: Inherit from the UserControl Class](./controls/how-to-inherit-from-the-usercontrol-class.md)| + +### Display and manipulate data + Many applications must display data from a database, XML file, XML 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 smart clients. 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. 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 smart client applications 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. + +#### Display and manipulate data + +For step-by-step information about how to use these features, see the following Help topics. + +|Description|Help topic| +|-----------------|----------------| +|Using the component|[How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer](./controls/bind-wf-controls-with-the-bindingsource.md)| +|Working with ADO.NET data sources|[How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component](./controls/sort-and-filter-ado-net-data-with-wf-bindingsource-component.md)| +|Using the Data Sources window|[Bind Windows Forms controls to data in Visual Studio](/visualstudio/data-tools/bind-windows-forms-controls-to-data-in-visual-studio)| +|Using application settings|[How to: Create Application Settings](./advanced/how-to-create-application-settings.md)| + +### Deploy apps to client computers + +After you have written your application, you must send the application 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 applications from within Visual Studio by using just a few clicks, and provide your users with a URL pointing to your application on the Web. ClickOnce manages all the elements and dependencies in your application, and ensures that the application is correctly installed on the client computer. + +ClickOnce applications 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 application should support offline operation, ClickOnce adds a link to your application in the user's **Start** menu. The user can then open the application without using the URL. + +When you update your application, you publish a new deployment manifest and a new copy of your application 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 assemblies. + +#### Deploy ClickOnce apps + +For a full introduction to ClickOnce, see [ClickOnce Security and Deployment](/visualstudio/deployment/clickonce-security-and-deployment). For step-by-step information about how to use these features, see the following Help topics, + +|Description|Help topic| +|-----------------|----------------| +|Deploying an application by using ClickOnce|[How to: Publish a ClickOnce Application using the Publish Wizard](/visualstudio/deployment/how-to-publish-a-clickonce-application-using-the-publish-wizard)

[Walkthrough: Manually Deploying a ClickOnce Application](/visualstudio/deployment/walkthrough-manually-deploying-a-clickonce-application)| +|Updating a ClickOnce deployment|[How to: Manage Updates for a ClickOnce Application](/visualstudio/deployment/how-to-manage-updates-for-a-clickonce-application)| +|Managing security with ClickOnce|[How to: Enable ClickOnce Security Settings](/visualstudio/deployment/how-to-enable-clickonce-security-settings)| + +### Other controls and features + +There are many other features in Windows Forms that make implementing common tasks fast and easy, such as support for creating dialog boxes, printing, adding Help and documentation, and localizing your application to multiple languages. Additionally, Windows Forms relies on the robust security system of the .NET Framework. With this system, you can release more secure applications to your customers. + +#### Implement other controls and features + +For step-by-step information about how to use these features, see the following Help topics. + +|Description|Help topic| +|-----------------|----------------| +|Printing the contents of a form|[How to: Print Graphics in Windows Forms](./advanced/how-to-print-graphics-in-windows-forms.md)

[How to: Print a Multi-Page Text File in Windows Forms](./advanced/how-to-print-a-multi-page-text-file-in-windows-forms.md)| +|Learn more about Windows Forms security|[Security in Windows Forms Overview](security-in-windows-forms-overview.md)| + +## See also + +- [Getting Started with Windows Forms](getting-started-with-windows-forms.md) +- [Creating a New Windows Form](creating-a-new-windows-form.md) +- [ToolStrip Control Overview](./controls/toolstrip-control-overview-windows-forms.md) +- [DataGridView Control Overview](./controls/datagridview-control-overview-windows-forms.md) +- [BindingSource Component Overview](./controls/bindingsource-component-overview.md) +- [Application Settings Overview](./advanced/application-settings-overview.md) +- [ClickOnce Security and Deployment](/visualstudio/deployment/clickonce-security-and-deployment) diff --git a/dotnet-desktop-guide/framework/winforms/windows-forms-security.md b/dotnet-desktop-guide/framework/winforms/windows-forms-security.md new file mode 100644 index 0000000000..81e819dedf --- /dev/null +++ b/dotnet-desktop-guide/framework/winforms/windows-forms-security.md @@ -0,0 +1,55 @@ +--- +title: Security +ms.date: "03/30/2017" +helpviewer_keywords: + - "designer access security [Windows Forms]" + - "permissions [Windows Forms], Windows Forms" + - "Windows Forms, security" + - "security [Windows Forms]" + - "access control [Windows Forms], Windows Forms" + - "security policy [Windows Forms], Windows Forms" +ms.assetid: 932d438a-5285-46d8-a958-8c93d0ad6cae +--- +# Windows Forms Security +Windows Forms features a security model that is code-based (security levels are set for code, regardless of the user running the code). This is in addition to any security schemas that may be in place already on your computer system. These can include those in the browser (such as the zone-based security available in Internet Explorer) or the operating system (such as the credential-based security of Windows NT). + +## In This Section + [Security in Windows Forms Overview](security-in-windows-forms-overview.md) + Briefly explains the .NET Framework security model and the basic steps necessary to ensure the Windows Forms in your application are secure. + + [More Secure File and Data Access in Windows Forms](more-secure-file-and-data-access-in-windows-forms.md) + Describes how to access files and data in a semi-trusted environment. + + [More Secure Printing in Windows Forms](more-secure-printing-in-windows-forms.md) + Describes how to access printing features in a semi-trusted environment. + + [Additional Security Considerations in Windows Forms](additional-security-considerations-in-windows-forms.md) + Describes performing window manipulation, using the Clipboard, and making calls to unmanaged code in a semi-trusted environment. + +## Related Sections + [Default Security Policy](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/03kwzyfc(v=vs.100)) + Lists the default permissions granted in the Full Trust, Local Intranet, and Internet permission sets. + + [General Security Policy Administration](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/ed5htz45(v=vs.100)) + Gives information about the administering the .NET Framework security policy and elevating permissions. + + [Dangerous Permissions and Policy Administration](https://docs.microsoft.com/dotnet/framework/misc/dangerous-permissions-and-policy-administration) + Discusses some of the.NET Framework permissions that can potentially allow the security system to be circumvented. + + [Secure Coding Guidelines](https://docs.microsoft.com/dotnet/standard/security/secure-coding-guidelines) + Links to topics that explain the best practices for securely writing code against the .NET Framework. + + [Requesting Permissions](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/yd267cce(v=vs.100)) + Discusses the use of attributes to let the runtime know what permissions your code needs to run. + + [Key Security Concepts](https://docs.microsoft.com/dotnet/standard/security/key-security-concepts) + Links to topics that cover the basic aspects of code security. + + [Code Access Security Basics](https://docs.microsoft.com/dotnet/framework/misc/code-access-security-basics) + Discusses the basics of working with the .NET Framework run time security policy. + + [Determining When to Modify Security Policy](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/xky659fc(v=vs.100)) + Explains how to determine when your applications need to diverge from the default security policy. + + [Deploying Security Policy](https://docs.microsoft.com/previous-versions/dotnet/netframework-4.0/13wcxx6y(v=vs.100)) + Discusses the best manner for deploying security policy changes. diff --git a/dotnet-desktop-guide/index.md b/dotnet-desktop-guide/index.md index 76920b50ff..ca03792be1 100644 --- a/dotnet-desktop-guide/index.md +++ b/dotnet-desktop-guide/index.md @@ -1 +1,35 @@ -# Welcome to dotnet-desktop-guide! \ No newline at end of file +--- +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.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 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) 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. + + The documentation for this version of Windows Forms is available [here](framework/winforms/index.yml?view=netframeworkdesktop-4.8). + +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. + + The documentation for this version of Windows Forms is in progress and not yet available. + +## Windows Presentation Foundation + +The documentation for the .NET Framework implementation of WPF is still hosted in the [.NET documentation](/dotnet/framework/wpf/). It's migration is in progress. + +The documentation for the open-source implementation of WPF for .NET 5 (and .NET Core 3.1) isn't yet available. diff --git a/dotnet-desktop-guide/net/breadcrumb/toc.yml b/dotnet-desktop-guide/net/breadcrumb/toc.yml new file mode 100644 index 0000000000..13f16dae18 --- /dev/null +++ b/dotnet-desktop-guide/net/breadcrumb/toc.yml @@ -0,0 +1,18 @@ +items: +- name: Docs + tocHref: / + topicHref: / + items: + - name: .NET + tocHref: /dotnet/ + topicHref: /dotnet/index + items: + - name: Desktop Guide + tocHref: /dotnet/desktop + topicHref: /dotnet/desktop/index + items: + - name: ".NET 5 (and .NET Core 3.1)" + items: + - name: Windows Forms + tocHref: /dotnet/desktop/winforms + topicHref: /dotnet/desktop/winforms/index diff --git a/dotnet-desktop-guide/net/includes/desktop-guide-preview-note.md b/dotnet-desktop-guide/net/includes/desktop-guide-preview-note.md new file mode 100644 index 0000000000..e787a90b92 --- /dev/null +++ b/dotnet-desktop-guide/net/includes/desktop-guide-preview-note.md @@ -0,0 +1,3 @@ + +> [!IMPORTANT] +> The Desktop Guide documentation for .NET 5 (and .NET Core) and later versions is under construction and hasn't been published yet. diff --git a/dotnet-desktop-guide/net/winforms/index.md b/dotnet-desktop-guide/net/winforms/index.md new file mode 100644 index 0000000000..7cfc6cd556 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/index.md @@ -0,0 +1,31 @@ +--- +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/toc.yml b/dotnet-desktop-guide/net/winforms/toc.yml new file mode 100644 index 0000000000..634940a292 --- /dev/null +++ b/dotnet-desktop-guide/net/winforms/toc.yml @@ -0,0 +1,3 @@ +items: +- name: Windows Forms + href: index.md diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/form1.cpp new file mode 100644 index 0000000000..352da3eed0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/form1.cpp @@ -0,0 +1,258 @@ +// +#pragma region Using directives + +#using +#using +#using +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Drawing; +using namespace System::Windows::Forms; +using namespace System::Data::SqlClient; + +#pragma endregion + +namespace MaskedTextBoxDataCSharp +{ + public ref class Form1 : public Form + { + /// + /// Required designer variable. + /// + private: + System::ComponentModel::IContainer^ components; + + public: + Form1() + { + InitializeComponent(); + } + + /// + /// Clean up any resources being used. + /// + protected: + ~Form1() + { + if (components != nullptr) + { + delete components; + } + } + + + +#pragma 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() + { + employeesTable = gcnew DataSet(); + components = nullptr; + this->firstName = gcnew System::Windows::Forms::TextBox(); + this->lastName = gcnew System::Windows::Forms::TextBox(); + this->phoneMask = gcnew System::Windows::Forms::MaskedTextBox(); + this->previousButton = gcnew System::Windows::Forms::Button(); + this->nextButton = gcnew System::Windows::Forms::Button(); + this->SuspendLayout(); + // + // firstName + // + this->firstName->Location = System::Drawing::Point(13, 14); + this->firstName->Name = "firstName"; + this->firstName->Size = System::Drawing::Size(184, 20); + this->firstName->TabIndex = 0; + // + // lastName + // + this->lastName->Location = System::Drawing::Point(204, 14); + this->lastName->Name = "lastName"; + this->lastName->Size = System::Drawing::Size(184, 20); + this->lastName->TabIndex = 1; + // + // phoneMask + // + this->phoneMask->Location = System::Drawing::Point(441, 14); + this->phoneMask->Mask = "(009) 000-0000 x9999"; + this->phoneMask->Name = "phoneMask"; + this->phoneMask->Size = System::Drawing::Size(169, 20); + this->phoneMask->TabIndex = 2; + // + // previousButton + // + this->previousButton->Location = System::Drawing::Point(630, 14); + this->previousButton->Name = "previousButton"; + this->previousButton->TabIndex = 3; + this->previousButton->Text = "Previous"; + this->previousButton->Click += gcnew System::EventHandler(this,&Form1::previousButton_Click); + // + // nextButton + // + this->nextButton->Location = System::Drawing::Point(723, 14); + this->nextButton->Name = "nextButton"; + this->nextButton->TabIndex = 4; + this->nextButton->Text = "Next"; + this->nextButton->Click += gcnew System::EventHandler(this,&Form1::nextButton_Click); + // + // Form1 + // + this->AutoScaleBaseSize = System::Drawing::Size(5, 13); + this->ClientSize = System::Drawing::Size(887, 46); + this->Controls->Add(this->nextButton); + this->Controls->Add(this->previousButton); + this->Controls->Add(this->phoneMask); + this->Controls->Add(this->lastName); + this->Controls->Add(this->firstName); + this->Name = "Form1"; + this->Text = "Form1"; + this->Load += gcnew System::EventHandler(this,&Form1::Form1_Load); + this->ResumeLayout(false); + this->PerformLayout(); + } + +#pragma endregion + + private: + System::Windows::Forms::TextBox^ firstName; + System::Windows::Forms::TextBox^ lastName; + System::Windows::Forms::MaskedTextBox^ phoneMask; + System::Windows::Forms::Button^ previousButton; + System::Windows::Forms::Button^ nextButton; + + private: + Binding^ currentBinding; + Binding^ phoneBinding; + DataSet^ employeesTable; + SqlConnection^ sc; + SqlDataAdapter^ dataConnect; + + private: + void Form1_Load(Object^ sender, EventArgs^ e) + { + DoMaskBinding(); + } + + private: + void DoMaskBinding() + { + try + { + sc = gcnew SqlConnection("Data Source=localhost;" + + "Initial Catalog=NORTHWIND;Integrated Security=SSPI"); + sc->Open(); + } + catch (Exception^ ex) + { + MessageBox::Show(ex->Message); + return; + } + + dataConnect = gcnew SqlDataAdapter("SELECT * FROM Employees", sc); + dataConnect->Fill(employeesTable, "Employees"); + + + // Now bind MaskedTextBox to appropriate field. Note that we must + // create the Binding objects before adding them to the control - + // otherwise, we won't get a Format event on the initial load. + try + { + currentBinding = gcnew Binding("Text", employeesTable, + "Employees.FirstName"); + firstName->DataBindings->Add(currentBinding); + + currentBinding = gcnew Binding("Text", employeesTable, + "Employees.LastName"); + lastName->DataBindings->Add(currentBinding); + + phoneBinding = gcnew Binding("Text", employeesTable, + "Employees.HomePhone"); + // We must add the event handlers before we bind, or the + // Format event will not get called for the first record. + phoneBinding->Format += gcnew + ConvertEventHandler(this, &Form1::phoneBinding_Format); + phoneBinding->Parse += gcnew + ConvertEventHandler(this, &Form1::phoneBinding_Parse); + phoneMask->DataBindings->Add(phoneBinding); + } + catch (Exception^ ex) + { + MessageBox::Show(ex->Message); + return; + } + } + + private: + void phoneBinding_Format(Object^ sender, ConvertEventArgs^ e) + { + String^ ext; + + DataRowView^ currentRow = (DataRowView^) BindingContext[ + employeesTable, "Employees"]->Current; + if (currentRow["Extension"] == nullptr) + { + ext = ""; + } + else + { + ext = currentRow["Extension"]->ToString(); + } + + e->Value = e->Value->ToString()->Trim() + " x" + ext; + } + + private: + void phoneBinding_Parse(Object^ sender, ConvertEventArgs^ e) + { + String^ phoneNumberAndExt = e->Value->ToString(); + + int extIndex = phoneNumberAndExt->IndexOf("x"); + String^ ext = phoneNumberAndExt->Substring(extIndex)->Trim(); + String^ phoneNumber = + phoneNumberAndExt->Substring(0, extIndex)->Trim(); + + //Get the current binding object, and set the new extension + //manually. + DataRowView^ currentRow = + (DataRowView^ ) BindingContext[employeesTable, + "Employees"]->Current; + // Remove the "x" from the extension. + currentRow["Extension"] = ext->Substring(1); + + //Return the phone number. + e->Value = phoneNumber; + } + + private: + void previousButton_Click(Object^ sender, EventArgs^ e) + { + BindingContext[employeesTable, "Employees"]->Position = + BindingContext[employeesTable, "Employees"]->Position - 1; + } + + private: + void nextButton_Click(Object^ sender, EventArgs^ e) + { + BindingContext[employeesTable, "Employees"]->Position = + BindingContext[employeesTable, "Employees"]->Position + 1; + } + }; +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew MaskedTextBoxDataCSharp::Form1()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/makefile new file mode 100644 index 0000000000..702e69680a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/MaskedTextBoxData/cpp/makefile @@ -0,0 +1,2 @@ +MaskedTextBoxData.exe: form1.cpp + cl /clr:pure /Femydll.dll form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp new file mode 100644 index 0000000000..abfc2d3bd7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CPP/fibonacciform.cpp @@ -0,0 +1,310 @@ + + +// +// +#using +#using +#using + +using namespace System; +using namespace System::Collections; +using namespace System::ComponentModel; +using namespace System::Drawing; +using namespace System::Threading; +using namespace System::Windows::Forms; + +// +public ref class FibonacciForm: public System::Windows::Forms::Form +{ +private: + + // + int numberToCompute; + int highestPercentageReached; + // + + System::Windows::Forms::NumericUpDown^ numericUpDown1; + System::Windows::Forms::Button^ startAsyncButton; + System::Windows::Forms::Button^ cancelAsyncButton; + System::Windows::Forms::ProgressBar^ progressBar1; + System::Windows::Forms::Label ^ resultLabel; + System::ComponentModel::BackgroundWorker^ backgroundWorker1; + +public: + FibonacciForm() + { + InitializeComponent(); + numberToCompute = highestPercentageReached = 0; + InitializeBackgoundWorker(); + } + + +private: + + // Set up the BackgroundWorker object by + // attaching event handlers. + void InitializeBackgoundWorker() + { + backgroundWorker1->DoWork += gcnew DoWorkEventHandler( this, &FibonacciForm::backgroundWorker1_DoWork ); + backgroundWorker1->RunWorkerCompleted += gcnew RunWorkerCompletedEventHandler( this, &FibonacciForm::backgroundWorker1_RunWorkerCompleted ); + backgroundWorker1->ProgressChanged += gcnew ProgressChangedEventHandler( this, &FibonacciForm::backgroundWorker1_ProgressChanged ); + } + + // + void startAsyncButton_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + + // Reset the text in the result label. + resultLabel->Text = String::Empty; + + // Disable the UpDown control until + // the asynchronous operation is done. + this->numericUpDown1->Enabled = false; + + // Disable the Start button until + // the asynchronous operation is done. + this->startAsyncButton->Enabled = false; + + // Enable the Cancel button while + // the asynchronous operation runs. + this->cancelAsyncButton->Enabled = true; + + // Get the value from the UpDown control. + numberToCompute = (int)numericUpDown1->Value; + + // Reset the variable for percentage tracking. + highestPercentageReached = 0; + + // + // Start the asynchronous operation. + backgroundWorker1->RunWorkerAsync( numberToCompute ); + // + } + // + + // + void cancelAsyncButton_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + // Cancel the asynchronous operation. + this->backgroundWorker1->CancelAsync(); + + // Disable the Cancel button. + cancelAsyncButton->Enabled = false; + } + // + + // + // This event handler is where the actual, + // potentially time-consuming work is done. + void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e ) + { + // Get the BackgroundWorker that raised this event. + BackgroundWorker^ worker = dynamic_cast(sender); + + // Assign the result of the computation + // to the Result property of the DoWorkEventArgs + // object. This is will be available to the + // RunWorkerCompleted eventhandler. + e->Result = ComputeFibonacci( safe_cast(e->Argument), worker, e ); + } + // + + // + // This event handler deals with the results of the + // background operation. + void backgroundWorker1_RunWorkerCompleted( Object^ /*sender*/, RunWorkerCompletedEventArgs^ e ) + { + // First, handle the case where an exception was thrown. + if ( e->Error != nullptr ) + { + MessageBox::Show( e->Error->Message ); + } + else + if ( e->Cancelled ) + { + // Next, handle the case where the user cancelled + // the operation. + // Note that due to a race condition in + // the DoWork event handler, the Cancelled + // flag may not have been set, even though + // CancelAsync was called. + resultLabel->Text = "Cancelled"; + } + else + { + // Finally, handle the case where the operation + // succeeded. + resultLabel->Text = e->Result->ToString(); + } + + // Enable the UpDown control. + this->numericUpDown1->Enabled = true; + + // Enable the Start button. + startAsyncButton->Enabled = true; + + // Disable the Cancel button. + cancelAsyncButton->Enabled = false; + } + // + + // + // This event handler updates the progress bar. + void backgroundWorker1_ProgressChanged( Object^ /*sender*/, ProgressChangedEventArgs^ e ) + { + this->progressBar1->Value = e->ProgressPercentage; + } + // + + // + // This is the method that does the actual work. For this + // example, it computes a Fibonacci number and + // reports progress as it does its work. + long ComputeFibonacci( int n, BackgroundWorker^ worker, DoWorkEventArgs ^ e ) + { + // The parameter n must be >= 0 and <= 91. + // Fib(n), with n > 91, overflows a long. + if ( (n < 0) || (n > 91) ) + { + throw gcnew ArgumentException( "value must be >= 0 and <= 91","n" ); + } + + long result = 0; + + // + // Abort the operation if the user has cancelled. + // Note that a call to CancelAsync may have set + // CancellationPending to true just after the + // last invocation of this method exits, so this + // code will not have the opportunity to set the + // DoWorkEventArgs.Cancel flag to true. This means + // that RunWorkerCompletedEventArgs.Cancelled will + // not be set to true in your RunWorkerCompleted + // event handler. This is a race condition. + // + if ( worker->CancellationPending ) + { + e->Cancel = true; + } + // + else + { + if ( n < 2 ) + { + result = 1; + } + else + { + result = ComputeFibonacci( n - 1, worker, e ) + ComputeFibonacci( n - 2, worker, e ); + } + + // + // Report progress as a percentage of the total task. + int percentComplete = (int)((float)n / (float)numberToCompute * 100); + if ( percentComplete > highestPercentageReached ) + { + highestPercentageReached = percentComplete; + worker->ReportProgress( percentComplete ); + } + // + } + // + + return result; + } + // + + void InitializeComponent() + { + this->numericUpDown1 = gcnew System::Windows::Forms::NumericUpDown; + this->startAsyncButton = gcnew System::Windows::Forms::Button; + this->cancelAsyncButton = gcnew System::Windows::Forms::Button; + this->resultLabel = gcnew System::Windows::Forms::Label; + this->progressBar1 = gcnew System::Windows::Forms::ProgressBar; + this->backgroundWorker1 = gcnew System::ComponentModel::BackgroundWorker; + (dynamic_cast(this->numericUpDown1))->BeginInit(); + this->SuspendLayout(); + + // + // numericUpDown1 + // + this->numericUpDown1->Location = System::Drawing::Point( 16, 16 ); + array^temp0 = {91,0,0,0}; + this->numericUpDown1->Maximum = System::Decimal( temp0 ); + array^temp1 = {1,0,0,0}; + this->numericUpDown1->Minimum = System::Decimal( temp1 ); + this->numericUpDown1->Name = "numericUpDown1"; + this->numericUpDown1->Size = System::Drawing::Size( 80, 20 ); + this->numericUpDown1->TabIndex = 0; + array^temp2 = {1,0,0,0}; + this->numericUpDown1->Value = System::Decimal( temp2 ); + + // + // startAsyncButton + // + this->startAsyncButton->Location = System::Drawing::Point( 16, 72 ); + this->startAsyncButton->Name = "startAsyncButton"; + this->startAsyncButton->Size = System::Drawing::Size( 120, 23 ); + this->startAsyncButton->TabIndex = 1; + this->startAsyncButton->Text = "Start Async"; + this->startAsyncButton->Click += gcnew System::EventHandler( this, &FibonacciForm::startAsyncButton_Click ); + + // + // cancelAsyncButton + // + this->cancelAsyncButton->Enabled = false; + this->cancelAsyncButton->Location = System::Drawing::Point( 153, 72 ); + this->cancelAsyncButton->Name = "cancelAsyncButton"; + this->cancelAsyncButton->Size = System::Drawing::Size( 119, 23 ); + this->cancelAsyncButton->TabIndex = 2; + this->cancelAsyncButton->Text = "Cancel Async"; + this->cancelAsyncButton->Click += gcnew System::EventHandler( this, &FibonacciForm::cancelAsyncButton_Click ); + + // + // resultLabel + // + this->resultLabel->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D; + this->resultLabel->Location = System::Drawing::Point( 112, 16 ); + this->resultLabel->Name = "resultLabel"; + this->resultLabel->Size = System::Drawing::Size( 160, 23 ); + this->resultLabel->TabIndex = 3; + this->resultLabel->Text = "(no result)"; + this->resultLabel->TextAlign = System::Drawing::ContentAlignment::MiddleCenter; + + // + // progressBar1 + // + this->progressBar1->Location = System::Drawing::Point( 18, 48 ); + this->progressBar1->Name = "progressBar1"; + this->progressBar1->Size = System::Drawing::Size( 256, 8 ); + this->progressBar1->Step = 2; + this->progressBar1->TabIndex = 4; + + // + // backgroundWorker1 + // + this->backgroundWorker1->WorkerReportsProgress = true; + this->backgroundWorker1->WorkerSupportsCancellation = true; + + // + // FibonacciForm + // + this->ClientSize = System::Drawing::Size( 292, 118 ); + this->Controls->Add( this->progressBar1 ); + this->Controls->Add( this->resultLabel ); + this->Controls->Add( this->cancelAsyncButton ); + this->Controls->Add( this->startAsyncButton ); + this->Controls->Add( this->numericUpDown1 ); + this->Name = "FibonacciForm"; + this->Text = "Fibonacci Calculator"; + (dynamic_cast(this->numericUpDown1))->EndInit(); + this->ResumeLayout( false ); + } +}; + +[STAThread] +int main() +{ + Application::Run( gcnew FibonacciForm ); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/form1.cpp new file mode 100644 index 0000000000..c8562f8325 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/form1.cpp @@ -0,0 +1,165 @@ +// +// +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Drawing; +using namespace System::Text; +using namespace System::Windows::Forms; +// + +// This sample demonstrates the use of the +// DesignerSerializationVisibility attribute +// to serialize a collection of strings +// at design time. +namespace SerializationDemo +{ + + // + public ref class SerializationDemoControl : + public System::Windows::Forms::UserControl + { + // This is the TextBox contained by + // the SerializationDemoControl. + private: + System::Windows::Forms::TextBox^ demoControlTextBox; + + // + // This field backs the Strings property. + private: + array^ stringsValue; + + + // + + public: + SerializationDemoControl() + { + InitializeComponent(); + stringsValue = gcnew array(1); + } + + // + // When the DesignerSerializationVisibility attribute has + // a value of "Content" or "Visible" the designer will + // serialize the property. This property can also be edited + // at design time with a CollectionEditor. + public: + [DesignerSerializationVisibility( + DesignerSerializationVisibility::Content)] + property array^ Strings + { + array^ get() + { + return this->stringsValue; + } + void set(array^ value) + { + this->stringsValue = value; + + // Populate the contained TextBox with the values + // in the stringsValue array. + StringBuilder^ sb = + gcnew StringBuilder(this->stringsValue->Length); + + for (int i = 0; i < this->stringsValue->Length; i++) + { + sb->Append(this->stringsValue[i]); + sb->Append(Environment::NewLine); + } + + this->demoControlTextBox->Text = sb->ToString(); + } + } + // + + private: + void InitializeComponent() + { + this->demoControlTextBox = + gcnew System::Windows::Forms::TextBox(); + this->SuspendLayout(); + + // Settings for the contained TextBox control. + this->demoControlTextBox->AutoSize = false; + this->demoControlTextBox->Dock = + System::Windows::Forms::DockStyle::Fill; + this->demoControlTextBox->Location = + System::Drawing::Point(5, 5); + this->demoControlTextBox->Margin = + System::Windows::Forms::Padding(0); + this->demoControlTextBox->Multiline = true; + this->demoControlTextBox->Name = "textBox1"; + this->demoControlTextBox->ReadOnly = true; + this->demoControlTextBox->ScrollBars = ScrollBars::Vertical; + this->demoControlTextBox->Size = + System::Drawing::Size(140, 140); + this->demoControlTextBox->TabIndex = 0; + + // Settings for SerializationDemoControl. + this->Controls->Add(this->demoControlTextBox); + this->Name = "SerializationDemoControl"; + this->Padding = System::Windows::Forms::Padding(5); + this->ResumeLayout(false); + } + }; + // + + public ref class SerializationDemoForm : + public System::Windows::Forms::Form + { + + SerializationDemoControl^ serializationDemoControl; + + + public: + SerializationDemoForm() + { + InitializeComponent(); + serializationDemoControl = nullptr; + } + + // The Windows Forms Designer emits code to this method. + // If an instance of SerializationDemoControl is added + // to the form, the Strings will be serialized here. + private: + void InitializeComponent() + { + this->serializationDemoControl = + gcnew SerializationDemo::SerializationDemoControl(); + this->SuspendLayout(); + // + // serializationDemoControl + // + this->serializationDemoControl->Location = + System::Drawing::Point(0, 0); + this->serializationDemoControl->Name = + "serializationDemoControl"; + this->serializationDemoControl->Padding = + System::Windows::Forms::Padding(5); + this->serializationDemoControl->TabIndex = 0; + // + // SerializationDemoForm + // + this->AutoScaleBaseSize = System::Drawing::Size(5, 13); + this->ClientSize = System::Drawing::Size(292, 273); + this->Controls->Add(this->serializationDemoControl); + this->Name = "SerializationDemoForm"; + this->Text = "Form1"; + this->ResumeLayout(false); + + } + }; +}; + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew SerializationDemo::SerializationDemoForm()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/makefile new file mode 100644 index 0000000000..7ec05a0f1a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/cpp/makefile @@ -0,0 +1,2 @@ +System.ComponentModel.DesignerSerializationVisibilityAttribute.exe : form1.cpp + cl /W4 /clr:pure /FeSystem.ComponentModel.DesignerSerializationVisibilityAttribute.exe form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp new file mode 100644 index 0000000000..9e4f62a57a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/form1.cpp @@ -0,0 +1,180 @@ +#using +#using +#using + +using namespace System; +using namespace System::Windows::Forms; +using namespace System::Drawing; + + +public ref class Form1: public System::Windows::Forms::Form +{ +private: + void DoSomething1() + { + // Snippet for: + // \vbtskcodeexampledrawingfilledellipseonform.xml + // + System::Drawing::SolidBrush^ myBrush = + gcnew System::Drawing::SolidBrush(System::Drawing::Color::Red); + System::Drawing::Graphics^ formGraphics; + formGraphics = this->CreateGraphics(); + formGraphics->FillEllipse(myBrush, Rectangle(0, 0, 200, 300)); + delete myBrush; + delete formGraphics; + // + } + +private: + void DoSomething2() + { + // Snippet for: + // \vbtskcodeexampledrawingfilledrectangleonform.xml + // + System::Drawing::SolidBrush^ myBrush = + gcnew System::Drawing::SolidBrush(System::Drawing::Color::Red); + System::Drawing::Graphics^ formGraphics; + formGraphics = this->CreateGraphics(); + formGraphics->FillRectangle(myBrush, Rectangle(0, 0, 200, 300)); + delete myBrush; + delete formGraphics; + // + } + +private: + void DoSomething3() + { + // Snippet for: \vbtskcodeexamplecreatingpen.xml + // + System::Drawing::Pen^ myPen; + myPen = gcnew System::Drawing::Pen(System::Drawing::Color::Tomato); + // + } + +private: + void DoSomething4() + { + // Snippet for: \vbtskcodeexamplecreatingsolidbrush.xml + // + System::Drawing::SolidBrush^ myBrush; + myBrush = gcnew System::Drawing::SolidBrush( + System::Drawing::Color::PeachPuff); + // + } + +private: + void DoSomething5() + { + // Snippet for: \vbtskcodeexampledrawinglineonform.xml + // + System::Drawing::Pen^ myPen = + gcnew System::Drawing::Pen(System::Drawing::Color::Red); + System::Drawing::Graphics^ formGraphics; + formGraphics = this->CreateGraphics(); + formGraphics->DrawLine(myPen, 0, 0, 200, 200); + delete myPen; + delete formGraphics; + // + } + + // Snippet for: \vbtskcodeexampledrawingoutlinedshapes.xml + // +private: + void DrawEllipse() + { + System::Drawing::Pen^ myPen = + gcnew System::Drawing::Pen(System::Drawing::Color::Red); + System::Drawing::Graphics^ formGraphics; + formGraphics = this->CreateGraphics(); + formGraphics->DrawEllipse(myPen, Rectangle(0, 0, 200, 300)); + delete myPen; + delete formGraphics; + } + +private: + void DrawRectangle() + { + System::Drawing::Pen^ myPen = + gcnew System::Drawing::Pen(System::Drawing::Color::Red); + System::Drawing::Graphics^ formGraphics; + formGraphics = this->CreateGraphics(); + formGraphics->DrawRectangle(myPen, Rectangle(0, 0, 200, 300)); + delete myPen; + delete formGraphics; + } + + // + // Snippet for: \vbtskcodeexampledrawingtextonform2.xml + // +public: + void DrawString() + { + System::Drawing::Graphics^ formGraphics = this->CreateGraphics(); + String^ drawString = "Sample Text"; + System::Drawing::Font^ drawFont = + gcnew System::Drawing::Font("Arial", 16); + System::Drawing::SolidBrush^ drawBrush = gcnew + System::Drawing::SolidBrush(System::Drawing::Color::Black); + float x = 150.0F; + float y = 50.0F; + System::Drawing::StringFormat^ drawFormat = + gcnew System::Drawing::StringFormat(); + formGraphics->DrawString(drawString, drawFont, drawBrush, x, + y, drawFormat); + delete drawFont; + delete drawBrush; + delete formGraphics; + } + + // + // Snippet for: \vbtskcodeexampledrawingtextonform.xml + // +public: + void DrawVerticalString() + { + System::Drawing::Graphics^ formGraphics = this->CreateGraphics(); + String^ drawString = "Sample Text"; + System::Drawing::Font^ drawFont = + gcnew System::Drawing::Font("Arial", 16); + System::Drawing::SolidBrush^ drawBrush = gcnew + System::Drawing::SolidBrush(System::Drawing::Color::Black); + float x = 150.0F; + float y = 50.0F; + System::Drawing::StringFormat^ drawFormat = + gcnew System::Drawing::StringFormat(); + drawFormat->FormatFlags = StringFormatFlags::DirectionVertical; + formGraphics->DrawString(drawString, drawFont, drawBrush, x, + y, drawFormat); + delete drawFont; + delete drawBrush; + delete formGraphics; + } + + // +private: + void DoSomething9() + { + Pen^ myPen = gcnew Pen(Color::Red); + // Snippet for: \vbtskcodeexamplesetcolorofpen.xml + // + myPen->Color = System::Drawing::Color::PeachPuff; + // + } + // Snippet for: \vbtskcreateashapedwindowsform.xml + // +protected: + virtual void OnPaint( + System::Windows::Forms::PaintEventArgs^ e) override + { + System::Drawing::Drawing2D::GraphicsPath^ shape = + gcnew System::Drawing::Drawing2D::GraphicsPath(); + shape->AddEllipse(0, 0, this->Width, this->Height); + this->Region = gcnew System::Drawing::Region(shape); + } + // +}; + +int main() +{ + Application::Run(gcnew Form1()); +} diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/makefile new file mode 100644 index 0000000000..10d414038b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/cpp/makefile @@ -0,0 +1,2 @@ +System.Drawing.ConceptualHowTos.exe: form1.cpp + cl /clr:pure /FeSystem.Drawing.ConceptualHowTos.exe form1.cpp \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CPP/form1.cpp new file mode 100644 index 0000000000..02ccd8a884 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CPP/form1.cpp @@ -0,0 +1,181 @@ +// +// +#using +#using +#using + +using namespace System; +using namespace System::ComponentModel; +using namespace System::Drawing; +using namespace System::Globalization; +using namespace System::Windows::Forms; +// + +namespace DataConnectorAddingNewExample +{ + // + // This class implements a simple customer type. + public ref class DemoCustomer + { + private: + // These fields hold the values for the public properties. + Guid idValue; + String^ customerName; + String^ companyNameValue; + String^ phoneNumberValue; + + // The constructor is private to enforce the factory pattern. + DemoCustomer() + { + idValue = Guid::NewGuid(); + customerName = String::Empty; + companyNameValue = String::Empty; + phoneNumberValue = String::Empty; + customerName = "no data"; + companyNameValue = "no data"; + phoneNumberValue = "no data"; + } + + public: + // This is the public factory method. + static DemoCustomer^ CreateNewCustomer() + { + return gcnew DemoCustomer; + } + + property Guid ID + { + // This property represents an ID, suitable + // for use as a primary key in a database. + Guid get() + { + return this->idValue; + } + } + + property String^ CompanyName + { + String^ get() + { + return this->companyNameValue; + } + + void set(String^ value) + { + this->companyNameValue = value; + } + } + + property String^ PhoneNumber + { + String^ get() + { + return this->phoneNumberValue; + } + + void set(String^ value) + { + this->phoneNumberValue = value; + } + } + }; + // + + // + // This form demonstrates using a BindingSource to provide + // data from a collection of custom types + // to a DataGridView control. + public ref class MainForm: public System::Windows::Forms::Form + { + // + private: + + // This is the BindingSource that will provide data for + // the DataGridView control. + BindingSource^ customersBindingSource; + + // This is the DataGridView control + // that will display our data. + DataGridView^ customersDataGridView; + + // Set up the StatusBar for displaying ListChanged events. + StatusBar^ status; + // + + // + public: + + MainForm() + { + customersBindingSource = gcnew BindingSource; + customersDataGridView = gcnew DataGridView; + status = gcnew StatusBar; + + // Set up the form. + this->Size = System::Drawing::Size(600, 400); + this->Text = "BindingSource.AddingNew sample"; + this->Load += + gcnew EventHandler(this, &MainForm::OnMainFormLoad); + this->Controls->Add(status); + + // Set up the DataGridView control. + this->customersDataGridView->Dock = DockStyle::Fill; + this->Controls->Add(this->customersDataGridView); + + // Attach an event handler for the AddingNew event. + this->customersBindingSource->AddingNew += + gcnew AddingNewEventHandler(this, + &MainForm::OnCustomersBindingSourceAddingNew); + + // Attach an event handler for the ListChanged event. + this->customersBindingSource->ListChanged += + gcnew ListChangedEventHandler(this, + &MainForm::OnCustomersBindingSourceListChanged); + } + // + + // + private: + + void OnMainFormLoad(Object^ sender, EventArgs^ e) + { + // Add a DemoCustomer to cause a row to be displayed. + this->customersBindingSource->AddNew(); + + // Bind the BindingSource to the DataGridView + // control's DataSource. + this->customersDataGridView->DataSource = + this->customersBindingSource; + } + // + + // + // This event handler provides custom item-creation behavior. + void OnCustomersBindingSourceAddingNew(Object^ sender, + AddingNewEventArgs^ e) + { + e->NewObject = DemoCustomer::CreateNewCustomer(); + } + // + + // + // This event handler detects changes in the BindingSource + // list or changes to items within the list. + void OnCustomersBindingSourceListChanged(Object^ sender, + ListChangedEventArgs^ e) + { + status->Text = Convert::ToString(e->ListChangedType, + CultureInfo::CurrentCulture); + } + // + }; + // +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew DataConnectorAddingNewExample::MainForm); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CPP/form1.cpp new file mode 100644 index 0000000000..868db4f9f9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CPP/form1.cpp @@ -0,0 +1,136 @@ +// +// +#using +#using +#using +#using +#using +#using +#using +using namespace System; +using namespace System::Collections; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Data::Common; +using namespace System::Data::SqlClient; +using namespace System::Diagnostics; +using namespace System::Drawing; +using namespace System::Windows::Forms; +// + +// +// This form demonstrates using a BindingSource to bind to a factory +// object. +public ref class Form1: public System::Windows::Forms::Form +{ +private: + + // + // This is the TextBox for entering CustomerID values. + static TextBox^ customerIdTextBox = gcnew TextBox; + + // This is the DataGridView that displays orders for the + // specified customer. + static DataGridView^ customersDataGridView = gcnew DataGridView; + + // This is the BindingSource for binding the database query + // result set to the DataGridView. + static BindingSource^ ordersBindingSource = gcnew BindingSource; + // + +public: + // + Form1() + { + // Set up the CustomerID TextBox. + this->customerIdTextBox->Dock = DockStyle::Bottom; + this->customerIdTextBox->Text = + L"Enter a valid Northwind CustomerID, for example: ALFKI," + + L" then TAB or click outside the TextBox"; + this->customerIdTextBox->Leave += gcnew EventHandler( + this, &Form1::customerIdTextBox_Leave ); + this->Controls->Add( this->customerIdTextBox ); + + // Set up the DataGridView. + customersDataGridView->Dock = DockStyle::Top; + this->Controls->Add( customersDataGridView ); + + // Set up the form. + this->Size = System::Drawing::Size( 800, 800 ); + this->Load += gcnew EventHandler( this, &Form1::Form1_Load ); + } + // + +private: + // + // This event handler binds the BindingSource to the DataGridView + // control's DataSource property. + void Form1_Load( + System::Object^ /*sender*/, + System::EventArgs^ /*e*/ ) + { + // Attach the BindingSource to the DataGridView. + this->customersDataGridView->DataSource = + this->ordersBindingSource; + } + // + +public: + // + // This is a static factory method. It queries the Northwind + // database for the orders belonging to the specified + // customer and returns an IList. + static System::Collections::IList^ GetOrdersByCustomerId( String^ id ) + { + // Open a connection to the database. + String^ connectString = L"Integrated Security=SSPI;" + L"Persist Security Info=False;Initial Catalog=Northwind;" + L"Data Source= localhost"; + SqlConnection^ connection = gcnew SqlConnection; + connection->ConnectionString = connectString; + connection->Open(); + + // Execute the query. + String^ queryString = String::Format( + L"Select * From Orders where CustomerID = '{0}'", id ); + SqlCommand^ command = gcnew SqlCommand( queryString,connection ); + SqlDataReader^ reader = command->ExecuteReader( + CommandBehavior::CloseConnection ); + + // Build an IList from the result set. + List< DbDataRecord^ >^ list = gcnew List< DbDataRecord^ >; + System::Collections::IEnumerator^ e = reader->GetEnumerator(); + while ( e->MoveNext() ) + { + list->Add( dynamic_cast(e->Current) ); + } + + return list; + } + // + + // + // This event handler is called when the user tabs or clicks + // out of the customerIdTextBox. The database is then queried + // with the CustomerID in the customerIdTextBox.Text property. +private: + void customerIdTextBox_Leave( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + // Attach the data source to the BindingSource control. + this->ordersBindingSource->DataSource = GetOrdersByCustomerId( + this->customerIdTextBox->Text ); + } + // + +public: + [STAThread] + static void main() + { + Application::EnableVisualStyles(); + Application::Run( gcnew Form1 ); + } +}; +// +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CPP/form1.cpp new file mode 100644 index 0000000000..a53ef06ab0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CPP/form1.cpp @@ -0,0 +1,169 @@ +// +#using +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Drawing; +using namespace System::Text; +using namespace System::Xml; +using namespace System::Windows::Forms; +using namespace System::IO; + +namespace System_Windows_Forms_UpdateBinding +{ + public ref class Form1: public Form + { + public: + Form1() + { + InitializeComponent(); + } + + [STAThread] + static void Main() + { + Application::EnableVisualStyles(); + Application::Run( gcnew Form1 ); + } + + // + private: + void Form1_Load( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + // The xml to bind to. + String^ xml = "" + + "WashingtonOlympia" + + "OregonSalem" + + "CaliforniaSacramento" + + "NevadaCarson City" + + ""; + + // Convert the xml string to bytes and load into a memory stream. + array^ xmlBytes = Encoding::UTF8->GetBytes( xml ); + MemoryStream^ stream = gcnew MemoryStream( xmlBytes,false ); + + // Create a DataSet and load the xml into it. + dataSet1->ReadXml( stream ); + + // Set the DataSource to the DataSet, and the DataMember + // to state. + bindingSource1->DataSource = dataSet1; + bindingSource1->DataMember = "state"; + + dataGridView1->DataSource = bindingSource1; + } + // + + // + private: + void button1_Click( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + String^ xml = "" + + "WashingtonOlympia " + + "Coast Rhododendron" + + "OregonSalem" + + "Oregon Grape" + + "CaliforniaSacramento" + + "California Poppy" + + "NevadaCarson City" + + "Sagebrush" + + ""; + + // Convert the xml string to bytes and load into a memory stream. + array^ xmlBytes = Encoding::UTF8->GetBytes( xml ); + MemoryStream^ stream = gcnew MemoryStream( xmlBytes,false ); + + // Create a DataSet and load the xml into it. + dataSet2->ReadXml( stream ); + + // Set the data source. + bindingSource1->DataSource = dataSet2; + bindingSource1->ResetBindings( true ); + } + // + + System::Windows::Forms::Button^ button1; + System::Windows::Forms::DataGridView^ dataGridView1; + System::Windows::Forms::BindingSource^ bindingSource1; + System::Data::DataSet^ dataSet1; + DataSet^ dataSet2; + + #pragma region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + void InitializeComponent() + { + this->button1 = gcnew System::Windows::Forms::Button; + this->dataGridView1 = gcnew System::Windows::Forms::DataGridView; + this->bindingSource1 = gcnew System::Windows::Forms::BindingSource; + this->dataSet1 = gcnew System::Data::DataSet; + this->dataSet2 = gcnew System::Data::DataSet; + ( (System::ComponentModel::ISupportInitialize^)(this->dataGridView1) )->BeginInit(); + ( (System::ComponentModel::ISupportInitialize^)(this->bindingSource1) )->BeginInit(); + ( (System::ComponentModel::ISupportInitialize^)(this->dataSet1) )->BeginInit(); + ( (System::ComponentModel::ISupportInitialize^)(this->dataSet2) )->BeginInit(); + this->SuspendLayout(); + + // + // button1 + // + this->button1->Location = System::Drawing::Point( 98, 222 ); + this->button1->Name = "button1"; + this->button1->TabIndex = 0; + this->button1->Text = "button1"; + this->button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click ); + + // + // dataGridView1 + // + this->dataGridView1->Dock = System::Windows::Forms::DockStyle::Top; + this->dataGridView1->Location = System::Drawing::Point( 0, 0 ); + this->dataGridView1->Name = "dataGridView1"; + this->dataGridView1->Size = System::Drawing::Size( 292, 150 ); + this->dataGridView1->TabIndex = 1; + + // + // dataSet1 + // + this->dataSet1->DataSetName = "NewDataSet"; + this->dataSet1->Locale = gcnew System::Globalization::CultureInfo( "en-US" ); + + // + // dataSet2 + // + this->dataSet2->DataSetName = "NewDataSet"; + this->dataSet2->Locale = gcnew System::Globalization::CultureInfo( "en-US" ); + + // + // Form1 + // + this->ClientSize = System::Drawing::Size( 292, 273 ); + this->Controls->Add( this->dataGridView1 ); + this->Controls->Add( this->button1 ); + this->Name = "Form1"; + this->Text = "Form1"; + this->Load += gcnew EventHandler( this, &Form1::Form1_Load ); + ( (System::ComponentModel::ISupportInitialize^)(this->dataGridView1) )->EndInit(); + ( (System::ComponentModel::ISupportInitialize^)(this->bindingSource1) )->EndInit(); + ( (System::ComponentModel::ISupportInitialize^)(this->dataSet1) )->EndInit(); + ( (System::ComponentModel::ISupportInitialize^)(this->dataSet2) )->EndInit(); + this->ResumeLayout( false ); + } + #pragma endregion + }; +} + +int main() +{ + System_Windows_Forms_UpdateBinding::Form1::Main(); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CPP/form1.cpp new file mode 100644 index 0000000000..ef99ada33f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CPP/form1.cpp @@ -0,0 +1,178 @@ +// +// +#using +#using +#using +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Data::Common; +using namespace System::Data::SqlClient; +using namespace System::Diagnostics; +using namespace System::Drawing; +using namespace System::Windows::Forms; +// + +// +// This class implements a simple customer type. +public ref class DemoCustomer +{ +private: + // These fields hold the values for the public properties. + Guid idValue; + String^ customerName; + String^ companyNameValue; + String^ phoneNumberValue; + + // The constructor is private to enforce the factory pattern. + DemoCustomer() + { + idValue = Guid::NewGuid(); + customerName = L"no data"; + companyNameValue = L"no data"; + phoneNumberValue = L"no data"; + } + +public: + // This is the public factory method. + static DemoCustomer^ CreateNewCustomer() + { + return gcnew DemoCustomer; + } + + property Guid ID + { + // This property represents an ID, suitable + // for use as a primary key in a database. + Guid get() + { + return this->idValue; + } + } + + property String^ CompanyName + { + String^ get() + { + return this->companyNameValue; + } + + void set( String^ value ) + { + this->companyNameValue = value; + } + } + + property String^ PhoneNumber + { + String^ get() + { + return this->phoneNumberValue; + } + + void set( String^ value ) + { + this->phoneNumberValue = value; + } + } +}; +// + +// +// This form demonstrates using a BindingSource to bind +// a list to a DataGridView control. The list does not +// raise change notifications, so the ResetItem method +// on the BindingSource is used. +public ref class Form1: public System::Windows::Forms::Form +{ +private: + // + // This button causes the value of a list element to be changed. + Button^ changeItemBtn; + + // This is the DataGridView control that displays the contents + // of the list. + DataGridView^ customersDataGridView; + + // This is the BindingSource used to bind the list to the + // DataGridView control. + BindingSource^ customersBindingSource; + // + +public: + // + Form1() + { + changeItemBtn = gcnew Button; + customersDataGridView = gcnew DataGridView; + customersBindingSource = gcnew BindingSource; + + // Set up the "Change Item" button. + this->changeItemBtn->Text = L"Change Item"; + this->changeItemBtn->Dock = DockStyle::Bottom; + this->changeItemBtn->Click += gcnew EventHandler( + this, &Form1::changeItemBtn_Click ); + this->Controls->Add( this->changeItemBtn ); + + // Set up the DataGridView. + customersDataGridView->Dock = DockStyle::Top; + this->Controls->Add( customersDataGridView ); + this->Size = System::Drawing::Size( 800, 200 ); + this->Load += gcnew EventHandler( this, &Form1::Form1_Load ); + } + // + +private: + // + void Form1_Load( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + // Create and populate the list of DemoCustomer objects + // which will supply data to the DataGridView. + List< DemoCustomer^ >^ customerList = gcnew List< DemoCustomer^ >; + customerList->Add( DemoCustomer::CreateNewCustomer() ); + customerList->Add( DemoCustomer::CreateNewCustomer() ); + customerList->Add( DemoCustomer::CreateNewCustomer() ); + + // Bind the list to the BindingSource. + this->customersBindingSource->DataSource = customerList; + + // Attach the BindingSource to the DataGridView. + this->customersDataGridView->DataSource = + this->customersBindingSource; + } + // + + // + // This event handler changes the value of the CompanyName + // property for the first item in the list. + void changeItemBtn_Click( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + // Get a reference to the list from the BindingSource. + List< DemoCustomer^ >^ customerList = + static_cast^>( + this->customersBindingSource->DataSource); + + // Change the value of the CompanyName property for the + // first item in the list. + customerList->default[ 0 ]->CompanyName = L"Tailspin Toys"; + + // Call ResetItem to alert the BindingSource that the + // list has changed. + this->customersBindingSource->ResetItem( 0 ); + } + // +}; + +int main() +{ + Application::EnableVisualStyles(); + Application::Run( gcnew Form1 ); +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CPP/form1.cpp new file mode 100644 index 0000000000..70a8c181d3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CPP/form1.cpp @@ -0,0 +1,215 @@ +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; +using namespace System::Globalization; + +namespace DataConnectorBindingCompleteExample +{ + // + // + // Represents a business object that throws exceptions when + // invalid values are entered for some of its properties. + public ref class Part + { + private: + String^ name; + int number; + double price; + + public: + Part(String^ name, int number, double price) + { + PartName = name; + PartNumber = number; + PartPrice = price; + } + + property String^ PartName + { + String^ get() + { + return name; + } + + void set(String^ value) + { + if (value->Length <= 0) + { + throw gcnew Exception( + "Each part must have a name."); + } + else + { + name = value; + } + } + } + + property double PartPrice + { + double get() + { + return price; + } + + void set(double value) + { + price = value; + } + } + + property int PartNumber + { + int get() + { + return number; + } + + void set(int value) + { + if (value < 100) + { + throw gcnew Exception( + "Invalid part number." \ + "Part numbers must be " \ + "greater than 100."); + } + else + { + number = value; + } + } + } + + }; + + ref class MainForm: public Form + { + private: + BindingSource^ bindingSource; + TextBox^ partNameTextBox; + TextBox^ partNumberTextBox; + TextBox^ partPriceTextBox; + + public: + MainForm() + { + bindingSource = gcnew BindingSource; + partNameTextBox = gcnew TextBox; + partNumberTextBox = gcnew TextBox; + partPriceTextBox = gcnew TextBox; + + //Set up the textbox controls. + this->partNameTextBox->Location = Point(82, 13); + this->partNameTextBox->TabIndex = 1; + this->partNumberTextBox->Location = Point(81, 47); + this->partNumberTextBox->TabIndex = 2; + this->partPriceTextBox->Location = Point(81, 83); + this->partPriceTextBox->TabIndex = 3; + + // Add the textbox controls to the form + this->Controls->Add(this->partNumberTextBox); + this->Controls->Add(this->partNameTextBox); + this->Controls->Add(this->partPriceTextBox); + + // Handle the form's Load event. + this->Load += gcnew EventHandler(this, + &MainForm::OnMainFormLoad); + } + + private: + + // + void OnMainFormLoad(Object^ sender, EventArgs^ e) + { + // Set the DataSource of bindingSource to the Part type. + bindingSource->DataSource = Part::typeid; + + // Bind the textboxes to the properties of the Part type, + // enabling formatting. + partNameTextBox->DataBindings->Add( + "Text", bindingSource, "PartName", true); + partNumberTextBox->DataBindings->Add( + "Text", bindingSource, "PartNumber", true); + + //Bind the textbox to the PartPrice value + // with currency formatting. + partPriceTextBox->DataBindings->Add("Text", bindingSource, "PartPrice", true, + DataSourceUpdateMode::OnPropertyChanged, nullptr, "C"); + + // Handle the BindingComplete event for bindingSource and + // the partNameBinding. + bindingSource->BindingComplete += + gcnew BindingCompleteEventHandler(this, + &MainForm::OnBindingSourceBindingComplete); + bindingSource->BindingComplete += + gcnew BindingCompleteEventHandler(this, + &MainForm::OnPartNameBindingBindingComplete); + + // Add a new part to bindingSource. + bindingSource->Add(gcnew Part("Widget", 1234, 12.45)); + } + + // Handle the BindingComplete event to catch errors and + // exceptions in binding process. + void OnBindingSourceBindingComplete(Object^ sender, + BindingCompleteEventArgs^ e) + { + if (e->BindingCompleteState == + BindingCompleteState::Exception) + { + MessageBox::Show(String::Format( + CultureInfo::CurrentCulture, + "bindingSource: {0}", e->Exception->Message)); + } + + if (e->BindingCompleteState == + BindingCompleteState::DataError) + { + MessageBox::Show(String::Format( + CultureInfo::CurrentCulture, + "bindingSource: {0}", e->Exception->Message)); + } + } + + // Handle the BindingComplete event to catch errors and + // exceptions in binding process. + void OnPartNameBindingBindingComplete(Object^ sender, + BindingCompleteEventArgs^ e) + { + if (e->BindingCompleteState == + BindingCompleteState::Exception) + { + MessageBox::Show(String::Format( + CultureInfo::CurrentCulture, + "PartNameBinding: {0}", e->Exception->Message)); + } + + if (e->BindingCompleteState == + BindingCompleteState::DataError) + { + MessageBox::Show(String::Format( + CultureInfo::CurrentCulture, + "PartNameBinding: {0}", e->Exception->Message)); + } + } + // + }; + +// +// +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew + DataConnectorBindingCompleteExample::MainForm()); +} + + diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp new file mode 100644 index 0000000000..28e2c43d35 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CPP/form1.cpp @@ -0,0 +1,248 @@ + +// +#using +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +namespace BindToWebService { + +// + [System::SerializableAttribute, System::Xml::Serialization::XmlTypeAttribute( + Namespace="http://webservices.eraserver.net/")] + public ref class USPSAddress + { + +private: + String^ streetField; + + String^ cityField; + + String^ stateField; + + String^ shortZIPField; + + String^ fullZIPField; + + +public: + property String^ Street + { + String^ get() + { + return this->streetField; + } + void set( String^ value ) + { + this->streetField = value; + } + } + + + property String^ City + { + String^ get() + { + return this->cityField; + } + void set( String^ value ) + { + this->cityField = value; + } + } + property String^ State + { + String^ get() + { + return this->stateField; + } + void set( String^ value ) + { + this->stateField = value; + } + } + + property String^ ShortZIP + { + String^ get() + { + return this->shortZIPField; + } + void set( String^ value ) + { + this->shortZIPField = value; + } + } + + property String^ FullZIP + { + String^ get() + { + return this->fullZIPField; + } + void set( String^ value ) + { + this->fullZIPField = value; + } + } + }; +// + + + [System::Web::Services::WebServiceBindingAttribute(Name="ZipCodeResolverSoap", + Namespace="http://webservices.eraserver.net/")] + public ref class ZipCodeResolver: + public System::Web::Services::Protocols::SoapHttpClientProtocol + + { + +public: + ZipCodeResolver() : SoapHttpClientProtocol() + { + this->Url = + "http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx"; + } + + + //'' + [System::Web::Services::Protocols::SoapDocumentMethodAttribute + ("http://webservices.eraserver.net/CorrectedAddressXml", + RequestNamespace="http://webservices.eraserver.net/", + ResponseNamespace="http://webservices.eraserver.net/", + Use=System::Web::Services::Description::SoapBindingUse::Literal, + ParameterStyle=System::Web::Services::Protocols::SoapParameterStyle::Wrapped)] + USPSAddress^ CorrectedAddressXml(String^ accessCode, + String^ address, String^ city, String^ state) + { + array^ results = this->Invoke("CorrectedAddressXml", + gcnew array{accessCode, address, city, state}); + return ((USPSAddress^) results[0]); + } + + //'' + System::IAsyncResult^ BeginCorrectedAddressXml(String^ accessCode, + String^ address, String^ city, String^ state, + System::AsyncCallback^ callback, Object^ asyncState) + { + + return this->BeginInvoke("CorrectedAddressXml", + gcnew array{accessCode, address, city, state}, callback, asyncState); + } + + + USPSAddress^ EndCorrectedAddressXml(System::IAsyncResult^ asyncResult) + { + array^ results = this->EndInvoke(asyncResult); + return ((USPSAddress^) results[0]); + } + + }; + + ref class Form1: public Form + { +public: + [STAThread] + static void Main() + { + Application::EnableVisualStyles(); + Application::Run(gcnew Form1()); + } + +private: + BindingSource^ BindingSource1; + + TextBox^ textBox1; + + TextBox^ textBox2; + + Button^ button1; + + +public: + Form1() + { + this->Load += gcnew EventHandler(this, &Form1::Form1_Load); + textBox1->Location = System::Drawing::Point(118, 131); + textBox1->ReadOnly = true; + button1->Location = System::Drawing::Point(133, 60); + button1->Click += gcnew EventHandler(this, &Form1::button1_Click); + button1->Text = "Get zipcode"; + ClientSize = System::Drawing::Size(292, 266); + Controls->Add(this->button1); + Controls->Add(this->textBox1); + BindingSource1 = gcnew BindingSource(); + textBox1 = gcnew TextBox(); + textBox2 = gcnew TextBox(); + button1 = gcnew Button(); + } + +private: + void button1_Click(Object^ sender, EventArgs^ e) + { + textBox1->Text = "Calling Web service.."; + ZipCodeResolver^ resolver = gcnew ZipCodeResolver(); + BindingSource1->Add(resolver->CorrectedAddressXml("0", + "One Microsoft Way", "Redmond", "WA")); + + } + +public: + void Form1_Load(Object^ sender, EventArgs^ e) + { + // + BindingSource1->DataSource = USPSAddress::typeid; + // + // + textBox1->DataBindings->Add("Text", this->BindingSource1, "FullZIP", true); + // + } + }; + + + + + public ref class CorrectedAddressXmlCompletedEventArgs: + public System::ComponentModel::AsyncCompletedEventArgs + + { +private: + array^ results; + +internal: + CorrectedAddressXmlCompletedEventArgs(array^ results, + System::Exception^ exception, bool cancelled, Object^ userState) : + AsyncCompletedEventArgs(exception, cancelled, userState) + { + this->results = results; + } + + +public: + property USPSAddress^ Result + { + USPSAddress^ get() + { + this->RaiseExceptionIfNecessary(); + return ((USPSAddress^) this->results[0]); + } + } + + delegate void CorrectedAddressXmlCompletedEventHandler(Object^ sender, + CorrectedAddressXmlCompletedEventArgs^ args); + + }; +} + +int main() +{ + BindToWebService::Form1::Main(); + return 1; +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CPP/autosizing.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CPP/autosizing.cpp new file mode 100644 index 0000000000..22dec58989 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CPP/autosizing.cpp @@ -0,0 +1,303 @@ + + +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Collections; +using namespace System::ComponentModel; +using namespace System::Windows::Forms; +public ref class AutoSizing: public System::Windows::Forms::Form +{ +private: + FlowLayoutPanel^ flowLayoutPanel1; + Button^ button1; + Button^ button2; + Button^ button3; + Button^ button4; + Button^ button5; + Button^ button6; + Button^ button7; + Button^ button8; + Button^ button9; + Button^ button10; + Button^ button11; + +public: + AutoSizing() + { + button1 = gcnew Button; + button2 = gcnew Button; + button3 = gcnew Button; + button4 = gcnew Button; + button5 = gcnew Button; + button6 = gcnew Button; + button7 = gcnew Button; + button8 = gcnew Button; + button9 = gcnew Button; + button10 = gcnew Button; + button11 = gcnew Button; + thirdColumnHeader = "Main Ingredients"; + boringMeatloaf = "ground beef"; + boringMeatloafRanking = "*"; + otherRestaurant = "Gomes's Saharan Sushi"; + currentLayoutName = "DataGridView.AutoSizeRowsMode is currently: "; + InitializeComponent(); + this->Load += gcnew EventHandler( this, &AutoSizing::InitializeDataGridView ); + AddDirections(); + AddButton( button1, "Reset", gcnew EventHandler( this, &AutoSizing::ResetToDisorder ) ); + AddButton( button2, "Change Column 3 Header", gcnew EventHandler( this, &AutoSizing::ChangeColumn3Header ) ); + AddButton( button3, "Change Meatloaf Recipe", gcnew EventHandler( this, &AutoSizing::ChangeMeatloafRecipe ) ); + AddButton( button4, "Change Restaurant 2", gcnew EventHandler( this, &AutoSizing::ChangeRestaurant ) ); + AddButtonsForAutomaticResizing(); + } + + +private: + void AddDirections() + { + Label^ directions = gcnew Label; + directions->AutoSize = true; + String^ newLine = Environment::NewLine; + directions->Text = String::Format( "Press the buttons that start {0}with 'Change' to see how different sizing {1}modes deal with content changes.", newLine, newLine ); + flowLayoutPanel1->Controls->Add( directions ); + } + + void InitializeComponent() + { + flowLayoutPanel1 = gcnew FlowLayoutPanel; + flowLayoutPanel1->FlowDirection = FlowDirection::TopDown; + flowLayoutPanel1->Location = System::Drawing::Point( 492, 0 ); + flowLayoutPanel1->AutoSize = true; + flowLayoutPanel1->TabIndex = 1; + ClientSize = System::Drawing::Size( 674, 419 ); + Controls->Add( flowLayoutPanel1 ); + Text = this->GetType()->Name; + AutoSize = true; + } + + System::Drawing::Size startingSize; + String^ thirdColumnHeader; + String^ boringMeatloaf; + String^ boringMeatloafRanking; + bool boringRecipe; + bool shortMode; + DataGridView^ dataGridView1; + String^ otherRestaurant; + void InitializeDataGridView( Object^ /*ignored*/, EventArgs^ /*ignoredToo*/ ) + { + dataGridView1 = gcnew System::Windows::Forms::DataGridView; + Controls->Add( dataGridView1 ); + startingSize = System::Drawing::Size( 450, 400 ); + dataGridView1->Size = startingSize; + dataGridView1->AutoSizeRowsModeChanged += gcnew DataGridViewAutoSizeModeEventHandler( this, &AutoSizing::WatchRowsModeChanges ); + AddLabels(); + SetUpColumns(); + PopulateRows(); + shortMode = false; + boringRecipe = true; + } + + void SetUpColumns() + { + dataGridView1->ColumnCount = 4; + dataGridView1->ColumnHeadersVisible = true; + DataGridViewCellStyle ^ columnHeaderStyle = gcnew DataGridViewCellStyle; + columnHeaderStyle->BackColor = Color::Aqua; + columnHeaderStyle->Font = gcnew System::Drawing::Font( "Verdana",10,FontStyle::Bold ); + dataGridView1->ColumnHeadersDefaultCellStyle = columnHeaderStyle; + dataGridView1->Columns[ 0 ]->Name = "Recipe"; + dataGridView1->Columns[ 1 ]->Name = "Category"; + dataGridView1->Columns[ 2 ]->Name = thirdColumnHeader; + dataGridView1->Columns[ 3 ]->Name = "Rating"; + } + + void PopulateRows() + { + array^row1 = {"Meatloaf","Main Dish",boringMeatloaf,boringMeatloafRanking}; + array^row2 = {"Key Lime Pie","Dessert","lime juice, evaporated milk","****"}; + array^row3 = {"Orange-Salsa Pork Chops","Main Dish","pork chops, salsa, orange juice","****"}; + array^row4 = {"Black Bean and Rice Salad","Salad","black beans, brown rice","****"}; + array^row5 = {"Chocolate Cheesecake","Dessert","cream cheese","***"}; + array^row6 = {"Black Bean Dip","Appetizer","black beans, sour cream","***"}; + array^rows = {row1,row2,row3,row4,row5,row6}; + IEnumerator^ myEnum = rows->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + array^row = safe_cast^>(myEnum->Current); + dataGridView1->Rows->Add( row ); + } + + IEnumerator^ myEnum1 = safe_cast(dataGridView1->Rows)->GetEnumerator(); + while ( myEnum1->MoveNext() ) + { + DataGridViewRow ^ row = safe_cast(myEnum1->Current); + if ( row->IsNewRow ) + break; + row->HeaderCell->Value = String::Format( "Restaurant {0}", row->Index ); + } + } + + void AddButton( Button^ button, String^ buttonLabel, EventHandler^ handler ) + { + button->Click += handler; + button->Text = buttonLabel; + button->AutoSize = true; + button->TabIndex = flowLayoutPanel1->Controls->Count; + flowLayoutPanel1->Controls->Add( button ); + } + + void ResetToDisorder( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + Controls->Remove( dataGridView1 ); + dataGridView1->DataGridView::~DataGridView(); + InitializeDataGridView( nullptr, nullptr ); + } + + void ChangeColumn3Header( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + Toggle( &shortMode ); + if ( shortMode ) + dataGridView1->Columns[ 2 ]->HeaderText = "S"; + else + dataGridView1->Columns[ 2 ]->HeaderText = thirdColumnHeader; + } + + Boolean Toggle( interior_ptr toggleThis ) + { + *toggleThis = ! *toggleThis; + return *toggleThis; + } + + void ChangeMeatloafRecipe( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + Toggle( &boringRecipe ); + if ( boringRecipe ) + SetMeatloaf( boringMeatloaf, boringMeatloafRanking ); + else + { + String^ greatMeatloafRecipe = "1 lb. lean ground beef, " + "1/2 cup bread crumbs, 1/4 cup ketchup," + "1/3 tsp onion powder, " + "1 clove of garlic, 1/2 pack onion soup mix," + " dash of your favorite BBQ Sauce"; + SetMeatloaf( greatMeatloafRecipe, "***" ); + } + } + + void ChangeRestaurant( Object^ /*sender*/, EventArgs^ /*ignored*/ ) + { + if ( dataGridView1->Rows[ 2 ]->HeaderCell->Value->ToString()->Equals( otherRestaurant ) ) + dataGridView1->Rows[ 2 ]->HeaderCell->Value = "Restaurant 2"; + else + dataGridView1->Rows[ 2 ]->HeaderCell->Value = otherRestaurant; + } + + void SetMeatloaf( String^ recipe, String^ rating ) + { + dataGridView1->Rows[ 0 ]->Cells[ 2 ]->Value = recipe; + dataGridView1->Rows[ 0 ]->Cells[ 3 ]->Value = rating; + } + + String^ currentLayoutName; + void AddLabels() + { + Label^ current = dynamic_cast(flowLayoutPanel1->Controls[ currentLayoutName ]); + if ( current == nullptr ) + { + current = gcnew Label; + current->AutoSize = true; + current->Name = currentLayoutName; + current->Text = String::Concat( currentLayoutName, dataGridView1->AutoSizeRowsMode ); + flowLayoutPanel1->Controls->Add( current ); + } + } + + void AddButtonsForAutomaticResizing() + { + AddButton( button5, "Keep Column Headers Sized", gcnew EventHandler( this, &AutoSizing::ColumnHeadersHeightSizeMode ) ); + AddButton( button6, "Keep Row Headers Sized", gcnew EventHandler( this, &AutoSizing::RowHeadersWidthSizeMode ) ); + AddButton( button7, "Keep Rows Sized", gcnew EventHandler( this, &AutoSizing::AutoSizeRowsMode ) ); + AddButton( button8, "Keep Row Headers Sized with RowsMode", gcnew EventHandler( this, &AutoSizing::AutoSizeRowHeadersUsingAllHeadersMode ) ); + AddButton( button9, "Disable AutoSizeRowsMode", gcnew EventHandler( this, &AutoSizing::DisableAutoSizeRowsMode ) ); + AddButton( button10, "AutoSize third column by rows", gcnew EventHandler( this, &AutoSizing::AutoSizeOneColumn ) ); + AddButton( button11, "AutoSize third column by rows and headers", gcnew EventHandler( this, &AutoSizing::AutoSizeOneColumnIncludingHeaders ) ); + } + + + // + void ColumnHeadersHeightSizeMode( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode::AutoSize; + } + // + // + void RowHeadersWidthSizeMode( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders; + } + + // + // + void AutoSizeRowsMode( Object^ /*sender*/, EventArgs^ /*es*/ ) + { + dataGridView1->AutoSizeRowsMode = DataGridViewAutoSizeRowsMode::AllCells; + } + // + void AutoSizeRowHeadersUsingAllHeadersMode( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + dataGridView1->AutoSizeRowsMode = DataGridViewAutoSizeRowsMode::AllHeaders; + } + + + // + void WatchRowsModeChanges( Object^ /*sender*/, DataGridViewAutoSizeModeEventArgs^ modeEvent ) + { + Label^ label = dynamic_cast(flowLayoutPanel1->Controls[ currentLayoutName ]); + if ( modeEvent->PreviousModeAutoSized ) + { + label->Text = String::Format( "changed to a different {0}{1}", label->Name, dataGridView1->AutoSizeRowsMode ); + } + else + { + label->Text = String::Concat( label->Name, dataGridView1->AutoSizeRowsMode ); + } + } + + + // + void DisableAutoSizeRowsMode( Object^ /*sender*/, EventArgs^ /*modeEvent*/ ) + { + dataGridView1->AutoSizeRowsMode = DataGridViewAutoSizeRowsMode::None; + } + + + // + void AutoSizeOneColumn( Object^ /*sender*/, EventArgs^ /*theEvent*/ ) + { + DataGridViewColumn^ column = dataGridView1->Columns[ 2 ]; + column->AutoSizeMode = DataGridViewAutoSizeColumnMode::DisplayedCellsExceptHeader; + } + + + // + void AutoSizeOneColumnIncludingHeaders( Object^ /*sender*/, EventArgs^ /*theEvent*/ ) + { + DataGridViewColumn^ column = dataGridView1->Columns[ 2 ]; + column->AutoSizeMode = DataGridViewAutoSizeColumnMode::AllCells; + } + +}; + + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run( gcnew AutoSizing ); +} + +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewBandDemo.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewBandDemo.cpp new file mode 100644 index 0000000000..346456ec48 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewBandDemo.cpp @@ -0,0 +1,328 @@ + +// +#using +#using +#using +#using + +using namespace System::Drawing; +using namespace System::Windows::Forms; +using namespace System; +using namespace System::Collections; +public ref class DataGridViewBandDemo: public Form +{ +private: + +#pragma region S " form setup " + +public: + DataGridViewBandDemo() + { + Button1 = gcnew Button; + Button2 = gcnew Button; + Button3 = gcnew Button; + Button4 = gcnew Button; + Button5 = gcnew Button; + Button6 = gcnew Button; + Button7 = gcnew Button; + Button8 = gcnew Button; + Button9 = gcnew Button; + Button10 = gcnew Button; + FlowLayoutPanel1 = gcnew FlowLayoutPanel; + InitializeComponent(); + thirdColumnHeader = L"Main Ingredients"; + boringMeatloaf = L"ground beef"; + boringMeatloafRanking = L"*"; + AddButton( Button1, L"Reset", gcnew EventHandler( this, &DataGridViewBandDemo::Button1_Click ) ); + AddButton( Button2, L"Change Column 3 Header", gcnew EventHandler( this, &DataGridViewBandDemo::Button2_Click ) ); + AddButton( Button3, L"Change Meatloaf Recipe", gcnew EventHandler( this, &DataGridViewBandDemo::Button3_Click ) ); + AddAdditionalButtons(); + InitializeDataGridView(); + } + + DataGridView^ dataGridView; + Button^ Button1; + Button^ Button2; + Button^ Button3; + Button^ Button4; + Button^ Button5; + Button^ Button6; + Button^ Button7; + Button^ Button8; + Button^ Button9; + Button^ Button10; + FlowLayoutPanel^ FlowLayoutPanel1; + +private: + void InitializeComponent() + { + FlowLayoutPanel1->Location = Point(454,0); + FlowLayoutPanel1->AutoSize = true; + FlowLayoutPanel1->FlowDirection = FlowDirection::TopDown; + AutoSize = true; + ClientSize = System::Drawing::Size( 614, 360 ); + FlowLayoutPanel1->Name = L"flowlayoutpanel"; + Controls->Add( this->FlowLayoutPanel1 ); + Text = this->GetType()->Name; + } + + +#pragma endregion +#pragma region S " setup DataGridView " + String^ thirdColumnHeader; + String^ boringMeatloaf; + String^ boringMeatloafRanking; + bool boringRecipe; + Boolean shortMode; + void InitializeDataGridView() + { + dataGridView = gcnew System::Windows::Forms::DataGridView; + Controls->Add( dataGridView ); + dataGridView->Size = System::Drawing::Size( 300, 200 ); + + // Create an unbound DataGridView by declaring a + // column count. + dataGridView->ColumnCount = 4; + AdjustDataGridViewSizing(); + + // Set the column header style. + DataGridViewCellStyle^ columnHeaderStyle = gcnew DataGridViewCellStyle; + columnHeaderStyle->BackColor = Color::Aqua; + columnHeaderStyle->Font = gcnew System::Drawing::Font( L"Verdana",10,FontStyle::Bold ); + dataGridView->ColumnHeadersDefaultCellStyle = columnHeaderStyle; + + // Set the column header names. + dataGridView->Columns[ 0 ]->Name = L"Recipe"; + dataGridView->Columns[ 1 ]->Name = L"Category"; + dataGridView->Columns[ 2 ]->Name = thirdColumnHeader; + dataGridView->Columns[ 3 ]->Name = L"Rating"; + + // Populate the rows. + array^row1 = gcnew array{ + L"Meatloaf",L"Main Dish",boringMeatloaf,boringMeatloafRanking + }; + array^row2 = gcnew array{ + L"Key Lime Pie",L"Dessert",L"lime juice, evaporated milk",L"****" + }; + array^row3 = gcnew array{ + L"Orange-Salsa Pork Chops",L"Main Dish",L"pork chops, salsa, orange juice",L"****" + }; + array^row4 = gcnew array{ + L"Black Bean and Rice Salad",L"Salad",L"black beans, brown rice",L"****" + }; + array^row5 = gcnew array{ + L"Chocolate Cheesecake",L"Dessert",L"cream cheese",L"***" + }; + array^row6 = gcnew array{ + L"Black Bean Dip",L"Appetizer",L"black beans, sour cream",L"***" + }; + array^rows = gcnew array{ + row1,row2,row3,row4,row5,row6 + }; + System::Collections::IEnumerator^ myEnum = rows->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + array^rowArray = safe_cast^>(myEnum->Current); + dataGridView->Rows->Add( rowArray ); + } + + PostRowCreation(); + shortMode = false; + boringRecipe = true; + } + + void AddButton( Button^ button, String^ buttonLabel, EventHandler^ handler ) + { + FlowLayoutPanel1->Controls->Add( button ); + button->TabIndex = FlowLayoutPanel1->Controls->Count; + button->Text = buttonLabel; + button->AutoSize = true; + button->Click += handler; + } + + + // Reset columns to initial disorderly arrangement. + void Button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Controls->Remove( dataGridView ); + dataGridView->~DataGridView(); + InitializeDataGridView(); + } + + + // Change the header in column three. + void Button2_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Toggle( &shortMode ); + if ( shortMode ) + { + dataGridView->Columns[ 2 ]->HeaderText = L"S"; + } + else + { + dataGridView->Columns[ 2 ]->HeaderText = thirdColumnHeader; + } + } + + void Toggle( interior_ptr toggleThis ) + { + *toggleThis = ! *toggleThis; + } + + + // Change the meatloaf recipe. + void Button3_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Toggle( &boringRecipe ); + if ( boringRecipe ) + { + SetMeatloaf( boringMeatloaf, boringMeatloafRanking ); + } + else + { + String^ greatMeatloafRecipe = L"1 lb. lean ground beef, " + L"1/2 cup bread crumbs, 1/4 cup ketchup," + L"1/3 tsp onion powder, " + L"1 clove of garlic, 1/2 pack onion soup mix " + L" dash of your favorite BBQ Sauce"; + SetMeatloaf( greatMeatloafRecipe, L"***" ); + } + } + + void SetMeatloaf( String^ recipe, String^ rating ) + { + dataGridView->Rows[ 0 ]->Cells[ 2 ]->Value = recipe; + dataGridView->Rows[ 0 ]->Cells[ 3 ]->Value = rating; + } + + +#pragma endregion +#pragma region S " demonstration code " + void AddAdditionalButtons() + { + AddButton( Button4, L"Freeze First Row", gcnew EventHandler( this, &DataGridViewBandDemo::Button4_Click ) ); + AddButton( Button5, L"Freeze Second Column", gcnew EventHandler( this, &DataGridViewBandDemo::Button5_Click ) ); + AddButton( Button6, L"Hide Salad Row", gcnew EventHandler( this, &DataGridViewBandDemo::Button6_Click ) ); + AddButton( Button7, L"Disable First Column Resizing", gcnew EventHandler( this, &DataGridViewBandDemo::Button7_Click ) ); + AddButton( Button8, L"Make ReadOnly", gcnew EventHandler( this, &DataGridViewBandDemo::Button8_Click ) ); + AddButton( Button9, L"Style Using Tag", gcnew EventHandler( this, &DataGridViewBandDemo::Button9_Click ) ); + } + + void AdjustDataGridViewSizing() + { + dataGridView->AutoSizeRowsMode = DataGridViewAutoSizeRowsMode::AllCells; + dataGridView->ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode::AutoSize; + } + + + // + // Freeze the first row. + void Button4_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + FreezeBand( dataGridView->Rows[ 0 ] ); + } + + void Button5_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + FreezeBand( dataGridView->Columns[ 1 ] ); + } + + void FreezeBand( DataGridViewBand^ band ) + { + band->Frozen = true; + DataGridViewCellStyle^ style = gcnew DataGridViewCellStyle; + style->BackColor = Color::WhiteSmoke; + band->DefaultCellStyle = style; + } + + + // + // + // Hide a band of cells. + void Button6_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + DataGridViewBand^ band = dataGridView->Rows[ 3 ]; + band->Visible = false; + } + + + // + // + // Turn off user's ability to resize a column. + void Button7_Click( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + DataGridViewBand^ band = dataGridView->Columns[ 0 ]; + band->Resizable = DataGridViewTriState::False; + } + + + // + // + // Make the entire DataGridView read only. + void Button8_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + System::Collections::IEnumerator^ myEnum = dataGridView->Columns->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + DataGridViewBand^ band = safe_cast(myEnum->Current); + band->ReadOnly = true; + } + } + + + // + // + void PostRowCreation() + { + SetBandColor( dataGridView->Columns[ 0 ], Color::CadetBlue ); + SetBandColor( dataGridView->Rows[ 1 ], Color::Coral ); + SetBandColor( dataGridView->Columns[ 2 ], Color::DodgerBlue ); + } + + void SetBandColor( DataGridViewBand^ band, Color color ) + { + band->Tag = color; + } + + + // Color the bands by the value stored in their tag. + void Button9_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + IEnumerator^ myEnum1 = dataGridView->Columns->GetEnumerator(); + while ( myEnum1->MoveNext() ) + { + DataGridViewBand^ band = static_cast(myEnum1->Current); + if ( band->Tag != nullptr ) + { + band->DefaultCellStyle->BackColor = *dynamic_cast(band->Tag); + } + } + + IEnumerator^ myEnum2 = safe_cast(dataGridView->Rows)->GetEnumerator(); + while ( myEnum2->MoveNext() ) + { + DataGridViewBand^ band = safe_cast(myEnum2->Current); + if ( band->Tag != nullptr ) + { + band->DefaultCellStyle->BackColor = *dynamic_cast(band->Tag); + } + } + } + + + // +#pragma endregion + +public: + static void Main() + { + Application::Run( gcnew DataGridViewBandDemo ); + } +}; + +int main() +{ + DataGridViewBandDemo::Main(); +} + +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewColumnDemo.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewColumnDemo.cpp new file mode 100644 index 0000000000..7266b7188d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewColumnDemo.cpp @@ -0,0 +1,441 @@ + +// +#using +#using +#using + +using namespace System; +using namespace System::Windows::Forms; +using namespace System::Drawing; +using namespace System::Collections; +public ref class DataGridViewColumnDemo: public Form +{ +private: + +#pragma region S "set up form" + +public: + DataGridViewColumnDemo() + { + Button1 = gcnew Button; + Button2 = gcnew Button; + Button3 = gcnew Button; + Button4 = gcnew Button; + Button5 = gcnew Button; + Button6 = gcnew Button; + Button7 = gcnew Button; + Button8 = gcnew Button; + Button9 = gcnew Button; + Button10 = gcnew Button; + FlowLayoutPanel1 = gcnew FlowLayoutPanel; + thirdColumnHeader = L"Main Ingredients"; + boringMeatloaf = L"ground beef"; + boringMeatloafRanking = L"*"; + toolStripItem1 = gcnew ToolStripMenuItem; + InitializeComponent(); + AddButton( Button1, L"Reset", gcnew EventHandler( this, &DataGridViewColumnDemo::ResetToDisorder ) ); + AddButton( Button2, L"Change Column 3 Header", gcnew EventHandler( this, &DataGridViewColumnDemo::ChangeColumn3Header ) ); + AddButton( Button3, L"Change Meatloaf Recipe", gcnew EventHandler( this, &DataGridViewColumnDemo::ChangeMeatloafRecipe ) ); + AddAdditionalButtons(); + InitializeDataGridView(); + } + + DataGridView^ dataGridView; + Button^ Button1; + Button^ Button2; + Button^ Button3; + Button^ Button4; + Button^ Button5; + Button^ Button6; + Button^ Button7; + Button^ Button8; + Button^ Button9; + Button^ Button10; + FlowLayoutPanel^ FlowLayoutPanel1; + +private: + void InitializeComponent() + { + FlowLayoutPanel1->Location = Point(454,0); + FlowLayoutPanel1->AutoSize = true; + FlowLayoutPanel1->FlowDirection = FlowDirection::TopDown; + AutoSize = true; + ClientSize = System::Drawing::Size( 614, 360 ); + FlowLayoutPanel1->Name = L"flowlayoutpanel"; + Controls->Add( this->FlowLayoutPanel1 ); + Text = this->GetType()->Name; + } + + +#pragma endregion +#pragma region S " set up DataGridView " + String^ thirdColumnHeader; + String^ boringMeatloaf; + String^ boringMeatloafRanking; + bool boringRecipe; + bool shortMode; + void InitializeDataGridView() + { + dataGridView = gcnew System::Windows::Forms::DataGridView; + Controls->Add( dataGridView ); + dataGridView->Size = System::Drawing::Size( 300, 200 ); + + // Create an unbound DataGridView by declaring a + // column count. + dataGridView->ColumnCount = 4; + AdjustDataGridViewSizing(); + + // Set the column header style. + DataGridViewCellStyle^ columnHeaderStyle = gcnew DataGridViewCellStyle; + columnHeaderStyle->BackColor = Color::Aqua; + columnHeaderStyle->Font = gcnew System::Drawing::Font( L"Verdana",10,FontStyle::Bold ); + dataGridView->ColumnHeadersDefaultCellStyle = columnHeaderStyle; + + // Set the column header names. + dataGridView->Columns[ 0 ]->Name = L"Recipe"; + dataGridView->Columns[ 1 ]->Name = L"Category"; + dataGridView->Columns[ 2 ]->Name = thirdColumnHeader; + dataGridView->Columns[ 3 ]->Name = L"Rating"; + criteriaLabel = L"Column 3 sizing criteria: "; + PostColumnCreation(); + + // Populate the rows. + array^row1 = gcnew array{ + L"Meatloaf",L"Main Dish",boringMeatloaf,boringMeatloafRanking + }; + array^row2 = gcnew array{ + L"Key Lime Pie",L"Dessert",L"lime juice, evaporated milk",L"****" + }; + array^row3 = gcnew array{ + L"Orange-Salsa Pork Chops",L"Main Dish",L"pork chops, salsa, orange juice",L"****" + }; + array^row4 = gcnew array{ + L"Black Bean and Rice Salad",L"Salad",L"black beans, brown rice",L"****" + }; + array^row5 = gcnew array{ + L"Chocolate Cheesecake",L"Dessert",L"cream cheese",L"***" + }; + array^row6 = gcnew array{ + L"Black Bean Dip",L"Appetizer",L"black beans, sour cream",L"***" + }; + array^rows = gcnew array{ + row1,row2,row3,row4,row5,row6 + }; + System::Collections::IEnumerator^ myEnum = rows->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + array^rowArray = safe_cast^>(myEnum->Current); + dataGridView->Rows->Add( rowArray ); + } + + shortMode = false; + boringRecipe = true; + } + + void AddButton( Button^ button, String^ buttonLabel, EventHandler^ handler ) + { + FlowLayoutPanel1->Controls->Add( button ); + button->TabIndex = FlowLayoutPanel1->Controls->Count; + button->Text = buttonLabel; + button->AutoSize = true; + button->Click += handler; + } + + void ResetToDisorder( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Controls->Remove( dataGridView ); + dataGridView->~DataGridView(); + InitializeDataGridView(); + } + + void ChangeColumn3Header( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Toggle( &shortMode ); + if ( shortMode ) + { + dataGridView->Columns[ 2 ]->HeaderText = L"S"; + } + else + { + dataGridView->Columns[ 2 ]->HeaderText = thirdColumnHeader; + } + } + + void Toggle( interior_ptr toggleThis ) + { + *toggleThis = ! *toggleThis; + } + + void ChangeMeatloafRecipe( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Toggle( &boringRecipe ); + if ( boringRecipe ) + { + SetMeatloaf( boringMeatloaf, boringMeatloafRanking ); + } + else + { + String^ greatMeatloafRecipe = L"1 lb. lean ground beef, " + L"1/2 cup bread crumbs, 1/4 cup ketchup," + L"1/3 tsp onion powder, " + L"1 clove of garlic, 1/2 pack onion soup mix " + L" dash of your favorite BBQ Sauce"; + SetMeatloaf( greatMeatloafRecipe, L"***" ); + } + } + + void SetMeatloaf( String^ recipe, String^ rating ) + { + dataGridView->Rows[ 0 ]->Cells[ 2 ]->Value = recipe; + dataGridView->Rows[ 0 ]->Cells[ 3 ]->Value = rating; + } + + +#pragma endregion + +public: + static void Main() + { + Application::Run( gcnew DataGridViewColumnDemo ); + } + + +#pragma region S " demonstration code " + +private: + void PostColumnCreation() + { + AddContextLabel(); + AddCriteriaLabel(); + CustomizeCellsInThirdColumn(); + AddContextMenu(); + SetDefaultCellInFirstColumn(); + ToolTips(); + dataGridView->CellMouseEnter += gcnew DataGridViewCellEventHandler( this, &DataGridViewColumnDemo::dataGridView_CellMouseEnter ); + dataGridView->AutoSizeColumnModeChanged += gcnew DataGridViewAutoSizeColumnModeEventHandler( this, &DataGridViewColumnDemo::dataGridView_AutoSizeColumnModeChanged ); + } + + String^ criteriaLabel; + void AddCriteriaLabel() + { + AddLabelToPanelIfNotAlreadyThere( criteriaLabel, String::Concat( criteriaLabel, dataGridView->Columns[ 2 ]->AutoSizeMode, L"." ) ); + } + + void AddContextLabel() + { + String^ labelName = L"label"; + AddLabelToPanelIfNotAlreadyThere( labelName, L"Use shortcut menu to change cell color." ); + } + + void AddLabelToPanelIfNotAlreadyThere( String^ labelName, String^ labelText ) + { + Label^ label; + if ( FlowLayoutPanel1->Controls[ labelName ] == nullptr ) + { + label = gcnew Label; + label->AutoSize = true; + label->Name = labelName; + label->BackColor = Color::Bisque; + FlowLayoutPanel1->Controls->Add( label ); + } + else + { + label = dynamic_cast(FlowLayoutPanel1->Controls[ labelName ]); + } + + label->Text = labelText; + } + + + // + void CustomizeCellsInThirdColumn() + { + int thirdColumn = 2; + DataGridViewColumn^ column = dataGridView->Columns[ thirdColumn ]; + DataGridViewCell^ cell = gcnew DataGridViewTextBoxCell; + cell->Style->BackColor = Color::Wheat; + column->CellTemplate = cell; + } + + + // + // + ToolStripMenuItem^ toolStripItem1; + void AddContextMenu() + { + toolStripItem1->Text = L"Redden"; + toolStripItem1->Click += gcnew EventHandler( this, &DataGridViewColumnDemo::toolStripItem1_Click ); + System::Windows::Forms::ContextMenuStrip^ strip = gcnew System::Windows::Forms::ContextMenuStrip; + IEnumerator^ myEnum = dataGridView->Columns->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + DataGridViewColumn^ column = safe_cast(myEnum->Current); + column->ContextMenuStrip = strip; + column->ContextMenuStrip->Items->Add( toolStripItem1 ); + } + } + + DataGridViewCellEventArgs^ mouseLocation; + + // Change the cell's color. + void toolStripItem1_Click( Object^ /*sender*/, EventArgs^ /*args*/ ) + { + dataGridView->Rows[ mouseLocation->RowIndex ]->Cells[ mouseLocation->ColumnIndex ]->Style->BackColor = Color::Red; + } + + + // Deal with hovering over a cell. + void dataGridView_CellMouseEnter( Object^ /*sender*/, DataGridViewCellEventArgs^ location ) + { + mouseLocation = location; + } + + + // + // + void SetDefaultCellInFirstColumn() + { + DataGridViewColumn^ firstColumn = dataGridView->Columns[ 0 ]; + DataGridViewCellStyle^ cellStyle = gcnew DataGridViewCellStyle; + cellStyle->BackColor = Color::Thistle; + firstColumn->DefaultCellStyle = cellStyle; + } + + + // + // + void ToolTips() + { + DataGridViewColumn^ firstColumn = dataGridView->Columns[ 0 ]; + DataGridViewColumn^ thirdColumn = dataGridView->Columns[ 2 ]; + firstColumn->ToolTipText = L"This column uses a default cell."; + thirdColumn->ToolTipText = L"This column uses a template cell." + L" Style changes to one cell apply to all cells."; + } + + + // + void AddAdditionalButtons() + { + AddButton( Button4, L"Set Minimum Width of Column Two", gcnew EventHandler( this, &DataGridViewColumnDemo::Button4_Click ) ); + AddButton( Button5, L"Set Width of Column One", gcnew EventHandler( this, &DataGridViewColumnDemo::Button5_Click ) ); + AddButton( Button6, L"Autosize Third Column", gcnew EventHandler( this, &DataGridViewColumnDemo::Button6_Click ) ); + AddButton( Button7, L"Add Thick Vertical Edge", gcnew EventHandler( this, &DataGridViewColumnDemo::Button7_Click ) ); + AddButton( Button8, L"Style and Number Columns", gcnew EventHandler( this, &DataGridViewColumnDemo::Button8_Click ) ); + AddButton( Button9, L"Change Column Header Text", gcnew EventHandler( this, &DataGridViewColumnDemo::Button9_Click ) ); + AddButton( Button10, L"Swap First and Last Columns", gcnew EventHandler( this, &DataGridViewColumnDemo::Button10_Click ) ); + } + + void AdjustDataGridViewSizing() + { + dataGridView->ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode::AutoSize; + } + + + // + //Set the minimum width. + void Button4_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + DataGridViewColumn^ column = dataGridView->Columns[ 1 ]; + column->MinimumWidth = 40; + } + + + // + // + // Set the width. + void Button5_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + DataGridViewColumn^ column = dataGridView->Columns[ 0 ]; + column->Width = 60; + } + + + // + // + // AutoSize the third column. + void Button6_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + DataGridViewColumn^ column = dataGridView->Columns[ 2 ]; + column->AutoSizeMode = DataGridViewAutoSizeColumnMode::DisplayedCells; + } + + + // + // + // Set the vertical edge. + void Button7_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + int thirdColumn = 2; + + // int edgeThickness = 5; + DataGridViewColumn^ column = dataGridView->Columns[ thirdColumn ]; + column->DividerWidth = 10; + } + + + // + // + // Style and number columns. + void Button8_Click( Object^ /*sender*/, EventArgs^ /*args*/ ) + { + DataGridViewCellStyle^ style = gcnew DataGridViewCellStyle; + style->Alignment = DataGridViewContentAlignment::MiddleCenter; + style->ForeColor = Color::IndianRed; + style->BackColor = Color::Ivory; + IEnumerator^ myEnum1 = dataGridView->Columns->GetEnumerator(); + while ( myEnum1->MoveNext() ) + { + DataGridViewColumn^ column = safe_cast(myEnum1->Current); + column->HeaderCell->Value = column->Index.ToString(); + column->HeaderCell->Style = style; + } + } + + + // + // + // Change the text in the column header. + void Button9_Click( Object^ /*sender*/, EventArgs^ /*args*/ ) + { + IEnumerator^ myEnum2 = dataGridView->Columns->GetEnumerator(); + while ( myEnum2->MoveNext() ) + { + DataGridViewColumn^ column = safe_cast(myEnum2->Current); + column->HeaderText = String::Concat( L"Column ", column->Index.ToString() ); + } + } + + + // + // + // Swap the last column with the first. + void Button10_Click( Object^ /*sender*/, EventArgs^ /*args*/ ) + { + DataGridViewColumnCollection^ columnCollection = dataGridView->Columns; + DataGridViewColumn^ firstDisplayedColumn = columnCollection->GetFirstColumn( DataGridViewElementStates::Visible ); + DataGridViewColumn^ lastDisplayedColumn = columnCollection->GetLastColumn( DataGridViewElementStates::Visible, DataGridViewElementStates::None ); + int firstColumn_sIndex = firstDisplayedColumn->DisplayIndex; + firstDisplayedColumn->DisplayIndex = lastDisplayedColumn->DisplayIndex; + lastDisplayedColumn->DisplayIndex = firstColumn_sIndex; + } + + + // + // + // Updated the criteria label. + void dataGridView_AutoSizeColumnModeChanged( Object^ /*sender*/, DataGridViewAutoSizeColumnModeEventArgs^ args ) + { + args->Column->DataGridView->Parent->Controls[ L"flowlayoutpanel" ]->Controls[ criteriaLabel ]->Text = String::Concat( criteriaLabel, args->Column->AutoSizeMode ); + } + // +#pragma endregion + +}; + +int main() +{ + DataGridViewColumnDemo::Main(); +} + +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewRowDemo.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewRowDemo.cpp new file mode 100644 index 0000000000..fda4f9201a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/DataGridViewRowDemo.cpp @@ -0,0 +1,304 @@ + +// +#using +#using +#using + +using namespace System; +using namespace System::Windows::Forms; +using namespace System::Drawing; +public ref class DataGridViewRowDemo: public Form +{ +private: + +#pragma region S " form setup " + +public: + DataGridViewRowDemo() + { + Button1 = gcnew Button; + Button2 = gcnew Button; + Button3 = gcnew Button; + Button4 = gcnew Button; + Button5 = gcnew Button; + Button6 = gcnew Button; + Button7 = gcnew Button; + Button8 = gcnew Button; + Button9 = gcnew Button; + Button10 = gcnew Button; + FlowLayoutPanel1 = gcnew FlowLayoutPanel; + thirdColumnHeader = L"Main Ingredients"; + boringMeatloaf = L"ground beef"; + boringMeatloafRanking = L"*"; + ratingColumn = 3; + AddButton( Button1, L"Reset", gcnew EventHandler( this, &DataGridViewRowDemo::Button1_Click ) ); + AddButton( Button2, L"Change Column 3 Header", gcnew EventHandler( this, &DataGridViewRowDemo::Button2_Click ) ); + AddButton( Button3, L"Change Meatloaf Recipe", gcnew EventHandler( this, &DataGridViewRowDemo::Button3_Click ) ); + InitializeComponent(); + InitializeDataGridView(); + AddAdditionalButtons(); + } + + +private: + DataGridView^ dataGridView; + Button^ Button1; + Button^ Button2; + Button^ Button3; + Button^ Button4; + Button^ Button5; + Button^ Button6; + Button^ Button7; + Button^ Button8; + Button^ Button9; + Button^ Button10; + FlowLayoutPanel^ FlowLayoutPanel1; + void InitializeComponent() + { + FlowLayoutPanel1->Location = Point(454,0); + FlowLayoutPanel1->AutoSize = true; + FlowLayoutPanel1->FlowDirection = FlowDirection::TopDown; + AutoSize = true; + ClientSize = System::Drawing::Size( 614, 360 ); + FlowLayoutPanel1->Name = L"flowlayoutpanel"; + Controls->Add( this->FlowLayoutPanel1 ); + Text = this->GetType()->Name; + } + + +#pragma endregion +#pragma region S " setup DataGridView " + String^ thirdColumnHeader; + String^ boringMeatloaf; + String^ boringMeatloafRanking; + bool boringRecipe; + bool shortMode; + void InitializeDataGridView() + { + dataGridView = gcnew System::Windows::Forms::DataGridView; + Controls->Add( dataGridView ); + dataGridView->Size = System::Drawing::Size( 300, 200 ); + + // Create an unbound DataGridView by declaring a + // column count. + dataGridView->ColumnCount = 4; + dataGridView->ColumnHeadersVisible = true; + AdjustDataGridViewSizing(); + + // Set the column header style. + DataGridViewCellStyle^ columnHeaderStyle = gcnew DataGridViewCellStyle; + columnHeaderStyle->BackColor = Color::Aqua; + columnHeaderStyle->Font = gcnew System::Drawing::Font( L"Verdana",10,FontStyle::Bold ); + dataGridView->ColumnHeadersDefaultCellStyle = columnHeaderStyle; + + // Set the column header names. + dataGridView->Columns[ 0 ]->Name = L"Recipe"; + dataGridView->Columns[ 1 ]->Name = L"Category"; + dataGridView->Columns[ 2 ]->Name = thirdColumnHeader; + dataGridView->Columns[ 3 ]->Name = L"Rating"; + + // Populate the rows. + array^row1 = gcnew array{ + L"Meatloaf",L"Main Dish",boringMeatloaf,boringMeatloafRanking + }; + array^row2 = gcnew array{ + L"Key Lime Pie",L"Dessert",L"lime juice, evaporated milk",L"****" + }; + array^row3 = gcnew array{ + L"Orange-Salsa Pork Chops",L"Main Dish",L"pork chops, salsa, orange juice",L"****" + }; + array^row4 = gcnew array{ + L"Black Bean and Rice Salad",L"Salad",L"black beans, brown rice",L"****" + }; + array^row5 = gcnew array{ + L"Chocolate Cheesecake",L"Dessert",L"cream cheese",L"***" + }; + array^row6 = gcnew array{ + L"Black Bean Dip",L"Appetizer",L"black beans, sour cream",L"***" + }; + array^rows = gcnew array{ + row1,row2,row3,row4,row5,row6 + }; + System::Collections::IEnumerator^ myEnum = rows->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + array^rowArray = safe_cast^>(myEnum->Current); + dataGridView->Rows->Add( rowArray ); + } + + shortMode = false; + boringRecipe = true; + } + + void AddButton( Button^ button, String^ buttonLabel, EventHandler^ handler ) + { + FlowLayoutPanel1->Controls->Add( button ); + button->TabIndex = FlowLayoutPanel1->Controls->Count; + button->Text = buttonLabel; + button->AutoSize = true; + button->Click += handler; + } + + + // Reset columns to initial disorderly arrangement. + void Button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Controls->Remove( dataGridView ); + dataGridView->~DataGridView(); + InitializeDataGridView(); + } + + + // Change column 3 header. + void Button2_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Toggle( &shortMode ); + if ( shortMode ) + { + dataGridView->Columns[ 2 ]->HeaderText = L"S"; + } + else + { + dataGridView->Columns[ 2 ]->HeaderText = thirdColumnHeader; + } + } + + void Toggle( interior_ptr toggleThis ) + { + *toggleThis = ! *toggleThis; + } + + + // Change meatloaf recipe. + void Button3_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + Toggle( &boringRecipe ); + if ( boringRecipe ) + { + SetMeatloaf( boringMeatloaf, boringMeatloafRanking ); + } + else + { + String^ greatMeatloafRecipe = L"1 lb. lean ground beef, " + L"1/2 cup bread crumbs, 1/4 cup ketchup," + L"1/3 tsp onion powder, " + L"1 clove of garlic, 1/2 pack onion soup mix " + L" dash of your favorite BBQ Sauce"; + SetMeatloaf( greatMeatloafRecipe, L"***" ); + } + } + + void SetMeatloaf( String^ recipe, String^ rating ) + { + dataGridView->Rows[ 0 ]->Cells[ 2 ]->Value = recipe; + dataGridView->Rows[ 0 ]->Cells[ 3 ]->Value = rating; + } + + +#pragma endregion +#pragma region S " demonstration code " + void AddAdditionalButtons() + { + AddButton( Button4, L"Set Row Two Minimum Height", gcnew EventHandler( this, &DataGridViewRowDemo::Button4_Click ) ); + AddButton( Button5, L"Set Row One Height", gcnew EventHandler( this, &DataGridViewRowDemo::Button5_Click ) ); + AddButton( Button6, L"Label Rows", gcnew EventHandler( this, &DataGridViewRowDemo::Button6_Click ) ); + AddButton( Button7, L"Turn on Extra Edge", gcnew EventHandler( this, &DataGridViewRowDemo::Button7_Click ) ); + AddButton( Button8, L"Give Cheesecake an Excellent Rating", gcnew EventHandler( this, &DataGridViewRowDemo::Button8_Click ) ); + } + + void AdjustDataGridViewSizing() + { + dataGridView->ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode::AutoSize; + dataGridView->Columns[ ratingColumn ]->Width = 50; + } + + + // + // Set minimum height. + void Button4_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + int secondRow = 1; + DataGridViewRow^ row = dataGridView->Rows[ secondRow ]; + row->MinimumHeight = 40; + } + + + // + // + // Set height. + void Button5_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + DataGridViewRow^ row = dataGridView->Rows[ 0 ]; + row->Height = 15; + } + + + // + // + // Set row labels. + void Button6_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + + int rowNumber = 1; + System::Collections::IEnumerator^ myEnum = safe_cast(dataGridView->Rows)->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + DataGridViewRow^ row = safe_cast(myEnum->Current); + if ( row->IsNewRow ) + continue; + row->HeaderCell->Value = String::Format( L"Row {0}", rowNumber ); + + rowNumber = rowNumber + 1; + } + + dataGridView->AutoResizeRowHeadersWidth( DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders ); + } + + + // + // + // Set a thick horizontal edge. + void Button7_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + int secondRow = 1; + int edgeThickness = 3; + DataGridViewRow^ row = dataGridView->Rows[ secondRow ]; + row->DividerHeight = 10; + } + + + // + // + // Give cheescake excellent rating. + void Button8_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + UpdateStars( dataGridView->Rows[ 4 ], L"******************" ); + } + + int ratingColumn; + void UpdateStars( DataGridViewRow^ row, String^ stars ) + { + row->Cells[ ratingColumn ]->Value = stars; + + // Resize the column width to account for the new value. + row->DataGridView->AutoResizeColumn( ratingColumn, DataGridViewAutoSizeColumnMode::DisplayedCells ); + } + + + // +#pragma endregion + +public: + static void Main() + { + Application::Run( gcnew DataGridViewRowDemo ); + } + +}; + +int main() +{ + DataGridViewRowDemo::Main(); +} + +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/makefile new file mode 100644 index 0000000000..a55752cd9f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CPP/makefile @@ -0,0 +1,10 @@ +all: DataGridViewBandDemo.exe DataGridViewColumnDemo.exe DataGridViewRowDemo.exe + +DataGridViewBandDemo.exe: DataGridViewBandDemo.cpp + cl /clr:pure DataGridViewBandDemo.cpp + +DataGridViewColumnDemo.exe: DataGridViewColumnDemo.cpp + cl /clr:pure DataGridViewColumnDemo.cpp + +DataGridViewRowDemo.exe: DataGridViewRowDemo.cpp + cl /clr:pure DataGridViewRowDemo.cpp \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CPP/tictactoe.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CPP/tictactoe.cpp new file mode 100644 index 0000000000..b7f42ec710 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CPP/tictactoe.cpp @@ -0,0 +1,480 @@ + +// This example demonstrates using images to create a +// TicTacToe game. +// +#using +#using +#using + +using namespace System::IO; +using namespace System::Windows::Forms; +using namespace System::Drawing; +using namespace System; +public ref class TicTacToe: public System::Windows::Forms::Form +{ +public: + TicTacToe() + : Form() + { + oBytes = gcnew array{ + 0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x76, + 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, 0xB, 0x0, 0x0, 0x0, 0xA, + 0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, + 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x80, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, 0x80, 0x0, + 0x80, 0x0, 0x0, 0x0, 0x80, 0x0, 0x80, 0x0, 0x80, 0x80, 0x0, + 0x0, 0xC0, 0xC0, 0xC0, 0x0, 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, + 0xFF, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF, + 0x0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0xF, 0xFF, 0xF0, + 0x0, 0x0, 0xFF, 0x0, 0xFF, 0xF0, 0xF, 0xF0, 0x0, 0x0, 0xF0, + 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF0, 0xFF, 0xFF, + 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x0, 0x0, 0x0, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0, 0x0, 0x0, + 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF0, 0xFF, + 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0xF0, + 0xF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xF, 0xFF, 0xF0, 0x0, + 0x0}; + xBytes = gcnew array{ + 0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x76, 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, + 0xB, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x50, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x80, + 0x0, 0x0, 0x0, 0x80, 0x80, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, + 0x0, 0x80, 0x0, 0x80, 0x80, 0x0, 0x0, 0xC0, 0xC0, 0xC0, 0x0, + 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0xFF, 0x0, + 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0x0, + 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0x0, + 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, 0xF, + 0xFF, 0xFF, 0xF, 0xF0, 0x0, 0x0, 0xFF, 0xF0, 0xFF, 0xF0, + 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xF, 0xF, 0xFF, 0xF0, 0x0, + 0x0, 0xFF, 0xFF, 0xF, 0xF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, + 0xF, 0xF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xF0, 0xFF, 0xF0, + 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xF, 0xFF, 0xFF, 0xF, 0xF0, 0x0, + 0x0, 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0}; + blankBytes = gcnew array{ + 0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x76, + 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, 0xB, 0x0, 0x0, 0x0, 0xA, + 0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, + 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x80, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, 0x80, 0x0, + 0x80, 0x0, 0x0, 0x0, 0x80, 0x0, 0x80, 0x0, 0x80, 0x80, 0x0, + 0x0, 0xC0, 0xC0, 0xC0, 0x0, 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, + 0xFF, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF, + 0x0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, + 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, + 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xF0, 0x0, 0x0}; + blank = gcnew Bitmap( gcnew MemoryStream( blankBytes ) ); + x = gcnew Bitmap( gcnew MemoryStream( xBytes ) ); + o = gcnew Bitmap( gcnew MemoryStream( oBytes ) ); + this->AutoSize = true; + turn = gcnew Label; + Button1 = gcnew Button; + Button2 = gcnew Button; + Button3 = gcnew Button; + Button4 = gcnew Button; + Button5 = gcnew Button; + Panel1 = gcnew FlowLayoutPanel; + SetupButtons(); + InitializeDataGridView( nullptr, nullptr ); + + xString = L"X's turn"; + oString = L"O's turn"; + gameOverString = L"Game Over"; + bitmapPadding = 6; + } + + +private: + DataGridView^ dataGridView1; + Button^ Button1; + Label^ turn; + Button^ Button2; + Button^ Button3; + Button^ Button4; + Button^ Button5; + FlowLayoutPanel^ Panel1; + +#pragma region S " bitmaps " + array^oBytes; + array^xBytes; + array^blankBytes; + +#pragma endregion + Bitmap^ blank; + Bitmap^ x; + Bitmap^ o; + String^ xString; + String^ oString; + String^ gameOverString; + int bitmapPadding; + void InitializeDataGridView( Object^ ignored, EventArgs^ e ) + { + this->Panel1->SuspendLayout(); + this->SuspendLayout(); + ConfigureForm(); + SizeGrid(); + CreateColumns(); + CreateRows(); + this->Panel1->ResumeLayout( false ); + this->ResumeLayout( false ); + } + + void ConfigureForm() + { + AutoSize = true; + turn->Size = System::Drawing::Size( 75, 34 ); + turn->TextAlign = ContentAlignment::MiddleLeft; + Panel1->Location = System::Drawing::Point( 0, 8 ); + Panel1->Size = System::Drawing::Size( 120, 196 ); + Panel1->FlowDirection = FlowDirection::TopDown; + ClientSize = System::Drawing::Size( 355, 200 ); + Controls->Add( this->Panel1 ); + Text = L"TicTacToe"; + dataGridView1 = gcnew System::Windows::Forms::DataGridView; + dataGridView1->Location = Point(120,0); + dataGridView1->AllowUserToAddRows = false; + dataGridView1->CellClick += gcnew DataGridViewCellEventHandler( this, &TicTacToe::dataGridView1_CellClick ); + dataGridView1->CellMouseEnter += gcnew DataGridViewCellEventHandler( this, &TicTacToe::dataGridView1_CellMouseEnter ); + dataGridView1->CellMouseLeave += gcnew DataGridViewCellEventHandler( this, &TicTacToe::dataGridView1_CellMouseLeave ); + Controls->Add( dataGridView1 ); + turn->Text = xString; + turn->AutoSize = true; + } + + void SetupButtons() + { + Button1->AutoSize = true; + SetupButton( Button1, L"Restart", gcnew EventHandler( this, &TicTacToe::Reset ) ); + Panel1->Controls->Add( turn ); + SetupButton( Button2, L"Increase Cell Size", gcnew EventHandler( this, &TicTacToe::MakeCellsLarger ) ); + SetupButton( Button3, L"Stretch Images", gcnew EventHandler( this, &TicTacToe::Stretch ) ); + SetupButton( Button4, L"Zoom Images", gcnew EventHandler( this, &TicTacToe::ZoomToImage ) ); + SetupButton( Button5, L"Normal Images", gcnew EventHandler( this, &TicTacToe::NormalImage ) ); + } + + void SetupButton( Button^ button, String^ buttonLabel, EventHandler^ handler ) + { + Panel1->Controls->Add( button ); + button->Text = buttonLabel; + button->AutoSize = true; + button->Click += handler; + } + + + // + void CreateColumns() + { + DataGridViewImageColumn^ imageColumn; + int columnCount = 0; + do + { + Bitmap^ unMarked = blank; + imageColumn = gcnew DataGridViewImageColumn; + + //Add twice the padding for the left and + //right sides of the cell. + imageColumn->Width = x->Width + 2 * bitmapPadding + 1; + imageColumn->Image = unMarked; + dataGridView1->Columns->Add( imageColumn ); + columnCount = columnCount + 1; + } + while ( columnCount < 3 ); + } + + + // + void CreateRows() + { + dataGridView1->Rows->Add(); + dataGridView1->Rows->Add(); + dataGridView1->Rows->Add(); + } + + + // + void SizeGrid() + { + dataGridView1->ColumnHeadersVisible = false; + dataGridView1->RowHeadersVisible = false; + dataGridView1->AllowUserToResizeColumns = false; + dataGridView1->AllowUserToResizeRows = false; + dataGridView1->BorderStyle = BorderStyle::None; + + //Add twice the padding for the top of the cell + //and the bottom. + dataGridView1->RowTemplate->Height = x->Height + 2 * bitmapPadding + 1; + dataGridView1->AutoSize = true; + } + + + // + void Reset( Object^ sender, System::EventArgs^ e ) + { + dataGridView1->~DataGridView(); + InitializeDataGridView( nullptr, nullptr ); + } + + + // + void dataGridView1_CellClick( Object^ sender, DataGridViewCellEventArgs^ e ) + { + if ( turn->Equals( gameOverString ) ) + { + return; + } + + DataGridViewImageCell^ cell = dynamic_cast(dataGridView1->Rows[ e->RowIndex ]->Cells[ e->ColumnIndex ]); + if ( cell->Value == blank ) + { + if ( IsOsTurn() ) + { + cell->Value = o; + } + else + { + cell->Value = x; + } + + ToggleTurn(); + } + + if ( IsAWin( cell ) ) + { + turn->Text = gameOverString; + } + } + + + // + // + void dataGridView1_CellMouseEnter( Object^ sender, DataGridViewCellEventArgs^ e ) + { + Bitmap^ markingUnderMouse = dynamic_cast(dataGridView1->Rows[ e->RowIndex ]->Cells[ e->ColumnIndex ]->Value); + if ( markingUnderMouse == blank ) + { + dataGridView1->Cursor = Cursors::Default; + } + else + if ( markingUnderMouse == o || markingUnderMouse == x ) + { + dataGridView1->Cursor = Cursors::No; + ToolTip(e,true); + } + } + + void ToolTip( DataGridViewCellEventArgs^ e, bool showTip ) + { + DataGridViewImageCell^ cell = dynamic_cast(dataGridView1->Rows[ e->RowIndex ]->Cells[ e->ColumnIndex ]); + DataGridViewImageColumn^ imageColumn = dynamic_cast(dataGridView1->Columns[ cell->ColumnIndex ]); + if ( showTip ) + cell->ToolTipText = imageColumn->Description; + else + { + cell->ToolTipText = String::Empty; + } + } + + void dataGridView1_CellMouseLeave( Object^ sender, DataGridViewCellEventArgs^ e ) + { + ToolTip( e, false ); + dataGridView1->Cursor = Cursors::Default; + } + + + // + // + void Stretch( Object^ sender, EventArgs^ e ) + { + System::Collections::IEnumerator^ myEnum = dataGridView1->Columns->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + DataGridViewImageColumn^ column = safe_cast(myEnum->Current); + column->ImageLayout = DataGridViewImageCellLayout::Stretch; + column->Description = L"Stretched"; + } + } + + void ZoomToImage( Object^ sender, EventArgs^ e ) + { + System::Collections::IEnumerator^ myEnum1 = dataGridView1->Columns->GetEnumerator(); + while ( myEnum1->MoveNext() ) + { + DataGridViewImageColumn^ column = safe_cast(myEnum1->Current); + column->ImageLayout = DataGridViewImageCellLayout::Zoom; + column->Description = L"Zoomed"; + } + } + + void NormalImage( Object^ sender, EventArgs^ e ) + { + System::Collections::IEnumerator^ myEnum2 = dataGridView1->Columns->GetEnumerator(); + while ( myEnum2->MoveNext() ) + { + DataGridViewImageColumn^ column = safe_cast(myEnum2->Current); + column->ImageLayout = DataGridViewImageCellLayout::Normal; + column->Description = L"Normal"; + } + } + + + // + void MakeCellsLarger( Object^ sender, EventArgs^ e ) + { + System::Collections::IEnumerator^ myEnum3 = dataGridView1->Columns->GetEnumerator(); + while ( myEnum3->MoveNext() ) + { + DataGridViewImageColumn^ column = safe_cast(myEnum3->Current); + column->Width = column->Width * 2; + } + + System::Collections::IEnumerable^ temp = safe_cast(dataGridView1->Rows); + System::Collections::IEnumerator^ myEnum4 = temp->GetEnumerator(); + + //System::Collections::IEnumerator^ myEnum4 = dataGridView1->Rows->GetEnumerator(); + while ( myEnum4->MoveNext() ) + { + DataGridViewRow^ row = safe_cast(myEnum4->Current); + if ( row->IsNewRow ) + break; + row->Height = (int)(row->Height * 1.5); + } + } + + bool IsAWin( DataGridViewCell^ cell ) + { + if ( ARowIsSame() || AColumnIsSame() || ADiagonalIsSame() ) + return true; + else + return false; + } + + bool ARowIsSame() + { + Bitmap^ marking = nullptr; + System::Collections::IEnumerable^ temp = safe_cast(dataGridView1->Rows); + System::Collections::IEnumerator^ myEnum5 = temp->GetEnumerator(); + //System::Collections::IEnumerator^ myEnum5 = dataGridView1->Rows->GetEnumerator(); + while ( myEnum5->MoveNext() ) + { + DataGridViewRow^ row = safe_cast(myEnum5->Current); + if ( row->IsNewRow ) + break; + + marking = dynamic_cast(row->Cells[ 0 ]->Value); + if ( marking != blank ) + { + if ( marking == row->Cells[ 1 ]->Value && marking == row->Cells[ 2 ]->Value ) + return true; + } + } + + return false; + } + + bool AColumnIsSame() + { + int columnIndex = 0; + Bitmap^ marking; + do + { + marking = dynamic_cast(dataGridView1->Rows[ 0 ]->Cells[ columnIndex ]->Value); + if ( marking != blank ) + { + if ( marking == dynamic_cast(dataGridView1->Rows[ 1 ]->Cells[ columnIndex ]->Value) && marking == dynamic_cast(dataGridView1->Rows[ 2 ]->Cells[ columnIndex ]->Value) ) + return true; + } + + columnIndex = columnIndex + 1; + } + while ( columnIndex < dataGridView1->Columns->GetColumnCount( DataGridViewElementStates::Visible ) ); + + return false; + } + + bool ADiagonalIsSame() + { + if ( LeftToRightDiagonalIsSame() ) + { + return true; + } + + if ( RightToLeftDiagonalIsSame() ) + { + return true; + } + + return false; + } + + bool LeftToRightDiagonalIsSame() + { + return IsDiagonalSame( 0, 2 ); + } + + bool RightToLeftDiagonalIsSame() + { + return IsDiagonalSame( 2, 0 ); + } + + bool IsDiagonalSame( int startingColumn, int lastColumn ) + { + Bitmap^ marking = dynamic_cast(dataGridView1->Rows[ 0 ]->Cells[ startingColumn ]->Value); + if ( marking == blank ) + return false; + + if ( marking == dataGridView1->Rows[ 1 ]->Cells[ 1 ]->Value && marking == dataGridView1->Rows[ 2 ]->Cells[ lastColumn ]->Value ) + return true; + + return false; + } + + void ToggleTurn() + { + if ( turn->Text->Equals( xString ) ) + { + turn->Text = oString; + } + else + { + turn->Text = xString; + } + } + + bool IsOsTurn() + { + if ( turn->Text->Equals( oString ) ) + return true; + + return false; + } + + +public: + + [STAThread] + static void Main() + { + Application::Run( gcnew TicTacToe ); + } + +}; + +int main() +{ + TicTacToe::Main(); +} + +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CPP/programmaticsizing.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CPP/programmaticsizing.cpp new file mode 100644 index 0000000000..65caf14ff3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CPP/programmaticsizing.cpp @@ -0,0 +1,281 @@ + + +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Collections; +using namespace System::ComponentModel; +using namespace System::Windows::Forms; +public ref class ProgrammaticSizing: public System::Windows::Forms::Form +{ +private: + FlowLayoutPanel^ flowLayoutPanel1; + Button^ button1; + Button^ button2; + Button^ button3; + Button^ button4; + Button^ button5; + Button^ button6; + Button^ button7; + Button^ button8; + Button^ button9; + Button^ button10; + Button^ button11; + +public: + ProgrammaticSizing() + { + button1 = gcnew Button; + button2 = gcnew Button; + button3 = gcnew Button; + button4 = gcnew Button; + button5 = gcnew Button; + button6 = gcnew Button; + button7 = gcnew Button; + button8 = gcnew Button; + button9 = gcnew Button; + button10 = gcnew Button; + button11 = gcnew Button; + thirdColumnHeader = "Main Ingredients"; + boringMeatloaf = "ground beef"; + boringMeatloafRanking = "*"; + otherResturant = "Gomes's Saharan Sushi"; + InitializeComponent(); + AddDirections(); + this->Load += gcnew EventHandler( this, &ProgrammaticSizing::InitializeDataGridView ); + AddButton( button1, "Reset", gcnew EventHandler( this, &ProgrammaticSizing::ResetToDisorder ) ); + AddButton( button2, "Change Column 3 Header", gcnew EventHandler( this, &ProgrammaticSizing::ChangeColumn3Header ) ); + AddButton( button3, "Change Meatloaf Recipe", gcnew EventHandler( this, &ProgrammaticSizing::ChangeMeatloafRecipe ) ); + AddButton( button10, "Change Resturant 2", gcnew EventHandler( this, &ProgrammaticSizing::ChangeResturant ) ); + AddButtonsForProgrammaticResizing(); + } + + +private: + void InitializeComponent() + { + this->flowLayoutPanel1 = gcnew FlowLayoutPanel; + this->flowLayoutPanel1->FlowDirection = FlowDirection::TopDown; + this->flowLayoutPanel1->Location = Point(492,0); + this->flowLayoutPanel1->AutoSize = true; + this->AutoSize = true; + this->Controls->Add( this->flowLayoutPanel1 ); + this->Text = this->GetType()->Name; + } + + void AddDirections() + { + Label^ directions = gcnew Label; + directions->AutoSize = true; + String^ newLine = Environment::NewLine; + directions->Text = String::Format( "Press the buttons that start {0}with 'Change' to see how different sizing {1}modes deal with content changes.", newLine, newLine ); + flowLayoutPanel1->Controls->Add( directions ); + } + + System::Drawing::Size startingSize; + String^ thirdColumnHeader; + String^ boringMeatloaf; + String^ boringMeatloafRanking; + bool boringRecipe; + bool shortMode; + DataGridView^ dataGridView1; + String^ otherResturant; + void InitializeDataGridView( Object^ /*sender*/, EventArgs^ /*ignoredToo*/ ) + { + this->dataGridView1 = gcnew DataGridView; + this->dataGridView1->Location = Point(0,0); + this->dataGridView1->Size = System::Drawing::Size( 292, 266 ); + this->Controls->Add( this->dataGridView1 ); + startingSize = System::Drawing::Size( 450, 400 ); + dataGridView1->Size = startingSize; + AddColumns(); + PopulateRows(); + shortMode = false; + boringRecipe = true; + } + + void AddColumns() + { + dataGridView1->ColumnCount = 4; + dataGridView1->ColumnHeadersVisible = true; + DataGridViewCellStyle ^ columnHeaderStyle = gcnew DataGridViewCellStyle; + columnHeaderStyle->BackColor = Color::Aqua; + columnHeaderStyle->Font = gcnew System::Drawing::Font( "Verdana",10,FontStyle::Bold ); + dataGridView1->ColumnHeadersDefaultCellStyle = columnHeaderStyle; + dataGridView1->Columns[ 0 ]->Name = "Recipe"; + dataGridView1->Columns[ 1 ]->Name = "Category"; + dataGridView1->Columns[ 2 ]->Name = thirdColumnHeader; + dataGridView1->Columns[ 3 ]->Name = "Rating"; + } + + void PopulateRows() + { + array^row1 = {"Meatloaf","Main Dish",boringMeatloaf,boringMeatloafRanking}; + array^row2 = {"Key Lime Pie","Dessert","lime juice, evaporated milk","****"}; + array^row3 = {"Orange-Salsa Pork Chops","Main Dish","pork chops, salsa, orange juice","****"}; + array^row4 = {"Black Bean and Rice Salad","Salad","black beans, brown rice","****"}; + array^row5 = {"Chocolate Cheesecake","Dessert","cream cheese","***"}; + array^row6 = {"Black Bean Dip","Appetizer","black beans, sour cream","***"}; + array^rows = {row1,row2,row3,row4,row5,row6}; + IEnumerator^ myEnum = rows->GetEnumerator(); + while ( myEnum->MoveNext() ) + { + array^row = safe_cast^>(myEnum->Current); + dataGridView1->Rows->Add( row ); + } + + IEnumerator^ myEnum1 = safe_cast(dataGridView1->Rows)->GetEnumerator(); + while ( myEnum1->MoveNext() ) + { + DataGridViewRow ^ row = safe_cast(myEnum1->Current); + if ( row->IsNewRow ) + break; + row->HeaderCell->Value = String::Format( "Resturant {0}", row->Index ); + } + } + + void AddButton( Button^ button, String^ buttonLabel, EventHandler^ handler ) + { + button->Text = buttonLabel; + button->AutoSize = true; + flowLayoutPanel1->Controls->Add( button ); + button->Click += handler; + } + + void ResetToDisorder( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + Controls->Remove( dataGridView1 ); + dataGridView1->Size = startingSize; + dataGridView1->DataGridView::~DataGridView(); + InitializeDataGridView( nullptr, nullptr ); + } + + void ChangeColumn3Header( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + Toggle( &shortMode ); + if ( shortMode ) + dataGridView1->Columns[ 2 ]->HeaderText = "S"; + else + dataGridView1->Columns[ 2 ]->HeaderText = thirdColumnHeader; + } + + void Toggle( interior_ptr toggleThis ) + { + *toggleThis = ! *toggleThis; + } + + void ChangeMeatloafRecipe( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + Toggle( &boringRecipe ); + if ( boringRecipe ) + SetMeatloaf( boringMeatloaf, boringMeatloafRanking ); + else + { + String^ greatMeatloafRecipe = "1 lb. lean ground beef, " + "1/2 cup bread crumbs, 1/4 cup ketchup," + "1/3 tsp onion powder, " + "1 clove of garlic, 1/2 pack onion soup mix " + " dash of your favorite BBQ Sauce"; + SetMeatloaf( greatMeatloafRecipe, "***" ); + } + } + + void SetMeatloaf( String^ recipe, String^ rating ) + { + dataGridView1->Rows[ 0 ]->Cells[ 2 ]->Value = recipe; + dataGridView1->Rows[ 0 ]->Cells[ 3 ]->Value = rating; + } + + void ChangeResturant( Object^ /*sender*/, EventArgs^ /*ignored*/ ) + { + if ( dataGridView1->Rows[ 2 ]->HeaderCell->Value == otherResturant ) + dataGridView1->Rows[ 2 ]->HeaderCell->Value = "Resturant 2"; + else + dataGridView1->Rows[ 2 ]->HeaderCell->Value = otherResturant; + } + + void AddButtonsForProgrammaticResizing() + { + AddButton( button4, "Size Third Column", gcnew EventHandler( this, &ProgrammaticSizing::SizeThirdColumnHeader ) ); + AddButton( button5, "Size Column Headers", gcnew EventHandler( this, &ProgrammaticSizing::SizeColumnHeaders ) ); + AddButton( button6, "Size All Columns", gcnew EventHandler( this, &ProgrammaticSizing::SizeAllColumns ) ); + AddButton( button7, "Size Third Row", gcnew EventHandler( this, &ProgrammaticSizing::SizeThirdRow ) ); + AddButton( button8, "Size First Row Header Using All Headers", gcnew EventHandler( this, &ProgrammaticSizing::SizeFirstRowHeaderToAllHeaders ) ); + AddButton( button9, "Size All Rows and Row Headers", gcnew EventHandler( this, &ProgrammaticSizing::SizeAllRowsAndTheirHeaders ) ); + AddButton( button11, "Size All Rows ", gcnew EventHandler( this, &ProgrammaticSizing::SizeAllRows ) ); + } + + + // + void SizeThirdColumnHeader( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->AutoResizeColumn(2, DataGridViewAutoSizeColumnMode::ColumnHeader); + } + + + // + // + void SizeColumnHeaders( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + int columnNumber; + bool dontChangeColumnWidth; + bool dontChangeRowHeadersWidth; + dataGridView1->AutoResizeColumnHeadersHeight(2); + } + + + // + // + void SizeAllColumns( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->AutoResizeColumns( DataGridViewAutoSizeColumnsMode::AllCells ); + } + + + // + // + void SizeThirdRow( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->AutoResizeRow(2, DataGridViewAutoSizeRowMode::AllCellsExceptHeader); + } + + + // + // + void SizeFirstRowHeaderToAllHeaders( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->AutoResizeRowHeadersWidth(0, DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders); + } + + + // + // + void SizeAllRowsAndTheirHeaders( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->AutoResizeRows(DataGridViewAutoSizeRowsMode::AllCells); + } + + + // + // + void SizeAllRows( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + dataGridView1->AutoResizeRows(DataGridViewAutoSizeRowsMode::AllCellsExceptHeaders); + } + + // +}; + + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run( gcnew ProgrammaticSizing ); +} + +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CPP/datagridviewrowtemplate.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CPP/datagridviewrowtemplate.cpp new file mode 100644 index 0000000000..2e3ca96ced --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CPP/datagridviewrowtemplate.cpp @@ -0,0 +1,48 @@ + +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; +ref class Form1: public Form +{ +private: + DataGridView^ dataGridView1; + +public: + static void Main() + { + Application::Run( gcnew Form1 ); + } + + Form1() + { + this->dataGridView1->Dock = DockStyle::Fill; + this->Controls->Add( this->dataGridView1 ); + this->Load += gcnew EventHandler( this, &Form1::Form1_Load ); + dataGridView1 = gcnew DataGridView; + } + + void Form1_Load( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + + // + DataGridViewRow^ row = this->dataGridView1->RowTemplate; + row->DefaultCellStyle->BackColor = Color::Bisque; + row->Height = 35; + row->MinimumHeight = 20; + + // + this->dataGridView1->ColumnCount = 5; + this->dataGridView1->RowCount = 10; + } + +}; + +int main() +{ + Form1::Main(); +} + diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp new file mode 100644 index 0000000000..24331430fe --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CPP/virtualmode.cpp @@ -0,0 +1,355 @@ +// +// +#using +#using +#using + +using namespace System; +using namespace System::Windows::Forms; + +// +public ref class Customer +{ +private: + String^ companyNameValue; + String^ contactNameValue; + +public: + Customer() + { + + // Leave fields empty. + } + + Customer( String^ companyName, String^ contactName ) + { + companyNameValue = companyName; + contactNameValue = contactName; + } + + + property String^ CompanyName + { + String^ get() + { + return companyNameValue; + } + + void set( String^ value ) + { + companyNameValue = value; + } + + } + + property String^ ContactName + { + String^ get() + { + return contactNameValue; + } + + void set( String^ value ) + { + contactNameValue = value; + } + + } + +}; +// + +// +public ref class Form1: public Form +{ +private: + DataGridView^ dataGridView1; + + // Declare an ArrayList to serve as the data store. + System::Collections::ArrayList^ customers; + + // Declare a Customer object to store data for a row being edited. + Customer^ customerInEdit; + + // Declare a variable to store the index of a row being edited. + // A value of -1 indicates that there is no row currently in edit. + int rowInEdit; + + // Declare a variable to indicate the commit scope. + // Set this value to false to use cell-level commit scope. + bool rowScopeCommit; + +public: + static void Main() + { + Application::Run( gcnew Form1 ); + } + + Form1() + { + dataGridView1 = gcnew DataGridView; + customers = gcnew System::Collections::ArrayList; + rowInEdit = -1; + rowScopeCommit = true; + + // Initialize the form. + this->dataGridView1->Dock = DockStyle::Fill; + this->Controls->Add( this->dataGridView1 ); + this->Load += gcnew EventHandler( this, &Form1::Form1_Load ); + } + +private: + // + // + void Form1_Load( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + + // Enable virtual mode. + this->dataGridView1->VirtualMode = true; + + // Connect the virtual-mode events to event handlers. + this->dataGridView1->CellValueNeeded += gcnew + DataGridViewCellValueEventHandler( this, &Form1::dataGridView1_CellValueNeeded ); + this->dataGridView1->CellValuePushed += gcnew + DataGridViewCellValueEventHandler( this, &Form1::dataGridView1_CellValuePushed ); + this->dataGridView1->NewRowNeeded += gcnew + DataGridViewRowEventHandler( this, &Form1::dataGridView1_NewRowNeeded ); + this->dataGridView1->RowValidated += gcnew + DataGridViewCellEventHandler( this, &Form1::dataGridView1_RowValidated ); + this->dataGridView1->RowDirtyStateNeeded += gcnew + QuestionEventHandler( this, &Form1::dataGridView1_RowDirtyStateNeeded ); + this->dataGridView1->CancelRowEdit += gcnew + QuestionEventHandler( this, &Form1::dataGridView1_CancelRowEdit ); + this->dataGridView1->UserDeletingRow += gcnew + DataGridViewRowCancelEventHandler( this, &Form1::dataGridView1_UserDeletingRow ); + + // Add columns to the DataGridView. + DataGridViewTextBoxColumn^ companyNameColumn = gcnew DataGridViewTextBoxColumn; + companyNameColumn->HeaderText = L"Company Name"; + companyNameColumn->Name = L"Company Name"; + DataGridViewTextBoxColumn^ contactNameColumn = gcnew DataGridViewTextBoxColumn; + contactNameColumn->HeaderText = L"Contact Name"; + contactNameColumn->Name = L"Contact Name"; + this->dataGridView1->Columns->Add( companyNameColumn ); + this->dataGridView1->Columns->Add( contactNameColumn ); + this->dataGridView1->AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode::AllCells; + + // Add some sample entries to the data store. + this->customers->Add( gcnew Customer( L"Bon app'",L"Laurence Lebihan" ) ); + this->customers->Add( gcnew Customer( L"Bottom-Dollar Markets",L"Elizabeth Lincoln" ) ); + this->customers->Add( gcnew Customer( L"B's Beverages",L"Victoria Ashworth" ) ); + + // Set the row count, including the row for new records. + this->dataGridView1->RowCount = 4; + } + // + + // + void dataGridView1_CellValueNeeded( Object^ /*sender*/, + System::Windows::Forms::DataGridViewCellValueEventArgs^ e ) + { + Customer^ customerTmp = nullptr; + + // Store a reference to the Customer object for the row being painted. + if ( e->RowIndex == rowInEdit ) + { + customerTmp = this->customerInEdit; + } + else + { + customerTmp = dynamic_cast(this->customers[ e->RowIndex ]); + } + + // Set the cell value to paint using the Customer object retrieved. + int switchcase = 0; + if ( (this->dataGridView1->Columns[ e->ColumnIndex ]->Name)->Equals( L"Company Name" ) ) + switchcase = 1; + else + if ( (this->dataGridView1->Columns[ e->ColumnIndex ]->Name)->Equals( L"Contact Name" ) ) + switchcase = 2; + + + switch ( switchcase ) + { + case 1: + e->Value = customerTmp->CompanyName; + break; + + case 2: + e->Value = customerTmp->ContactName; + break; + } + } + + + // + // + void dataGridView1_CellValuePushed( Object^ /*sender*/, + System::Windows::Forms::DataGridViewCellValueEventArgs^ e ) + { + Customer^ customerTmp = nullptr; + + // Store a reference to the Customer object for the row being edited. + if ( e->RowIndex < this->customers->Count ) + { + + // If the user is editing a new row, create a new Customer object. + if ( this->customerInEdit == nullptr ) + { + this->customerInEdit = gcnew Customer( + (dynamic_cast(this->customers[ e->RowIndex ]))->CompanyName, + (dynamic_cast(this->customers[ e->RowIndex ])->ContactName) ); + } + + customerTmp = this->customerInEdit; + this->rowInEdit = e->RowIndex; + } + else + { + customerTmp = this->customerInEdit; + } + + + // Set the appropriate Customer property to the cell value entered. + int switchcase = 0; + if ( (this->dataGridView1->Columns[ e->ColumnIndex ]->Name)->Equals( L"Company Name" ) ) + switchcase = 1; + else + if ( (this->dataGridView1->Columns[ e->ColumnIndex ]->Name)->Equals( L"Contact Name" ) ) + switchcase = 2; + + + switch ( switchcase ) + { + case 1: + customerTmp->CompanyName = dynamic_cast(e->Value); + break; + + case 2: + customerTmp->ContactName = dynamic_cast(e->Value); + break; + } + } + + + // + // + void dataGridView1_NewRowNeeded( Object^ /*sender*/, + System::Windows::Forms::DataGridViewRowEventArgs^ /*e*/ ) + { + + // Create a new Customer object when the user edits + // the row for new records. + this->customerInEdit = gcnew Customer; + this->rowInEdit = this->dataGridView1->Rows->Count - 1; + } + + + // + // + void dataGridView1_RowValidated( Object^ /*sender*/, + System::Windows::Forms::DataGridViewCellEventArgs^ e ) + { + + // Save row changes if any were made and release the edited + // Customer object if there is one. + if ( e->RowIndex >= this->customers->Count && e->RowIndex != this->dataGridView1->Rows->Count - 1 ) + { + + // Add the new Customer object to the data store. + this->customers->Add( this->customerInEdit ); + this->customerInEdit = nullptr; + this->rowInEdit = -1; + } + else + if ( this->customerInEdit != nullptr && e->RowIndex < this->customers->Count ) + { + + // Save the modified Customer object in the data store. + this->customers[ e->RowIndex ] = this->customerInEdit; + this->customerInEdit = nullptr; + this->rowInEdit = -1; + } + else + if ( this->dataGridView1->ContainsFocus ) + { + this->customerInEdit = nullptr; + this->rowInEdit = -1; + } + } + + + // + // + void dataGridView1_RowDirtyStateNeeded( Object^ /*sender*/, + System::Windows::Forms::QuestionEventArgs^ e ) + { + if ( !rowScopeCommit ) + { + + // In cell-level commit scope, indicate whether the value + // of the current cell has been modified. + e->Response = this->dataGridView1->IsCurrentCellDirty; + } + } + + + // + // + void dataGridView1_CancelRowEdit( Object^ /*sender*/, + System::Windows::Forms::QuestionEventArgs^ /*e*/ ) + { + if ( this->rowInEdit == this->dataGridView1->Rows->Count - 2 && + this->rowInEdit == this->customers->Count ) + { + + // If the user has canceled the edit of a newly created row, + // replace the corresponding Customer object with a new, empty one. + this->customerInEdit = gcnew Customer; + } + else + { + + // If the user has canceled the edit of an existing row, + // release the corresponding Customer object. + this->customerInEdit = nullptr; + this->rowInEdit = -1; + } + } + + + // + // + void dataGridView1_UserDeletingRow( Object^ /*sender*/, + System::Windows::Forms::DataGridViewRowCancelEventArgs^ e ) + { + if ( e->Row->Index < this->customers->Count ) + { + + // If the user has deleted an existing row, remove the + // corresponding Customer object from the data store. + this->customers->RemoveAt( e->Row->Index ); + } + + if ( e->Row->Index == this->rowInEdit ) + { + + // If the user has deleted a newly created row, release + // the corresponding Customer object. + this->rowInEdit = -1; + this->customerInEdit = nullptr; + } + } + // + // +}; +// + +int main() +{ + Form1::Main(); +} +// + + +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/cpp/datagridviewcell.tooltiptext.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/cpp/datagridviewcell.tooltiptext.cpp new file mode 100644 index 0000000000..cd185ce9a7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/cpp/datagridviewcell.tooltiptext.cpp @@ -0,0 +1,89 @@ +#using +#using +#using +using namespace System; +using namespace System::Windows::Forms; + +ref class Form1 : public Form +{ +private: + DataGridView^ dataGridView1; + +public: + static void Main() + { + Application::Run(gcnew Form1()); + } + +public: + Form1() + { + dataGridView1 = gcnew DataGridView(); + + this->dataGridView1->Dock = DockStyle::Fill; + // Set the column header names. + this->dataGridView1->ColumnCount = 5; + this->dataGridView1->Columns[0]->Name = "Recipe"; + this->dataGridView1->Columns[1]->Name = "Category"; + this->dataGridView1->Columns[2]->Name = "Main Ingredients"; + this->dataGridView1->Columns[3]->Name = "Last Fixed"; + this->dataGridView1->Columns[4]->Name = "Rating"; + + // Populate the rows. + array^ row1 = gcnew array{"Meatloaf", + "Main Dish", "ground beef", gcnew DateTime(2000, 3, 23), "*"}; + array^ row2 = gcnew array{"Key Lime Pie", + "Dessert", "lime juice, evaporated milk", gcnew DateTime(2002, 4, 12), "****"}; + array^ row3 = gcnew array{"Orange-Salsa Pork Chops", + "Main Dish", "pork chops, salsa, orange juice", gcnew DateTime(2000, 8, 9), "****"}; + array^ row4 = gcnew array{"Black Bean and Rice Salad", + "Salad", "black beans, brown rice", gcnew DateTime(1999, 5, 7), "****"}; + array^ row5 = gcnew array{"Chocolate Cheesecake", + "Dessert", "cream cheese", gcnew DateTime(2003, 3, 12), "***"}; + array^ row6 = gcnew array{"Black Bean Dip", "Appetizer", + "black beans, sour cream", gcnew DateTime(2003, 12, 23), "***"}; + array^ rows = gcnew array { row1, row2, row3, row4, row5, row6 }; + + for each (array^ rowArray in rows) + { + this->dataGridView1->Rows->Add(rowArray); + } + this->Controls->Add(this->dataGridView1); + this->dataGridView1->CellFormatting += gcnew DataGridViewCellFormattingEventHandler(this, &Form1::dataGridView1_CellFormatting); + } + + + // + // Sets the ToolTip text for cells in the Rating column. + void dataGridView1_CellFormatting(Object^ /*sender*/, + DataGridViewCellFormattingEventArgs^ e) + { + if ( (e->ColumnIndex == this->dataGridView1->Columns["Rating"]->Index) + && e->Value != nullptr ) + { + DataGridViewCell^ cell = + this->dataGridView1->Rows[e->RowIndex]->Cells[e->ColumnIndex]; + if (e->Value->Equals("*")) + { + cell->ToolTipText = "very bad"; + } + else if (e->Value->Equals("**")) + { + cell->ToolTipText = "bad"; + } + else if (e->Value->Equals("***")) + { + cell->ToolTipText = "good"; + } + else if (e->Value->Equals("****")) + { + cell->ToolTipText = "very good"; + } + } + } + // +}; + +int main(){ + Form1::Main(); +} diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/form1.cpp new file mode 100644 index 0000000000..ea36b703b2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/form1.cpp @@ -0,0 +1,45 @@ +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +namespace DetermineModifierKey +{ + public ref class Form1 : public Form + { + private: + TextBox^ textBox1; + + public: + Form1() + { + textBox1 = gcnew TextBox(); + textBox1->KeyPress += + gcnew KeyPressEventHandler(this, &Form1::textBox1_KeyPress); + this->Controls->Add(textBox1); + } + + // + private: + void textBox1_KeyPress(Object^ sender, KeyPressEventArgs^ e) + { + if ((Control::ModifierKeys & Keys::Shift) == Keys::Shift) + { + MessageBox::Show("Pressed " + Keys::Shift.ToString()); + } + } + // + }; +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew DetermineModifierKey::Form1()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/makefile new file mode 100644 index 0000000000..cbfe888c1e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.DetermineModifierKey.exe : form1.cpp + cl /clr:pure /FeSystem.Windows.Forms.DetermineModifierKey.exe form1.cpp \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/form1.cpp new file mode 100644 index 0000000000..6be8f69a22 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/form1.cpp @@ -0,0 +1,139 @@ +// This sample compiles a set of miscellaneous code snippets that demonstrate +// different levels of user input control. + +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; +using namespace System::Security::Permissions; + +namespace KeyboardInputForm +{ + public ref class Form1 sealed: public Form, public IMessageFilter + { + // The following Windows message value is defined in Winuser.h. + private: + static const int WM_KEYDOWN = 0x100; + private: + TextBox^ inputTextBox; + public: + Form1() + { + inputTextBox = gcnew TextBox(); + this->AutoSize = true; + Application::AddMessageFilter(this); + FlowLayoutPanel^ panel = gcnew FlowLayoutPanel(); + panel->AutoSize = true; + panel->FlowDirection = FlowDirection::TopDown; + panel->Controls->Add(gcnew Button()); + panel->Controls->Add(gcnew RadioButton()); + panel->Controls->Add(inputTextBox); + this->Controls->Add(panel); + this->KeyPreview = true; + this->KeyPress += + gcnew KeyPressEventHandler(this, &Form1::Form1_KeyPress); + inputTextBox->KeyPress += + gcnew KeyPressEventHandler(this, + &Form1::inputTextBox_KeyPress); + } + + // + // Detect all numeric characters at the + // application level and consume 0. + [SecurityPermission(SecurityAction::LinkDemand, + Flags=SecurityPermissionFlag::UnmanagedCode)] + virtual bool PreFilterMessage(Message% m) + { + // Detect key down messages. + if (m.Msg == WM_KEYDOWN) + { + Keys keyCode = (Keys)((int)m.WParam) & Keys::KeyCode; + // Determine whether the keystroke is a number from the top of + // the keyboard, or a number from the keypad. + if (((keyCode >= Keys::D0) && (keyCode <= Keys::D9)) + ||((keyCode >= Keys::NumPad0) + && (keyCode <= Keys::NumPad9))) + { + MessageBox::Show( + "IMessageFilter.PreFilterMessage: '" + + keyCode.ToString() + "' pressed."); + + if ((keyCode == Keys::D0) || (keyCode == Keys::NumPad0)) + { + MessageBox::Show( + "IMessageFilter.PreFilterMessage: '" + + keyCode.ToString() + "' consumed."); + return true; + } + } + } + + // Forward all other messages. + return false; + } + // + + // + // Detect all numeric characters at the form level and consume 1, + // 4, and 7. Note that Form.KeyPreview must be set to true for this + // event handler to be called. + private: + void Form1_KeyPress(Object^ sender, KeyPressEventArgs^ e) + { + if ((e->KeyChar >= '0') && (e->KeyChar <= '9')) + { + MessageBox::Show("Form.KeyPress: '" + + e->KeyChar.ToString() + "' pressed."); + + switch (e->KeyChar) + { + case '1': + case '4': + case '7': + MessageBox::Show("Form.KeyPress: '" + + e->KeyChar.ToString() + "' consumed."); + e->Handled = true; + break; + } + } + } + // + + // + // Detect all numeric characters at the TextBox level and consume + // 2, 5, and 8. + private: + void inputTextBox_KeyPress(Object^ sender, KeyPressEventArgs^ e) + { + if ((e->KeyChar >= '0') && (e->KeyChar <= '9')) + { + MessageBox::Show("Control.KeyPress: '" + + e->KeyChar.ToString() + "' pressed."); + + switch (e->KeyChar) + { + case '2': + case '5': + case '8': + MessageBox::Show("Control.KeyPress: '" + + e->KeyChar.ToString() + "' consumed."); + e->Handled = true; + break; + } + } + } + // + }; +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew KeyboardInputForm::Form1()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/makefile new file mode 100644 index 0000000000..8c81e9ef4a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.KeyboardInputForm.exe: form1.cpp + cl /FeSystem.Windows.Forms.KeyboardInputForm.exe /clr:pure form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/DemoFlowLayout.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/DemoFlowLayout.cpp new file mode 100644 index 0000000000..8e76df324e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/DemoFlowLayout.cpp @@ -0,0 +1,134 @@ +// +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::Drawing; +using namespace System::Text; +using namespace System::Windows::Forms; +using namespace System::Windows::Forms::Layout; + +// +// This class demonstrates a simple custom layout engine. +public ref class DemoFlowLayout : public LayoutEngine +{ + // +public: + virtual bool Layout(Object^ container, + LayoutEventArgs^ layoutEventArgs) override + { + Control^ parent = nullptr; + try + { + parent = (Control ^) container; + } + catch (InvalidCastException^ ex) + { + throw gcnew ArgumentException( + "The parameter 'container' must be a control", "container", ex); + } + // Use DisplayRectangle so that parent.Padding is honored. + Rectangle parentDisplayRectangle = parent->DisplayRectangle; + Point nextControlLocation = parentDisplayRectangle.Location; + + for each (Control^ currentControl in parent->Controls) + { + // Only apply layout to visible controls. + if (!currentControl->Visible) + { + continue; + } + + // Respect the margin of the control: + // shift over the left and the top. + nextControlLocation.Offset(currentControl->Margin.Left, + currentControl->Margin.Top); + + // Set the location of the control. + currentControl->Location = nextControlLocation; + + // Set the autosized controls to their + // autosized heights. + if (currentControl->AutoSize) + { + currentControl->Size = currentControl->GetPreferredSize( + parentDisplayRectangle.Size); + } + + // Move X back to the display rectangle origin. + nextControlLocation.X = parentDisplayRectangle.X; + + // Increment Y by the height of the control + // and the bottom margin. + nextControlLocation.Y += currentControl->Height + + currentControl->Margin.Bottom; + } + + // Optional: Return whether or not the container's + // parent should perform layout as a result of this + // layout. Some layout engines return the value of + // the container's AutoSize property. + + return false; + } + // +}; +// + +// +// This class demonstrates a simple custom layout panel. +// It overrides the LayoutEngine property of the Panel +// control to provide a custom layout engine. +public ref class DemoFlowPanel : public Panel +{ +private: + DemoFlowLayout^ layoutEngine; + +public: + DemoFlowPanel() + { + layoutEngine = gcnew DemoFlowLayout(); + } + +public: + virtual property System::Windows::Forms::Layout::LayoutEngine^ LayoutEngine + { + System::Windows::Forms::Layout::LayoutEngine^ get() override + { + if (layoutEngine == nullptr) + { + layoutEngine = gcnew DemoFlowLayout(); + } + + return layoutEngine; + } + } +}; +// + +// + +public ref class TestForm : public Form +{ +public: + TestForm() + { + Panel^ testPanel = gcnew DemoFlowPanel(); + for (int i = 0; i < 10; i ++) + { + Button^ b = gcnew Button(); + testPanel->Controls->Add(b); + b->Text = i.ToString( + System::Globalization::CultureInfo::CurrentCulture); + } + this->Controls->Add(testPanel); + } +}; + +[STAThread] +int main() +{ + Application::Run(gcnew TestForm()); +} diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/makefile new file mode 100644 index 0000000000..67b65c2cba --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.Layout.LayoutEngine.dll: DemoFlowLayout.cpp + cl /FeSystem.Windows.Forms.Layout.LayoutEngine.exe /clr:pure DemoFlowLayout.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp new file mode 100644 index 0000000000..0e1cfe242a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp @@ -0,0 +1,160 @@ + + +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; +public ref class ListViewInsertionMarkExample: public Form +{ +private: + ListView^ myListView; + +public: + + // + ListViewInsertionMarkExample() + { + // Initialize myListView. + myListView = gcnew ListView; + myListView->Dock = DockStyle::Fill; + myListView->View = View::LargeIcon; + myListView->MultiSelect = false; + myListView->ListViewItemSorter = gcnew ListViewIndexComparer; + + // Initialize the insertion mark. + myListView->InsertionMark->Color = Color::Green; + + // Add items to myListView. + myListView->Items->Add( "zero" ); + myListView->Items->Add( "one" ); + myListView->Items->Add( "two" ); + myListView->Items->Add( "three" ); + myListView->Items->Add( "four" ); + myListView->Items->Add( "five" ); + + // Initialize the drag-and-drop operation when running + // under Windows XP or a later operating system. + if ( System::Environment::OSVersion->Version->Major > 5 || (System::Environment::OSVersion->Version->Major == 5 && System::Environment::OSVersion->Version->Minor >= 1) ) + { + myListView->AllowDrop = true; + myListView->ItemDrag += gcnew ItemDragEventHandler( this, &ListViewInsertionMarkExample::myListView_ItemDrag ); + myListView->DragEnter += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragEnter ); + myListView->DragOver += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragOver ); + myListView->DragLeave += gcnew EventHandler( this, &ListViewInsertionMarkExample::myListView_DragLeave ); + myListView->DragDrop += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragDrop ); + } + + // Initialize the form. + this->Text = "ListView Insertion Mark Example"; + this->Controls->Add( myListView ); + } + +private: + + // + // Starts the drag-and-drop operation when an item is dragged. + void myListView_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e ) + { + myListView->DoDragDrop( e->Item, DragDropEffects::Move ); + } + + // Sets the target drop effect. + void myListView_DragEnter( Object^ /*sender*/, DragEventArgs^ e ) + { + e->Effect = e->AllowedEffect; + } + + // + // Moves the insertion mark as the item is dragged. + void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e ) + { + // Retrieve the client coordinates of the mouse pointer. + Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) ); + + // Retrieve the index of the item closest to the mouse pointer. + int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint ); + + // Confirm that the mouse pointer is not over the dragged item. + if ( targetIndex > -1 ) + { + // Determine whether the mouse pointer is to the left or + // the right of the midpoint of the closest item and set + // the InsertionMark.AppearsAfterItem property accordingly. + Rectangle itemBounds = myListView->GetItemRect( targetIndex ); + if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) ) + { + myListView->InsertionMark->AppearsAfterItem = true; + } + else + { + myListView->InsertionMark->AppearsAfterItem = false; + } + } + + // Set the location of the insertion mark. If the mouse is + // over the dragged item, the targetIndex value is -1 and + // the insertion mark disappears. + myListView->InsertionMark->Index = targetIndex; + } + + // + // Removes the insertion mark when the mouse leaves the control. + void myListView_DragLeave( Object^ /*sender*/, EventArgs^ /*e*/ ) + { + myListView->InsertionMark->Index = -1; + } + + // Moves the item to the location of the insertion mark. + void myListView_DragDrop( Object^ /*sender*/, DragEventArgs^ e ) + { + // Retrieve the index of the insertion mark; + int targetIndex = myListView->InsertionMark->Index; + + // If the insertion mark is not visible, exit the method. + if ( targetIndex == -1 ) + { + return; + } + + // If the insertion mark is to the right of the item with + // the corresponding index, increment the target index. + if ( myListView->InsertionMark->AppearsAfterItem ) + { + targetIndex++; + } + + // Retrieve the dragged item. + ListViewItem^ draggedItem = dynamic_cast(e->Data->GetData( ListViewItem::typeid )); + + // Insert a copy of the dragged item at the target index. + // A copy must be inserted before the original item is removed + // to preserve item index values. + myListView->Items->Insert( targetIndex, dynamic_cast(draggedItem->Clone()) ); + + // Remove the original copy of the dragged item. + myListView->Items->Remove( draggedItem ); + + } + + // Sorts ListViewItem objects by index. + ref class ListViewIndexComparer: public System::Collections::IComparer + { + public: + virtual int Compare( Object^ x, Object^ y ) + { + return (dynamic_cast(x))->Index - (dynamic_cast(y))->Index; + } + }; +}; + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run( gcnew ListViewInsertionMarkExample ); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CPP/listviewtilingexample.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CPP/listviewtilingexample.cpp new file mode 100644 index 0000000000..aca6650783 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CPP/listviewtilingexample.cpp @@ -0,0 +1,88 @@ + + +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +public ref class ListViewTilingExample: public Form +{ +private: + ImageList^ myImageList; + +public: + ListViewTilingExample() + { + // Initialize myListView. + ListView^ myListView = gcnew ListView; + myListView->Dock = DockStyle::Fill; + myListView->View = View::Tile; + + // Initialize the tile size. + myListView->TileSize = System::Drawing::Size( 400, 45 ); + + // Initialize the item icons. + myImageList = gcnew ImageList; + System::Drawing::Icon^ myIcon = gcnew System::Drawing::Icon( "book.ico" ); + try + { + myImageList->Images->Add( myIcon ); + } + finally + { + if ( myIcon ) + delete safe_cast(myIcon); + } + + myImageList->ImageSize = System::Drawing::Size( 32, 32 ); + myListView->LargeImageList = myImageList; + + // Add column headers so the subitems will appear. + array^temp0 = {gcnew ColumnHeader,gcnew ColumnHeader,gcnew ColumnHeader}; + myListView->Columns->AddRange( temp0 ); + + // Create items and add them to myListView. + array^temp1 = {"Programming Windows","Petzold, Charles","1998"}; + ListViewItem^ item0 = gcnew ListViewItem( temp1,0 ); + array^temp2 = {"Code: The Hidden Language of Computer Hardware and Software","Petzold, Charles","2000"}; + ListViewItem^ item1 = gcnew ListViewItem( temp2,0 ); + array^temp3 = {"Programming Windows with C#","Petzold, Charles","2001"}; + ListViewItem^ item2 = gcnew ListViewItem( temp3,0 ); + array^temp4 = {"Coding Techniques for Microsoft Visual Basic .NET","Connell, John","2001"}; + ListViewItem^ item3 = gcnew ListViewItem( temp4,0 ); + array^temp5 = {"C# for Java Developers","Jones, Allen & Freeman, Adam","2002"}; + ListViewItem^ item4 = gcnew ListViewItem( temp5,0 ); + array^temp6 = {"Microsoft .NET XML Web Services Step by Step","Jones, Allen & Freeman, Adam","2002"}; + ListViewItem^ item5 = gcnew ListViewItem( temp6,0 ); + array^temp7 = {item0,item1,item2,item3,item4,item5}; + myListView->Items->AddRange( temp7 ); + + // Initialize the form. + this->Controls->Add( myListView ); + this->Size = System::Drawing::Size( 430, 330 ); + this->Text = "ListView Tiling Example"; + } + +protected: + + // Clean up any resources being used. + ~ListViewTilingExample() + { + if ( myImageList != nullptr ) + { + delete myImageList; + } + } +}; + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run( gcnew ListViewTilingExample ); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/form1.cpp new file mode 100644 index 0000000000..be4243b738 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/form1.cpp @@ -0,0 +1,188 @@ +#pragma region Using directives + +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +#pragma endregion + +namespace ListViewFindItemWithTextHowTo +{ + public ref class Form1 : public Form + { + public: + Form1() + { + + InitializeComponent(); + + //InitializeTextSearchListView(); + InitializeLocationSearchListView(); + } + + /// + /// Required designer variable. + /// + private: + System::ComponentModel::IContainer^ components; + + /// + /// Clean up any resources being used. + /// + protected: + ~Form1() + { + if (components != nullptr) + { + delete components; + } + } + +#pragma 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() + { + // + // Form1 + // + this->AutoScaleBaseSize = System::Drawing::Size(5, 13); + this->ClientSize = System::Drawing::Size(292, 266); + this->Name = "Form1"; + this->Text = "Form1"; + + } + +#pragma endregion + + // + private: + ListView^ textListView; + TextBox^ searchBox; + + private: + void InitializeTextSearchListView() + { + textListView = gcnew ListView(); + searchBox = gcnew TextBox(); + searchBox->Location = Point(150, 20); + textListView->Scrollable = true; + textListView->Width = 100; + + // Set the View to list to use the FindItemWithText method. + textListView->View = View::List; + + // Populate the ListViewWithItems + textListView->Items->AddRange(gcnew array{ + gcnew ListViewItem("Amy Alberts"), + gcnew ListViewItem("Amy Recker"), + gcnew ListViewItem("Erin Hagens"), + gcnew ListViewItem("Barry Johnson"), + gcnew ListViewItem("Jay Hamlin"), + gcnew ListViewItem("Brian Valentine"), + gcnew ListViewItem("Brian Welker"), + gcnew ListViewItem("Daniel Weisman") }); + + // Handle the TextChanged to get the text for our search. + searchBox->TextChanged += gcnew EventHandler(this, + &Form1::searchBox_TextChanged); + + // Add the controls to the form. + this->Controls->Add(textListView); + this->Controls->Add(searchBox); + } + + // + private: + void searchBox_TextChanged(Object^ sender, EventArgs^ e) + { + // Call FindItemWithText with the contents of the textbox. + ListViewItem^ foundItem = + textListView->FindItemWithText(searchBox->Text, false, 0, true); + if (foundItem != nullptr) + { + textListView->TopItem = foundItem; + } + } + // + // + + // + ListView^ iconListView; + TextBox^ previousItemBox; + + private: + void InitializeLocationSearchListView() + { + previousItemBox = gcnew TextBox(); + iconListView = gcnew ListView(); + previousItemBox->Location = Point(150, 20); + + // Create an image list for the icon ListView. + iconListView->SmallImageList = gcnew ImageList(); + + // Add an image to the ListView small icon list. + iconListView->SmallImageList->Images->Add( + gcnew Bitmap(Control::typeid, "Edit.bmp")); + + // Set the view to small icon and add some items with the image + // in the image list. + iconListView->View = View::SmallIcon; + iconListView->Items->AddRange(gcnew array{ + gcnew ListViewItem("Amy Alberts", 0), + gcnew ListViewItem("Amy Recker", 0), + gcnew ListViewItem("Erin Hagens", 0), + gcnew ListViewItem("Barry Johnson", 0), + gcnew ListViewItem("Jay Hamlin", 0), + gcnew ListViewItem("Brian Valentine", 0), + gcnew ListViewItem("Brian Welker", 0), + gcnew ListViewItem("Daniel Weisman", 0) }); + this->Controls->Add(iconListView); + this->Controls->Add(previousItemBox); + + // Handle the MouseDown event to capture user input. + iconListView->MouseDown += gcnew MouseEventHandler( + this, &Form1::iconListView_MouseDown); + } + + // + void iconListView_MouseDown(Object^ sender, MouseEventArgs^ e) + { + // Find the next item up from where the user clicked. + ListViewItem^ foundItem = iconListView->FindNearestItem( + SearchDirectionHint::Up, e->X, e->Y); + + // Display the results in a textbox.. + if (foundItem != nullptr) + { + previousItemBox->Text = foundItem->Text; + } + else + { + previousItemBox->Text = "No item found"; + } + } + // + // + }; +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew ListViewFindItemWithTextHowTo::Form1()); +} + diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/makefile new file mode 100644 index 0000000000..db900e12f0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.ListViewFindItems.exe: form1.cpp + cl /FeSystem.Windows.Forms.ListViewFindItems.exe /clr:pure form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/form1.cpp new file mode 100644 index 0000000000..4d26196f3b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/form1.cpp @@ -0,0 +1,88 @@ + +// +#using +#using +#using + +using namespace System; +using namespace System::Runtime::InteropServices; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +namespace SimulateKeyPress +{ + + public ref class Form1 : public Form + { + public: + Form1() + { + Button^ button1 = gcnew Button(); + button1->Location = Point(10, 10); + button1->TabIndex = 0; + button1->Text = "Click to automate Calculator"; + button1->AutoSize = true; + button1->Click += gcnew EventHandler(this, &Form1::button1_Click); + + this->DoubleClick += gcnew EventHandler(this, + &Form1::Form1_DoubleClick); + this->Controls->Add(button1); + } + + // + // Get a handle to an application window. + public: + [DllImport("USER32.DLL", CharSet = CharSet::Unicode)] + static IntPtr FindWindow(String^ lpClassName, String^ lpWindowName); + public: + // Activate an application window. + [DllImport("USER32.DLL")] + static bool SetForegroundWindow(IntPtr hWnd); + + // Send a series of key presses to the Calculator application. + private: + void button1_Click(Object^ sender, EventArgs^ e) + { + // Get a handle to the Calculator application. The window class + // and window name were obtained using the Spy++ tool. + IntPtr calculatorHandle = FindWindow("CalcFrame", "Calculator"); + + // Verify that Calculator is a running process. + if (calculatorHandle == IntPtr::Zero) + { + MessageBox::Show("Calculator is not running."); + return; + } + + // Make Calculator the foreground application and send it + // a set of calculations. + SetForegroundWindow(calculatorHandle); + SendKeys::SendWait("111"); + SendKeys::SendWait("*"); + SendKeys::SendWait("11"); + SendKeys::SendWait("="); + } + // + + // + // Send a key to the button when the user double-clicks anywhere + // on the form. + private: + void Form1_DoubleClick(Object^ sender, EventArgs^ e) + { + // Send the enter key to the button, which triggers the click + // event for the button. This works because the tab stop of + // the button is 0. + SendKeys::Send("{ENTER}"); + } + // + }; +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew SimulateKeyPress::Form1()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/makefile new file mode 100644 index 0000000000..4a18c281b6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.SimulateKeyPress.exe: form1.cpp + cl /clr:pure /FeSystem.Windows.Forms.SimulateKeyPress.exe form1.cpp \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/form1.cpp new file mode 100644 index 0000000000..4e4820f428 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/form1.cpp @@ -0,0 +1,175 @@ +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +namespace SingleVersusDoubleClick +{ + public ref class Form1 : public Form + { + private: + Rectangle hitTestRectangle; + private: + Rectangle doubleClickRectangle; + private: + TextBox^ outputBox; + private: + Timer^ doubleClickTimer; + private: + ProgressBar^ doubleClickBar; + private: + Label^ hitTestLabel; + private: + Label^ timerLabel; + private: + bool isFirstClick; + private: + bool isDoubleClick; + private: + int milliseconds; + + public: + Form1() + { + hitTestRectangle = Rectangle(); + hitTestRectangle.Location = Point(30, 20); + hitTestRectangle.Size = System::Drawing::Size(100, 40); + + doubleClickRectangle = Rectangle(); + + outputBox = gcnew TextBox(); + outputBox->Location = Point(30, 120); + outputBox->Size = System::Drawing::Size(200, 100); + outputBox->AutoSize = false; + outputBox->Multiline = true; + + doubleClickTimer = gcnew Timer(); + doubleClickTimer->Interval = 100; + doubleClickTimer->Tick += + gcnew EventHandler(this, &Form1::doubleClickTimer_Tick); + + doubleClickBar = gcnew ProgressBar(); + doubleClickBar->Location = Point(30, 85); + doubleClickBar->Minimum = 0; + doubleClickBar->Maximum = SystemInformation::DoubleClickTime; + + hitTestLabel = gcnew Label(); + hitTestLabel->Location = Point(30, 5); + hitTestLabel->Size = System::Drawing::Size(100, 15); + hitTestLabel->Text = "Hit test rectangle:"; + + timerLabel = gcnew Label(); + timerLabel->Location = Point(30, 70); + timerLabel->Size = System::Drawing::Size(100, 15); + timerLabel->Text = "Double click timer:"; + + isFirstClick = true; + + this->Paint += gcnew PaintEventHandler(this, &Form1::Form1_Paint); + this->MouseDown += + gcnew MouseEventHandler(this, &Form1::Form1_MouseDown); + this->Controls-> + AddRange(gcnew array { doubleClickBar, outputBox, + hitTestLabel, timerLabel }); + } + + // + // Detect a valid single click or double click. + private: + void Form1_MouseDown(Object^ sender, MouseEventArgs^ e) + { + // Verify that the mouse click is in the main hit + // test rectangle. + if (!hitTestRectangle.Contains(e->Location)) + { + return; + } + + // This is the first mouse click. + if (isFirstClick) + { + isFirstClick = false; + + // Determine the location and size of the double click + // rectangle area to draw around the cursor point. + doubleClickRectangle = Rectangle( + e->X - (SystemInformation::DoubleClickSize.Width / 2), + e->Y - (SystemInformation::DoubleClickSize.Height / 2), + SystemInformation::DoubleClickSize.Width, + SystemInformation::DoubleClickSize.Height); + Invalidate(); + + // Start the double click timer. + doubleClickTimer->Start(); + } + + // This is the second mouse click. + else + { + // Verify that the mouse click is within the double click + // rectangle and is within the system-defined double + // click period. + if (doubleClickRectangle.Contains(e->Location) && + milliseconds < SystemInformation::DoubleClickTime) + { + isDoubleClick = true; + } + } + } + // + + private: + void doubleClickTimer_Tick(Object^ sender, EventArgs^ e) + { + milliseconds += 100; + doubleClickBar->Increment(100); + + // The timer has reached the double click time limit. + if (milliseconds >= SystemInformation::DoubleClickTime) + { + doubleClickTimer->Stop(); + + if (isDoubleClick) + { + outputBox->AppendText("Perform double click action"); + outputBox->AppendText(Environment::NewLine); + } + else + { + outputBox->AppendText("Perform single click action"); + outputBox->AppendText(Environment::NewLine); + } + + // Allow the MouseDown event handler to process clicks again. + isFirstClick = true; + isDoubleClick = false; + milliseconds = 0; + doubleClickBar->Value = 0; + } + } + + // Paint the hit test and double click rectangles. + private: + void Form1_Paint(Object^ sender, PaintEventArgs^ e) + { + // Draw the border of the main hit test rectangle. + e->Graphics->DrawRectangle(Pens::Black, hitTestRectangle); + + // Fill in the double click rectangle. + e->Graphics->FillRectangle(Brushes::Blue, doubleClickRectangle); + } + }; +} + + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew SingleVersusDoubleClick::Form1); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/makefile new file mode 100644 index 0000000000..93fdb590e2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.ScrollBarRenderer.exe : form1.cpp + cl /clr:pure /FeSystem.Windows.Forms.ScrollBarRenderer.exe form1.cpp \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/basicdataentryform.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/basicdataentryform.cpp new file mode 100644 index 0000000000..d64c83537f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/basicdataentryform.cpp @@ -0,0 +1,416 @@ +// +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections::Generic; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Drawing; +using namespace System::Text; +using namespace System::Windows::Forms; + +// This form demonstrates how to build a form layout that adjusts well +// when the user resizes the form. It also demonstrates a layout that +// responds well to localization. +ref class BasicDataEntryForm : public System::Windows::Forms::Form +{ +public: + BasicDataEntryForm() + { + InitializeComponent(); + components = nullptr; + } + +private: + System::ComponentModel::IContainer^ components; + +protected: + ~BasicDataEntryForm() + { + if (components != nullptr) + { + delete components; + } + } + +public: + virtual String^ ToString() override + { + return "Basic Data Entry Form"; + } + +private: + void okBtn_Click(Object^ sender, EventArgs^ e) + { + this->Close(); + } + +private: + void cancelBtn_Click(Object^ sender, EventArgs^ e) + { + this->Close(); + } + +private: + void InitializeComponent() + { + this->tableLayoutPanel1 = gcnew + System::Windows::Forms::TableLayoutPanel(); + this->lblFirstName = gcnew System::Windows::Forms::Label(); + this->lblLastName = gcnew System::Windows::Forms::Label(); + this->lblAddress1 = gcnew System::Windows::Forms::Label(); + this->lblAddress2 = gcnew System::Windows::Forms::Label(); + this->lblCity = gcnew System::Windows::Forms::Label(); + this->lblState = gcnew System::Windows::Forms::Label(); + this->lblPhoneH = gcnew System::Windows::Forms::Label(); + this->txtAddress1 = gcnew System::Windows::Forms::TextBox(); + this->txtAddress2 = gcnew System::Windows::Forms::TextBox(); + this->txtCity = gcnew System::Windows::Forms::TextBox(); + this->txtLastName = gcnew System::Windows::Forms::TextBox(); + this->maskedTxtPhoneW = gcnew System::Windows::Forms::MaskedTextBox(); + this->maskedTxtPhoneH = gcnew System::Windows::Forms::MaskedTextBox(); + this->cboState = gcnew System::Windows::Forms::ComboBox(); + this->txtFirstName = gcnew System::Windows::Forms::TextBox(); + this->lblNotes = gcnew System::Windows::Forms::Label(); + this->lblPhoneW = gcnew System::Windows::Forms::Label(); + this->richTxtNotes = gcnew System::Windows::Forms::RichTextBox(); + this->cancelBtn = gcnew System::Windows::Forms::Button(); + this->okBtn = gcnew System::Windows::Forms::Button(); + this->tableLayoutPanel1->SuspendLayout(); + this->SuspendLayout(); + // + // tableLayoutPanel1 + // + this->tableLayoutPanel1->Anchor = + System::Windows::Forms::AnchorStyles::Top | + System::Windows::Forms::AnchorStyles::Bottom| + System::Windows::Forms::AnchorStyles::Left | + System::Windows::Forms::AnchorStyles::Right; + this->tableLayoutPanel1->ColumnCount = 4; + this->tableLayoutPanel1->ColumnStyles->Add(gcnew + System::Windows::Forms::ColumnStyle()); + this->tableLayoutPanel1->ColumnStyles->Add(gcnew + System::Windows::Forms::ColumnStyle( + System::Windows::Forms::SizeType::Percent, 50.0)); + this->tableLayoutPanel1->ColumnStyles->Add(gcnew + System::Windows::Forms::ColumnStyle()); + this->tableLayoutPanel1->ColumnStyles->Add(gcnew + System::Windows::Forms::ColumnStyle( + System::Windows::Forms::SizeType::Percent, 50.0)); + this->tableLayoutPanel1->Controls->Add(this->lblFirstName, 0, 0); + this->tableLayoutPanel1->Controls->Add(this->lblLastName, 2, 0); + this->tableLayoutPanel1->Controls->Add(this->lblAddress1, 0, 1); + this->tableLayoutPanel1->Controls->Add(this->lblAddress2, 0, 2); + this->tableLayoutPanel1->Controls->Add(this->lblCity, 0, 3); + this->tableLayoutPanel1->Controls->Add(this->lblState, 2, 3); + this->tableLayoutPanel1->Controls->Add(this->lblPhoneH, 2, 4); + this->tableLayoutPanel1->Controls->Add(this->txtAddress1, 1, 1); + this->tableLayoutPanel1->Controls->Add(this->txtAddress2, 1, 2); + this->tableLayoutPanel1->Controls->Add(this->txtCity, 1, 3); + this->tableLayoutPanel1->Controls->Add(this->txtLastName, 3, 0); + this->tableLayoutPanel1->Controls->Add(this->maskedTxtPhoneW, 1, 4); + this->tableLayoutPanel1->Controls->Add(this->maskedTxtPhoneH, 3, 4); + this->tableLayoutPanel1->Controls->Add(this->cboState, 3, 3); + this->tableLayoutPanel1->Controls->Add(this->txtFirstName, 1, 0); + this->tableLayoutPanel1->Controls->Add(this->lblNotes, 0, 5); + this->tableLayoutPanel1->Controls->Add(this->lblPhoneW, 0, 4); + this->tableLayoutPanel1->Controls->Add(this->richTxtNotes, 1, 5); + this->tableLayoutPanel1->Location = System::Drawing::Point(13, 13); + this->tableLayoutPanel1->Name = "tableLayoutPanel1"; + this->tableLayoutPanel1->RowCount = 6; + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Absolute, 28.0)); + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Absolute, 28.0)); + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Absolute, 28.0)); + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Absolute, 28.0)); + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Absolute, 28.0)); + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Percent, 80.0)); + this->tableLayoutPanel1->RowStyles->Add(gcnew + System::Windows::Forms::RowStyle( + System::Windows::Forms::SizeType::Absolute, 20.0)); + this->tableLayoutPanel1->Size = System::Drawing::Size(623, 286); + this->tableLayoutPanel1->TabIndex = 0; + // + // lblFirstName + // + this->lblFirstName->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblFirstName->AutoSize = true; + this->lblFirstName->Location = System::Drawing::Point(3, 7); + this->lblFirstName->Name = "lblFirstName"; + this->lblFirstName->Size = System::Drawing::Size(59, 14); + this->lblFirstName->TabIndex = 20; + this->lblFirstName->Text = "First Name"; + // + // lblLastName + // + this->lblLastName->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblLastName->AutoSize = true; + this->lblLastName->Location = System::Drawing::Point(323, 7); + this->lblLastName->Name = "lblLastName"; + this->lblLastName->Size = System::Drawing::Size(59, 14); + this->lblLastName->TabIndex = 21; + this->lblLastName->Text = "Last Name"; + // + // lblAddress1 + // + this->lblAddress1->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblAddress1->AutoSize = true; + this->lblAddress1->Location = System::Drawing::Point(10, 35); + this->lblAddress1->Name = "lblAddress1"; + this->lblAddress1->Size = System::Drawing::Size(52, 14); + this->lblAddress1->TabIndex = 22; + this->lblAddress1->Text = "Address1"; + // + // lblAddress2 + // + this->lblAddress2->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblAddress2->AutoSize = true; + this->lblAddress2->Location = System::Drawing::Point(7, 63); + this->lblAddress2->Name = "lblAddress2"; + this->lblAddress2->Size = System::Drawing::Size(55, 14); + this->lblAddress2->TabIndex = 23; + this->lblAddress2->Text = "Address 2"; + // + // lblCity + // + this->lblCity->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblCity->AutoSize = true; + this->lblCity->Location = System::Drawing::Point(38, 91); + this->lblCity->Name = "lblCity"; + this->lblCity->Size = System::Drawing::Size(24, 14); + this->lblCity->TabIndex = 24; + this->lblCity->Text = "City"; + // + // lblState + // + this->lblState->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblState->AutoSize = true; + this->lblState->Location = System::Drawing::Point(351, 91); + this->lblState->Name = "lblState"; + this->lblState->Size = System::Drawing::Size(31, 14); + this->lblState->TabIndex = 25; + this->lblState->Text = "State"; + // + // lblPhoneH + // + this->lblPhoneH->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblPhoneH->AutoSize = true; + this->lblPhoneH->Location = System::Drawing::Point(326, 119); + this->lblPhoneH->Name = "lblPhoneH"; + this->lblPhoneH->Size = System::Drawing::Size(56, 14); + this->lblPhoneH->TabIndex = 33; + this->lblPhoneH->Text = "Phone (H)"; + // + // txtAddress1 + // + this->txtAddress1->Anchor = + System::Windows::Forms::AnchorStyles::Left | + System::Windows::Forms::AnchorStyles::Right; + this->tableLayoutPanel1->SetColumnSpan(this->txtAddress1, 3); + this->txtAddress1->Location = System::Drawing::Point(68, 32); + this->txtAddress1->Name = "txtAddress1"; + this->txtAddress1->Size = System::Drawing::Size(552, 20); + this->txtAddress1->TabIndex = 2; + // + // txtAddress2 + // + this->txtAddress2->Anchor = + System::Windows::Forms::AnchorStyles::Left | + System::Windows::Forms::AnchorStyles::Right; + this->tableLayoutPanel1->SetColumnSpan(this->txtAddress2, 3); + this->txtAddress2->Location = System::Drawing::Point(68, 60); + this->txtAddress2->Name = "txtAddress2"; + this->txtAddress2->Size = System::Drawing::Size(552, 20); + this->txtAddress2->TabIndex = 3; + // + // txtCity + // + this->txtCity->Anchor = + System::Windows::Forms::AnchorStyles::Left | + System::Windows::Forms::AnchorStyles::Right; + this->txtCity->Location = System::Drawing::Point(68, 88); + this->txtCity->Name = "txtCity"; + this->txtCity->Size = System::Drawing::Size(249, 20); + this->txtCity->TabIndex = 4; + // + // txtLastName + // + this->txtLastName->Anchor = + System::Windows::Forms::AnchorStyles::Left | + System::Windows::Forms::AnchorStyles::Right; + this->txtLastName->Location = System::Drawing::Point(388, 4); + this->txtLastName->Name = "txtLastName"; + this->txtLastName->Size = System::Drawing::Size(232, 20); + this->txtLastName->TabIndex = 1; + // + // maskedTxtPhoneW + // + this->maskedTxtPhoneW->Anchor = + System::Windows::Forms::AnchorStyles::Left; + this->maskedTxtPhoneW->Location = System::Drawing::Point(68, 116); + this->maskedTxtPhoneW->Mask = "(999)000-0000"; + this->maskedTxtPhoneW->Name = "maskedTxtPhoneW"; + this->maskedTxtPhoneW->TabIndex = 6; + // + // maskedTxtPhoneH + // + this->maskedTxtPhoneH->Anchor = + System::Windows::Forms::AnchorStyles::Left; + this->maskedTxtPhoneH->Location = System::Drawing::Point(388, 116); + this->maskedTxtPhoneH->Mask = "(999)000-0000"; + this->maskedTxtPhoneH->Name = "maskedTxtPhoneH"; + this->maskedTxtPhoneH->TabIndex = 7; + // + // cboState + // + this->cboState->Anchor = System::Windows::Forms::AnchorStyles::Left; + this->cboState->FormattingEnabled = true; + this->cboState->Items->AddRange(gcnew array { + "AK - Alaska", + "WA - Washington"}); + this->cboState->Location = System::Drawing::Point(388, 87); + this->cboState->Name = "cboState"; + this->cboState->Size = System::Drawing::Size(100, 21); + this->cboState->TabIndex = 5; + // + // txtFirstName + // + this->txtFirstName->Anchor = + System::Windows::Forms::AnchorStyles::Left | + System::Windows::Forms::AnchorStyles::Right; + this->txtFirstName->Location = System::Drawing::Point(68, 4); + this->txtFirstName->Name = "txtFirstName"; + this->txtFirstName->Size = System::Drawing::Size(249, 20); + this->txtFirstName->TabIndex = 0; + // + // lblNotes + // + this->lblNotes->Anchor = + System::Windows::Forms::AnchorStyles::Top | + System::Windows::Forms::AnchorStyles::Right; + this->lblNotes->AutoSize = true; + this->lblNotes->Location = System::Drawing::Point(28, 143); + this->lblNotes->Name = "lblNotes"; + this->lblNotes->Size = System::Drawing::Size(34, 14); + this->lblNotes->TabIndex = 26; + this->lblNotes->Text = "Notes"; + // + // lblPhoneW + // + this->lblPhoneW->Anchor = + System::Windows::Forms::AnchorStyles::Right; + this->lblPhoneW->AutoSize = true; + this->lblPhoneW->Location = System::Drawing::Point(4, 119); + this->lblPhoneW->Name = "lblPhoneW"; + this->lblPhoneW->Size = System::Drawing::Size(58, 14); + this->lblPhoneW->TabIndex = 32; + this->lblPhoneW->Text = "Phone (W)"; + // + // richTxtNotes + // + this->tableLayoutPanel1->SetColumnSpan(this->richTxtNotes, 3); + this->richTxtNotes->Dock = System::Windows::Forms::DockStyle::Fill; + this->richTxtNotes->Location = System::Drawing::Point(68, 143); + this->richTxtNotes->Name = "richTxtNotes"; + this->richTxtNotes->Size = System::Drawing::Size(552, 140); + this->richTxtNotes->TabIndex = 8; + this->richTxtNotes->Text = ""; + // + // cancelBtn + // + this->cancelBtn->Anchor = + System::Windows::Forms::AnchorStyles::Bottom | + System::Windows::Forms::AnchorStyles::Right; + this->cancelBtn->DialogResult = + System::Windows::Forms::DialogResult::Cancel; + this->cancelBtn->Location = System::Drawing::Point(558, 306); + this->cancelBtn->Name = "cancelBtn"; + this->cancelBtn->TabIndex = 1; + this->cancelBtn->Text = "Cancel"; + this->cancelBtn->Click += gcnew System::EventHandler( + this, &BasicDataEntryForm::cancelBtn_Click); + // + // okBtn + // + this->okBtn->Anchor = + System::Windows::Forms::AnchorStyles::Bottom | + System::Windows::Forms::AnchorStyles::Right; + this->okBtn->DialogResult = + System::Windows::Forms::DialogResult::OK; + this->okBtn->Location = System::Drawing::Point(476, 306); + this->okBtn->Name = "okBtn"; + this->okBtn->TabIndex = 0; + this->okBtn->Text = "OK"; + this->okBtn->Click += gcnew System::EventHandler( + this, &BasicDataEntryForm::okBtn_Click); + // + // BasicDataEntryForm + // + this->AutoScaleBaseSize = System::Drawing::Size(5, 13); + this->ClientSize = System::Drawing::Size(642, 338); + this->Controls->Add(this->okBtn); + this->Controls->Add(this->cancelBtn); + this->Controls->Add(this->tableLayoutPanel1); + this->Name = "BasicDataEntryForm"; + this->Padding = System::Windows::Forms::Padding(9); + this->StartPosition = + System::Windows::Forms::FormStartPosition::Manual; + this->Text = "Basic Data Entry"; + this->tableLayoutPanel1->ResumeLayout(false); + this->tableLayoutPanel1->PerformLayout(); + this->ResumeLayout(false); + + } + +private: + System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1; + System::Windows::Forms::Label^ lblFirstName; + System::Windows::Forms::Label^ lblLastName; + System::Windows::Forms::Label^ lblAddress1; + System::Windows::Forms::Label^ lblAddress2; + System::Windows::Forms::Label^ lblCity; + System::Windows::Forms::Label^ lblState; + System::Windows::Forms::Label^ lblNotes; + System::Windows::Forms::Label^ lblPhoneW; + System::Windows::Forms::Label^ lblPhoneH; + System::Windows::Forms::Button^ cancelBtn; + System::Windows::Forms::Button^ okBtn; + System::Windows::Forms::TextBox^ txtFirstName; + System::Windows::Forms::TextBox^ txtAddress1; + System::Windows::Forms::TextBox^ txtAddress2; + System::Windows::Forms::TextBox^ txtCity; + System::Windows::Forms::TextBox^ txtLastName; + System::Windows::Forms::MaskedTextBox^ maskedTxtPhoneW; + System::Windows::Forms::MaskedTextBox^ maskedTxtPhoneH; + System::Windows::Forms::ComboBox^ cboState; + System::Windows::Forms::RichTextBox^ richTxtNotes; +}; + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew BasicDataEntryForm()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/makefile new file mode 100644 index 0000000000..02fe37366d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.TableLayoutPanel.DataEntryForm.exe : basicdataentryform.cpp + cl /W4 /clr:pure /FeSystem.Windows.Forms.TableLayoutPanel.DataEntryForm.exe basicdataentryform.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp new file mode 100644 index 0000000000..c35dc17f15 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CPP/form1.cpp @@ -0,0 +1,332 @@ +#using +#using +#using +#using + +using namespace System; +using namespace System::Collections; +using namespace System::ComponentModel; +using namespace System::Data; +using namespace System::Drawing; +using namespace System::Windows::Forms; + +/// +/// Summary description for form. +/// + +// The following example shows how to wrap a control +// using ToolStripControlHost. +// +//Declare a class that inherits from ToolStripControlHost. +public ref class ToolStripMonthCalendar: public ToolStripControlHost +{ +public: + // + // Call the base constructor passing in a MonthCalendar instance. + ToolStripMonthCalendar() : ToolStripControlHost( gcnew MonthCalendar ) {} + // + + // + property MonthCalendar^ MonthCalendarControl + { + MonthCalendar^ get() + { + return static_cast(Control); + } + } + // + // + property Day FirstDayOfWeek + { + // Expose the MonthCalendar.FirstDayOfWeek as a property. + Day get() + { + return MonthCalendarControl->FirstDayOfWeek; + } + + void set( Day value ) + { + MonthCalendarControl->FirstDayOfWeek = value; + } + } + + // Expose the AddBoldedDate method. + void AddBoldedDate( DateTime dateToBold ) + { + MonthCalendarControl->AddBoldedDate( dateToBold ); + } + // + +protected: + // Subscribe and unsubscribe the control events you wish to expose. + // + // + void OnSubscribeControlEvents( System::Windows::Forms::Control^ c ) + { + // Call the base so the base events are connected. + __super::OnSubscribeControlEvents( c ); + + // Cast the control to a MonthCalendar control. + MonthCalendar^ monthCalendarControl = (MonthCalendar^)c; + + // Add the event. + monthCalendarControl->DateChanged += gcnew DateRangeEventHandler( this, &ToolStripMonthCalendar::HandleDateChanged ); + } + // + + // + void OnUnsubscribeControlEvents( System::Windows::Forms::Control^ c ) + { + + // Call the base method so the basic events are unsubscribed. + __super::OnUnsubscribeControlEvents( c ); + + // Cast the control to a MonthCalendar control. + MonthCalendar^ monthCalendarControl = (MonthCalendar^)c; + + // Remove the event. + monthCalendarControl->DateChanged -= gcnew DateRangeEventHandler( this, &ToolStripMonthCalendar::HandleDateChanged ); + } + // + // + +public: + event DateRangeEventHandler^ DateChanged; + +private: + // + // Declare the DateChanged event. + // Raise the DateChanged event. + void HandleDateChanged( Object^ sender, DateRangeEventArgs^ e ) + { + if ( DateChanged != nullptr ) + { + DateChanged( this, e ); + } + } + // +}; +// + +public ref class Form1: public System::Windows::Forms::Form +{ +private: + /// + /// Required designer variable. + /// + static System::ComponentModel::IContainer^ components = nullptr; + static ToolStripTextBox^ textbox1; + +public: + Form1() + { + InitializeComponent(); + InitializeDropDownMonthCalendar(); + textbox1 = gcnew ToolStripTextBox; + textbox1->Width = 70; + toolStrip1->Items->Add( textbox1 ); + InitializeDateTimePickerHost(); + } + + static void Main() + { + Application::Run( gcnew Form1 ); + } + +private: + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + void InitializeComponent() + { + this->toolStrip1 = gcnew System::Windows::Forms::ToolStrip; + this->raftingContainer1 = gcnew System::Windows::Forms::RaftingContainer; + this->raftingContainer2 = gcnew System::Windows::Forms::RaftingContainer; + this->raftingContainer3 = gcnew System::Windows::Forms::RaftingContainer; + this->raftingContainer4 = gcnew System::Windows::Forms::RaftingContainer; + this->SuspendLayout(); + + // + // toolStrip1 + // + this->toolStrip1->Anchor = System::Windows::Forms::AnchorStyles::Right; + this->toolStrip1->Dock = System::Windows::Forms::DockStyle::None; + this->toolStrip1->Location = System::Drawing::Point( 0, 0 ); + this->toolStrip1->Name = L"toolStrip1"; + this->toolStrip1->Raft = System::Windows::Forms::RaftingSides::Top; + this->toolStrip1->TabIndex = 1; + this->toolStrip1->Text = L"toolStrip1"; + this->toolStrip1->Visible = true; + + // + // raftingContainer1 + // + this->raftingContainer1->AutoSize = true; + this->raftingContainer1->Dock = System::Windows::Forms::DockStyle::Top; + this->raftingContainer1->Location = System::Drawing::Point( 9, 9 ); + this->raftingContainer1->Name = L"raftingContainer1"; + this->raftingContainer1->Orientation = System::Windows::Forms::Orientation::Horizontal; + this->raftingContainer1->RowMargin = System::Windows::Forms::Padding( 0 ); + this->raftingContainer1->Size = System::Drawing::Size( 274, 25 ); + this->raftingContainer1->TabIndex = 0; + this->raftingContainer1->Text = L"RaftingContainerRaftingContainerTop"; + this->raftingContainer1->Join( this->toolStrip1 ); + + // + // raftingContainer2 + // + this->raftingContainer2->AutoSize = true; + this->raftingContainer2->Dock = System::Windows::Forms::DockStyle::Bottom; + this->raftingContainer2->Location = System::Drawing::Point( 9, 257 ); + this->raftingContainer2->Name = L"raftingContainer2"; + this->raftingContainer2->Orientation = System::Windows::Forms::Orientation::Horizontal; + this->raftingContainer2->RowMargin = System::Windows::Forms::Padding( 0 ); + this->raftingContainer2->Size = System::Drawing::Size( 274, 0 ); + this->raftingContainer2->TabIndex = 1; + this->raftingContainer2->Text = L"RaftingContainerRaftingContainerBottom"; + + // + // raftingContainer3 + // + this->raftingContainer3->AutoSize = true; + this->raftingContainer3->Dock = System::Windows::Forms::DockStyle::Left; + this->raftingContainer3->Location = System::Drawing::Point( 9, 9 ); + this->raftingContainer3->Name = L"raftingContainer3"; + this->raftingContainer3->Orientation = System::Windows::Forms::Orientation::Vertical; + this->raftingContainer3->RowMargin = System::Windows::Forms::Padding( 0 ); + this->raftingContainer3->Size = System::Drawing::Size( 0, 248 ); + this->raftingContainer3->TabIndex = 2; + this->raftingContainer3->Text = L"RaftingContainerRaftingContainerLeft"; + + // + // raftingContainer4 + // + this->raftingContainer4->AutoSize = true; + this->raftingContainer4->Dock = System::Windows::Forms::DockStyle::Right; + this->raftingContainer4->Location = System::Drawing::Point( 283, 9 ); + this->raftingContainer4->Name = L"raftingContainer4"; + this->raftingContainer4->Orientation = System::Windows::Forms::Orientation::Vertical; + this->raftingContainer4->RowMargin = System::Windows::Forms::Padding( 0 ); + this->raftingContainer4->Size = System::Drawing::Size( 0, 248 ); + this->raftingContainer4->TabIndex = 3; + this->raftingContainer4->Text = L"RaftingContainerRaftingContainerRight"; + + // + // Form1 + // + this->AutoSize = true; + this->ClientSize = System::Drawing::Size( 292, 266 ); + this->Controls->Add( this->raftingContainer1 ); + this->Controls->Add( this->raftingContainer2 ); + this->Controls->Add( this->raftingContainer3 ); + this->Controls->Add( this->raftingContainer4 ); + this->Name = L"Form1"; + this->Padding = System::Windows::Forms::Padding( 9 ); + this->Text = L"Form1"; + this->ResumeLayout( false ); + this->PerformLayout(); + } + +protected: + /// + /// Clean up any resources being used. + /// + void Dispose( bool disposing ) + { + if ( disposing ) + { + if ( components != nullptr ) + { + delete components; + } + } + + __super::Dispose( disposing ); + } + +private: + System::Windows::Forms::ToolStrip^ toolStrip1; + System::Windows::Forms::RaftingContainer^ raftingContainer1; + System::Windows::Forms::RaftingContainer^ raftingContainer2; + System::Windows::Forms::RaftingContainer^ raftingContainer3; + System::Windows::Forms::RaftingContainer^ raftingContainer4; + + // The following snippet demonstrates the ToolStripControlHost(Control) + // consturctor, the ToolStripControlHost.Font, Width, DisplayStyle, + // Text properties. + // + ToolStripControlHost^ dateTimePickerHost; + void InitializeDateTimePickerHost() + { + // Create a new ToolStripControlHost, passing in a control. + dateTimePickerHost = gcnew ToolStripControlHost( gcnew DateTimePicker ); + + // Set the font on the ToolStripControlHost, this will affect the hosted control. + dateTimePickerHost->Font = + gcnew System::Drawing::Font( L"Arial",7.0F,FontStyle::Italic ); + + // Set the Width property, this will also affect the hosted control. + dateTimePickerHost->Width = 100; + dateTimePickerHost->DisplayStyle = ToolStripItemDisplayStyle::Text; + + // Setting the Text property requires a string that converts to a + // DateTime type since that is what the hosted control requires. + dateTimePickerHost->Text = L"12/23/2005"; + + // Cast the Control property back to the original type to set a + // type-specific property. + (dynamic_cast(dateTimePickerHost->Control))->Format = + DateTimePickerFormat::Short; + + // Add the control host to the ToolStrip. + toolStrip1->Items->Add( dateTimePickerHost ); + } + // + + // The following example shows how to set the custom + // ToolStripMonthCalendar control. + // + void InitializeDropDownMonthCalendar() + { + // Declare the drop-down button and the drop-down. + ToolStripDropDownButton^ dropDownButton2 = gcnew ToolStripDropDownButton; + + // Set the image to the MonthCalendar embedded bitmap + // image. + dropDownButton2->Image = + gcnew Bitmap( MonthCalendar::typeid,L"MonthCalendar.bmp" ); + + // Add the button to the ToolStrip. + toolStrip1->Items->Add( dropDownButton2 ); + + // Construct a new drop-down. + ToolStripDropDown^ dropDown = gcnew ToolStripDropDown; + + // Construct a new wrapped MonthCalendar control. + ToolStripMonthCalendar^ monthCalendar = gcnew ToolStripMonthCalendar; + + // Set a date in boldface. + monthCalendar->AddBoldedDate( DateTime::Today.AddDays( 7 ) ); + monthCalendar->DateChanged += gcnew DateRangeEventHandler( + this, &Form1::monthCalendar_DateChanged ); + + //Add the calendar to the drop-down. + dropDown->Items->Add( monthCalendar ); + + //Set the drop-down on the DropDownButton. + dropDownButton2->DropDown = dropDown; + } + +private: + void monthCalendar_DateChanged( Object^ /*sender*/, DateRangeEventArgs^ e ) + { + textbox1->Text = e->Start.ToShortDateString(); + } +}; + +int main() +{ + Form1::Main(); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/form1.cpp new file mode 100644 index 0000000000..ddebd119d3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/form1.cpp @@ -0,0 +1,775 @@ +// User Input Test Application for new Windows Forms user input conceptual topics +// in Visual Studio 2005 documentation. + +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::ComponentModel; +using namespace System::Windows::Forms; + +namespace UserInputWalkthrough +{ + public ref class Form1 : public Form + { + Label^ lblEvent; + Label^ lblInput; + + TextBox^ TextBoxOutput; + TextBox^ TextBoxInput; + GroupBox^ GroupBoxEvents; + Button^ ButtonClear; + LinkLabel^ LinkLabelDrag; + + CheckBox^ CheckBoxToggleAll; + CheckBox^ CheckBoxMouse; + CheckBox^ CheckBoxMouseEnter; + CheckBox^ CheckBoxMouseMove; + CheckBox^ CheckBoxMousePoints; + CheckBox^ CheckBoxMouseDrag; + CheckBox^ CheckBoxMouseDragOver; + CheckBox^ CheckBoxKeyboard; + CheckBox^ CheckBoxKeyUpDown; + CheckBox^ CheckBoxFocus; + CheckBox^ CheckBoxValidation; + + public: + Form1() : Form() + { + this->Load += gcnew EventHandler(this, &Form1::Form1_Load); + + lblEvent = gcnew Label(); + lblInput = gcnew Label(); + + TextBoxOutput = gcnew TextBox(); + TextBoxInput = gcnew TextBox(); + GroupBoxEvents = gcnew GroupBox(); + ButtonClear = gcnew Button(); + LinkLabelDrag = gcnew LinkLabel(); + + CheckBoxToggleAll = gcnew CheckBox(); + CheckBoxMouse = gcnew CheckBox(); + CheckBoxMouseEnter = gcnew CheckBox(); + CheckBoxMouseMove = gcnew CheckBox(); + CheckBoxMousePoints = gcnew CheckBox(); + CheckBoxMouseDrag = gcnew CheckBox(); + CheckBoxMouseDragOver = gcnew CheckBox(); + CheckBoxKeyboard = gcnew CheckBox(); + CheckBoxKeyUpDown = gcnew CheckBox(); + CheckBoxFocus = gcnew CheckBox(); + CheckBoxValidation = gcnew CheckBox(); + } + + private: + void Form1_Load(Object^ sender, EventArgs^ e) + { + this->GroupBoxEvents->SuspendLayout(); + this->SuspendLayout(); + + lblEvent->Location = Point(232, 12); + lblEvent->Size = System::Drawing::Size(98, 14); + lblEvent->AutoSize = true; + lblEvent->Text = "Generated Events:"; + + lblInput->Location = Point(13, 12); + lblInput->Size = System::Drawing::Size(95, 14); + lblInput->AutoSize = true; + lblInput->Text = "User Input Target:"; + + TextBoxInput->Location = Point(13, 34); + TextBoxInput->Size = System::Drawing::Size(200, 200); + TextBoxInput->AllowDrop = true; + TextBoxInput->AutoSize = false; + TextBoxInput->Cursor = Cursors::Cross; + TextBoxInput->Multiline = true; + TextBoxInput->TabIndex = 1; + + LinkLabelDrag->AllowDrop = true; + LinkLabelDrag->AutoSize = true; + LinkLabelDrag->Location = Point(13, 240); + LinkLabelDrag->Size = System::Drawing::Size(175, 14); + LinkLabelDrag->TabIndex = 2; + LinkLabelDrag->TabStop = true; + LinkLabelDrag->Text = "Click here to use as a drag source"; + LinkLabelDrag->Links->Add(gcnew LinkLabel::Link(0, + LinkLabelDrag->Text->Length)); + + GroupBoxEvents->Location = Point(13, 281); + GroupBoxEvents->Size = System::Drawing::Size(200, 302); + GroupBoxEvents->Text = "Event Filter:"; + GroupBoxEvents->TabStop = true; + GroupBoxEvents->TabIndex = 3; + GroupBoxEvents->Controls->Add(CheckBoxMouseEnter); + GroupBoxEvents->Controls->Add(CheckBoxToggleAll); + GroupBoxEvents->Controls->Add(CheckBoxMousePoints); + GroupBoxEvents->Controls->Add(CheckBoxKeyUpDown); + GroupBoxEvents->Controls->Add(CheckBoxMouseDragOver); + GroupBoxEvents->Controls->Add(CheckBoxMouseDrag); + GroupBoxEvents->Controls->Add(CheckBoxValidation); + GroupBoxEvents->Controls->Add(CheckBoxMouseMove); + GroupBoxEvents->Controls->Add(CheckBoxFocus); + GroupBoxEvents->Controls->Add(CheckBoxKeyboard); + GroupBoxEvents->Controls->Add(CheckBoxMouse); + + CheckBoxToggleAll->AutoSize = true; + CheckBoxToggleAll->Location = Point(7, 20); + CheckBoxToggleAll->Size = System::Drawing::Size(122, 17); + CheckBoxToggleAll->TabIndex = 4; + CheckBoxToggleAll->Text = "Toggle All Events"; + + CheckBoxMouse->AutoSize = true; + CheckBoxMouse->Location = Point(7, 45); + CheckBoxMouse->Size = System::Drawing::Size(137, 17); + CheckBoxMouse->TabIndex = 5; + CheckBoxMouse->Text = "Mouse and Click Events"; + + CheckBoxMouseEnter->AutoSize = true; + CheckBoxMouseEnter->Location = Point(26, 69); + CheckBoxMouseEnter->Margin = + System::Windows::Forms::Padding(3, 3, 3, 1); + CheckBoxMouseEnter->Size = System::Drawing::Size(151, 17); + CheckBoxMouseEnter->TabIndex = 6; + CheckBoxMouseEnter->Text = "Mouse Enter/Hover/Leave"; + + CheckBoxMouseMove->AutoSize = true; + CheckBoxMouseMove->Location = Point(26, 89); + CheckBoxMouseMove->Margin = + System::Windows::Forms::Padding(3, 2, 3, 3); + CheckBoxMouseMove->Size = System::Drawing::Size(120, 17); + CheckBoxMouseMove->TabIndex = 7; + CheckBoxMouseMove->Text = "Mouse Move Events"; + + CheckBoxMousePoints->AutoSize = true; + CheckBoxMousePoints->Location = Point(26, 112); + CheckBoxMousePoints->Margin = + System::Windows::Forms::Padding(3, 3, 3, 1); + CheckBoxMousePoints->Size = System::Drawing::Size(141, 17); + CheckBoxMousePoints->TabIndex = 8; + CheckBoxMousePoints->Text = "Draw Mouse Points"; + + CheckBoxMouseDrag->AutoSize = true; + CheckBoxMouseDrag->Location = Point(26, 135); + CheckBoxMouseDrag->Margin = + System::Windows::Forms::Padding(3, 1, 3, 3); + CheckBoxMouseDrag->Size = System::Drawing::Size(151, 17); + CheckBoxMouseDrag->TabIndex = 9; + CheckBoxMouseDrag->Text = "Mouse Drag && Drop Events"; + + CheckBoxMouseDragOver->AutoSize = true; + CheckBoxMouseDragOver->Location = Point(44, 159); + CheckBoxMouseDragOver->Size = System::Drawing::Size(142, 17); + CheckBoxMouseDragOver->TabIndex = 10; + CheckBoxMouseDragOver->Text = "Mouse Drag Over Events"; + + CheckBoxKeyboard->AutoSize = true; + CheckBoxKeyboard->Location = Point(8, 184); + CheckBoxKeyboard->Size = System::Drawing::Size(103, 17); + CheckBoxKeyboard->TabIndex = 11; + CheckBoxKeyboard->Text = "Keyboard Events"; + + CheckBoxKeyUpDown->AutoSize = true; + CheckBoxKeyUpDown->Location = Point(26, 207); + CheckBoxKeyUpDown->Margin = + System::Windows::Forms::Padding(3, 3, 3, 1); + CheckBoxKeyUpDown->Size = System::Drawing::Size(133, 17); + CheckBoxKeyUpDown->TabIndex = 12; + CheckBoxKeyUpDown->Text = "Key Up && Down Events"; + + CheckBoxFocus->AutoSize = true; + CheckBoxFocus->Location = Point(8, 233); + CheckBoxFocus->Margin = + System::Windows::Forms::Padding(3, 2, 3, 3); + CheckBoxFocus->Size = System::Drawing::Size(146, 17); + CheckBoxFocus->TabIndex = 13; + CheckBoxFocus->Text = "Focus && Activation Events"; + + CheckBoxValidation->AutoSize = true; + CheckBoxValidation->Location = Point(8, 257); + CheckBoxValidation->Size = System::Drawing::Size(104, 17); + CheckBoxValidation->TabIndex = 14; + CheckBoxValidation->Text = "Validation Events"; + + TextBoxOutput->Location = Point(232, 34); + TextBoxOutput->Size = System::Drawing::Size(308, 510); + TextBoxOutput->Multiline = true; + TextBoxOutput->CausesValidation = false; + TextBoxOutput->ReadOnly = true; + TextBoxOutput->ScrollBars = ScrollBars::Vertical; + TextBoxOutput->TabIndex = 15; + TextBoxOutput->WordWrap = false; + + ButtonClear->Location = Point(232, 560); + ButtonClear->Size = System::Drawing::Size(308, 23); + ButtonClear->TabIndex = 16; + ButtonClear->Text = "Clear Event List"; + + this->ClientSize = System::Drawing::Size(552, 595); + this->Controls->Add(LinkLabelDrag); + this->Controls->Add(ButtonClear); + this->Controls->Add(GroupBoxEvents); + this->Controls->Add(lblEvent); + this->Controls->Add(lblInput); + this->Controls->Add(TextBoxInput); + this->Controls->Add(TextBoxOutput); + this->Text = "User Input Events"; + + ButtonClear->Click += + gcnew EventHandler(this, &Form1::ButtonClear_Click); + TextBoxInput->KeyDown += + gcnew KeyEventHandler(this, &Form1::TextBoxInput_KeyDown); + TextBoxInput->KeyPress += + gcnew KeyPressEventHandler(this, + &Form1::TextBoxInput_KeyPress); + TextBoxInput->KeyUp += + gcnew KeyEventHandler(this, &Form1::TextBoxInput_KeyUp); + TextBoxInput->Click += + gcnew EventHandler(this, &Form1::TextBoxInput_Click); + TextBoxInput->DoubleClick += + gcnew EventHandler(this, &Form1::TextBoxInput_DoubleClick); + TextBoxInput->MouseClick += + gcnew MouseEventHandler(this, &Form1::TextBoxInput_MouseClick); + TextBoxInput->MouseDoubleClick += + gcnew MouseEventHandler(this, + &Form1::TextBoxInput_MouseDoubleClick); + TextBoxInput->MouseDown += + gcnew MouseEventHandler(this, &Form1::TextBoxInput_MouseDown); + TextBoxInput->MouseUp += + gcnew MouseEventHandler(this, &Form1::TextBoxInput_MouseUp); + TextBoxInput->MouseEnter += + gcnew EventHandler(this, &Form1::TextBoxInput_MouseEnter); + TextBoxInput->MouseHover += + gcnew EventHandler(this, &Form1::TextBoxInput_MouseHover); + TextBoxInput->MouseLeave += + gcnew EventHandler(this, &Form1::TextBoxInput_MouseLeave); + TextBoxInput->MouseWheel += + gcnew MouseEventHandler(this, &Form1::TextBoxInput_MouseWheel); + TextBoxInput->MouseMove += + gcnew MouseEventHandler(this, &Form1::TextBoxInput_MouseMove); + TextBoxInput->MouseCaptureChanged += + gcnew EventHandler(this, + &Form1::TextBoxInput_MouseCaptureChanged); + TextBoxInput->DragEnter += + gcnew DragEventHandler(this, &Form1::TextBoxInput_DragEnter); + TextBoxInput->DragDrop += + gcnew DragEventHandler(this, &Form1::TextBoxInput_DragDrop); + TextBoxInput->DragOver += + gcnew DragEventHandler(this, &Form1::TextBoxInput_DragOver); + TextBoxInput->DragLeave += + gcnew EventHandler(this, &Form1::TextBoxInput_DragLeave); + TextBoxInput->Enter += + gcnew EventHandler(this, &Form1::TextBoxInput_Enter); + TextBoxInput->Leave += + gcnew EventHandler(this, &Form1::TextBoxInput_Leave); + TextBoxInput->GotFocus += + gcnew EventHandler(this, &Form1::TextBoxInput_GotFocus); + TextBoxInput->LostFocus += + gcnew EventHandler(this, &Form1::TextBoxInput_LostFocus); + TextBoxInput->Validated += + gcnew EventHandler(this, &Form1::TextBoxInput_Validated); + TextBoxInput->Validating += + gcnew CancelEventHandler(this, + &Form1::TextBoxInput_Validating); + + LinkLabelDrag->MouseDown += + gcnew MouseEventHandler(this, &Form1::LinkLabelDrag_MouseDown); + LinkLabelDrag->GiveFeedback += + gcnew GiveFeedbackEventHandler(this, + &Form1::LinkLabelDrag_GiveFeedback); + + CheckBoxToggleAll->CheckedChanged += + gcnew EventHandler(this, + &Form1::CheckBoxToggleAll_CheckedChanged); + CheckBoxMouse->CheckedChanged += + gcnew EventHandler(this, &Form1::CheckBoxMouse_CheckedChanged); + CheckBoxMouseDrag->CheckedChanged += + gcnew EventHandler(this, + &Form1::CheckBoxMouseDrag_CheckedChanged); + CheckBoxMouseEnter->CheckedChanged += + gcnew EventHandler(this, + &Form1::CheckBoxMouseMove_CheckedChanged); + CheckBoxMouseMove->CheckedChanged += + gcnew EventHandler(this, + &Form1::CheckBoxMouseMove_CheckedChanged); + CheckBoxKeyboard->CheckedChanged += + gcnew EventHandler(this, + &Form1::CheckBoxKeyboard_CheckedChanged); + + this->GroupBoxEvents->ResumeLayout(false); + this->GroupBoxEvents->PerformLayout(); + this->ResumeLayout(false); + this->PerformLayout(); + CheckAllChildCheckBoxes(this, true); + } + + // Recursively search the form for all contained checkboxes and + // initially check them + private: + void CheckAllChildCheckBoxes(Control^ parent, bool value) + { + CheckBox^ box; + for each (Control^ currentControl in parent->Controls) + { + if (dynamic_cast(currentControl)) + { + box = (CheckBox^)currentControl; + box->Checked = value; + } + + // Recurse if control contains other controls + if (currentControl->Controls->Count > 0) + { + CheckAllChildCheckBoxes(currentControl, value); + } + } + } + + // All-purpose method for displaying a line of text in one of the + // text boxes. + private: + void DisplayLine(String^ line) + { + TextBoxOutput->AppendText(line); + TextBoxOutput->AppendText(Environment::NewLine); + } + + // Click event handler for the button that clears the text box. + private: + void ButtonClear_Click(Object^ sender, EventArgs^ e) + { + TextBoxOutput->Invalidate(); + TextBoxOutput->Clear(); + } + + private: + void TextBoxInput_KeyDown(Object^ sender, KeyEventArgs^ e) + { + if (CheckBoxKeyUpDown->Checked) + { + DisplayLine("KeyDown: " + e->KeyData.ToString()); + } + } + + private: + void TextBoxInput_KeyUp(Object^ sender, KeyEventArgs^ e) + { + if (CheckBoxKeyUpDown->Checked) + { + DisplayLine("KeyUp: " + e->KeyData.ToString()); + } + } + + private: + void TextBoxInput_KeyPress(Object^ sender, + KeyPressEventArgs^ e) + { + if (CheckBoxKeyboard->Checked) + { + if (Char::IsWhiteSpace(e->KeyChar)) + { + DisplayLine("KeyPress: WS"); + } + else + { + DisplayLine("KeyPress: " + e->KeyChar.ToString()); + } + } + } + + private: + void TextBoxInput_Click(Object^ sender, EventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("Click event"); + } + } + + private: + void TextBoxInput_DoubleClick(Object^ sender, EventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("DoubleClick event"); + } + } + + private: + void TextBoxInput_MouseClick(Object^ sender, MouseEventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("MouseClick: " + e->Button.ToString() + + " " + e->Location.ToString()); + } + } + + private: + void TextBoxInput_MouseDoubleClick(Object^ sender, + MouseEventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("MouseDoubleClick: " + e->Button.ToString() + + " " + e->Location.ToString()); + } + } + + private: + void TextBoxInput_MouseDown(Object^ sender, + MouseEventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("MouseDown: " + e->Button.ToString() + + " " + e->Location.ToString()); + } + } + + private: + void TextBoxInput_MouseUp(Object^ sender, + MouseEventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("MouseUp: " + e->Button.ToString() + + " " + e->Location.ToString()); + } + + // The TextBox control was designed to change focus only on + // the primary click, so force focus to avoid user confusion. + if (!TextBoxInput->Focused) + { + TextBoxInput->Focus(); + } + } + + private: + void TextBoxInput_MouseEnter(Object^ sender, EventArgs^ e) + { + if (CheckBoxMouseEnter->Checked) + { + DisplayLine("MouseEnter event"); + } + } + + private: + void TextBoxInput_MouseHover(Object^ sender, EventArgs^ e) + { + if (CheckBoxMouseEnter->Checked) + { + DisplayLine("MouseHover event"); + } + } + + private: + void TextBoxInput_MouseLeave(Object^ sender, EventArgs^ e) + { + if (CheckBoxMouseEnter->Checked) + { + DisplayLine("MouseLeave event"); + } + } + + private: + void TextBoxInput_MouseWheel(Object^ sender, + MouseEventArgs^ e) + { + if (CheckBoxMouse->Checked) + { + DisplayLine("MouseWheel: " + e->Delta.ToString() + + " detents at " + e->Location.ToString()); + } + } + + private: + void TextBoxInput_MouseMove(Object^ sender, + MouseEventArgs^ e) + { + if (CheckBoxMouseMove->Checked) + { + DisplayLine("MouseMove: " + e->Button.ToString() + " " + + e->Location.ToString()); + } + + if (CheckBoxMousePoints->Checked) + { + Graphics^ g = TextBoxInput->CreateGraphics(); + g->FillRectangle(Brushes::Black, e->Location.X, + e->Location.Y, 1, 1); + delete g; + } + } + + private: + void TextBoxInput_MouseCaptureChanged(Object^ sender, + EventArgs^ e) + { + if (CheckBoxMouseDrag->Checked) + { + DisplayLine("MouseCaptureChanged event"); + } + } + + private: + void TextBoxInput_DragEnter(Object^ sender, DragEventArgs^ e) + { + if (CheckBoxMouseDrag->Checked) + { + Point^ pt = gcnew Point(e->X, e->Y); + DisplayLine("DragEnter: " + + CovertKeyStateToString(e->KeyState) + + " at " + pt->ToString()); + } + } + + private: + void TextBoxInput_DragDrop(Object^ sender, DragEventArgs^ e) + { + if (CheckBoxMouseDrag->Checked) + { + Point^ pt = gcnew Point(e->X, e->Y); + DisplayLine("DragDrop: " + + CovertKeyStateToString(e->KeyState) + + " at " + pt->ToString()); + } + } + + private: + void TextBoxInput_DragOver(Object^ sender, DragEventArgs^ e) + { + if (CheckBoxMouseDragOver->Checked) + { + Point^ pt = gcnew Point(e->X, e->Y); + DisplayLine("DragOver: " + + CovertKeyStateToString(e->KeyState) + + " at " + pt->ToString()); + } + + // Allow if drop data is of type string. + if (!e->Data->GetDataPresent(String::typeid)) + { + e->Effect = DragDropEffects::None; + } + else + { + e->Effect = DragDropEffects::Copy; + } + } + + private: + void TextBoxInput_DragLeave(Object^ sender, + EventArgs^ e) + { + if (CheckBoxMouseDrag->Checked) + { + DisplayLine("DragLeave event"); + } + } + + private: + static String^ CovertKeyStateToString(int keyState) + { + String^ keyString = "None"; + + // Which button was pressed? + if ((keyState & 1) == 1) + { + keyString = "Left"; + } + else if ((keyState & 2) == 2) + { + keyString = "Right"; + } + else if ((keyState & 16) == 16) + { + keyString = "Middle"; + } + + // Are one or more modifier keys also pressed? + if ((keyState & 4) == 4) + { + keyString += "+SHIFT"; + } + + if ((keyState & 8) == 8) + { + keyString += "+CTRL"; + } + + if ((keyState & 32) == 32) + { + keyString += "+ALT"; + } + + return keyString; + } + + private: + void TextBoxInput_Enter(Object^ sender, EventArgs^ e) + { + if (CheckBoxFocus->Checked) + { + DisplayLine("Enter event"); + } + } + + private: + void TextBoxInput_Leave(Object^ sender, EventArgs^ e) + { + if (CheckBoxFocus->Checked) + { + DisplayLine("Leave event"); + } + } + + private: + void TextBoxInput_GotFocus(Object^ sender, EventArgs^ e) + { + if (CheckBoxFocus->Checked) + { + DisplayLine("GotFocus event"); + } + } + + private: + void TextBoxInput_LostFocus(Object^ sender, EventArgs^ e) + { + if (CheckBoxFocus->Checked) + { + DisplayLine("LostFocus event"); + } + } + + private: + void TextBoxInput_Validated(Object^ sender, EventArgs^ e) + { + if (CheckBoxValidation->Checked) + { + DisplayLine("Validated event"); + } + } + + private: + void TextBoxInput_Validating( + Object^ sender, CancelEventArgs^ e) + { + if (CheckBoxValidation->Checked) + { + DisplayLine("Validating event"); + } + } + + private: + void CheckBoxToggleAll_CheckedChanged( + Object^ sender, EventArgs^ e) + { + if (dynamic_cast(sender)) + { + CheckAllChildCheckBoxes(this, ((CheckBox^)sender)->Checked); + } + } + + private: + void CheckBoxMouse_CheckedChanged( + Object^ sender, EventArgs^ e) + { + ConfigureCheckBoxSettings(); + } + + private: + void CheckBoxMouseDrag_CheckedChanged( + Object^ sender, EventArgs^ e) + { + ConfigureCheckBoxSettings(); + } + + private: + void CheckBoxKeyboard_CheckedChanged( + Object^ sender, EventArgs^ e) + { + ConfigureCheckBoxSettings(); + } + + private: + void CheckBoxMouseMove_CheckedChanged( + Object^ sender, EventArgs^ e) + { + ConfigureCheckBoxSettings(); + } + + // Reconcile dependencies between the check box + // selection choices. + private: + void ConfigureCheckBoxSettings() + { + // CheckBoxMouse is a top-level check box. + if (!CheckBoxMouse->Checked) + { + CheckBoxMouseEnter->Enabled = false; + CheckBoxMouseMove->Enabled = false; + CheckBoxMouseDrag->Enabled = false; + CheckBoxMouseDragOver->Enabled = false; + CheckBoxMousePoints->Enabled = false; + } + else + { + CheckBoxMouseEnter->Enabled = true; + CheckBoxMouseMove->Enabled = true; + CheckBoxMouseDrag->Enabled = true; + CheckBoxMousePoints->Enabled = true; + + // Enable children depending on the state of the parent. + if (!CheckBoxMouseDrag->Checked) + { + CheckBoxMouseDragOver->Enabled = false; + } + else + { + CheckBoxMouseDragOver->Enabled = true; + } + } + + if (!CheckBoxKeyboard->Checked) + { + CheckBoxKeyUpDown->Enabled = false; + } + else + { + CheckBoxKeyUpDown->Enabled = true; + } + } + + private: + void LinkLabelDrag_MouseDown(Object^ sender, MouseEventArgs^ e) + { + String^ data = "Sample Data"; + LinkLabelDrag->DoDragDrop(data, DragDropEffects::All); + } + + private: + void LinkLabelDrag_GiveFeedback(Object^ sender, + GiveFeedbackEventArgs^ e) + { + if ((e->Effect & DragDropEffects::Copy) == + DragDropEffects::Copy) + { + LinkLabelDrag->Cursor = Cursors::HSplit; + } + else + { + LinkLabelDrag->Cursor = Cursors::Default; + } + } + }; +} + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew UserInputWalkthrough::Form1()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/makefile new file mode 100644 index 0000000000..7737adb41c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.UserInputWalkthrough.exe: form1.cpp + cl /clr:pure /FeSystem.Windows.Forms.UserInputWalkthrough.exe form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/form1.cpp new file mode 100644 index 0000000000..84341cd985 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/form1.cpp @@ -0,0 +1,76 @@ +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; +using namespace System::Windows::Forms::VisualStyles; + +namespace SimpleVisualStyleRendererSample +{ + public ref class CustomControl : public Control + { + // + private: + VisualStyleRenderer^ renderer; + VisualStyleElement^ element; + + public: + CustomControl() + { + this->Location = Point(50, 50); + this->Size = System::Drawing::Size(200, 200); + this->BackColor = SystemColors::ActiveBorder; + this->element = + VisualStyleElement::StartPanel::LogOffButtons::Normal; + if (Application::RenderWithVisualStyles && + VisualStyleRenderer::IsElementDefined(element)) + { + renderer = gcnew VisualStyleRenderer(element); + } + } + // + + // + protected: + virtual void OnPaint(PaintEventArgs^ e) override + { + // Draw the element if the renderer has been set. + if (renderer != nullptr) + { + renderer->DrawBackground(e->Graphics, this->ClientRectangle); + } + + // Visual styles are disabled or the element is undefined, + // so just draw a message. + else + { + this->Text = "Visual styles are disabled."; + TextRenderer::DrawText(e->Graphics, this->Text, this->Font, + Point(0, 0), this->ForeColor); + } + } + // + }; + + public ref class SimpleVisualStyleRendererForm : public Form + { + public: + SimpleVisualStyleRendererForm() + { + this->Size = System::Drawing::Size(400, 400); + this->BackColor = Color::WhiteSmoke; + this->Controls->Add(gcnew CustomControl()); + } + }; +} + +using namespace SimpleVisualStyleRendererSample; + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew SimpleVisualStyleRendererForm()); +} diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/makefile new file mode 100644 index 0000000000..bccf6c199e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple.exe : form1.cpp + cl /W4 /clr:pure /FeSystem.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple.exe form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CPP/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CPP/form1.cpp new file mode 100644 index 0000000000..c653b99492 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CPP/form1.cpp @@ -0,0 +1,502 @@ + + +// +#using +#using +#using + +using namespace System; +using namespace System::Security::Permissions; + +public ref class Form1: public System::Windows::Forms::Form +{ +public: + Form1() + { + //This call is required by the Windows Form Designer. + InitializeComponent(); + + //Add any initialization after the InitializeComponent() call + } + + +private: + + //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. + System::Windows::Forms::MainMenu^ MainMenu1; + System::Windows::Forms::MenuItem^ MenuItemFile; + System::Windows::Forms::MenuItem^ MenuItemFileSaveAs; + System::Windows::Forms::MenuItem^ MenuItemFilePageSetup; + System::Windows::Forms::MenuItem^ MenuItemFilePrint; + System::Windows::Forms::MenuItem^ MenuItemFilePrintPreview; + System::Windows::Forms::MenuItem^ MenuItemFileProperties; + System::Windows::Forms::TextBox^ TextBoxAddress; + System::Windows::Forms::Button^ ButtonGo; + System::Windows::Forms::Button^ backButton; + System::Windows::Forms::Button^ ButtonForward; + System::Windows::Forms::Button^ ButtonStop; + System::Windows::Forms::Button^ ButtonRefresh; + System::Windows::Forms::Button^ ButtonHome; + System::Windows::Forms::Button^ ButtonSearch; + System::Windows::Forms::Panel^ Panel1; + System::Windows::Forms::WebBrowser ^ WebBrowser1; + System::Windows::Forms::StatusBar^ StatusBar1; + System::Windows::Forms::MenuItem^ MenuItem1; + System::Windows::Forms::MenuItem^ MenuItem2; + System::Windows::Forms::Button^ ButtonPrint; + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + [SecurityPermission(SecurityAction::Demand, Flags=SecurityPermissionFlag::UnmanagedCode)] + void InitializeComponent() + { + this->MainMenu1 = gcnew System::Windows::Forms::MainMenu; + this->MenuItemFile = gcnew System::Windows::Forms::MenuItem; + this->MenuItemFileSaveAs = gcnew System::Windows::Forms::MenuItem; + this->MenuItem1 = gcnew System::Windows::Forms::MenuItem; + this->MenuItemFilePageSetup = gcnew System::Windows::Forms::MenuItem; + this->MenuItemFilePrint = gcnew System::Windows::Forms::MenuItem; + this->MenuItemFilePrintPreview = gcnew System::Windows::Forms::MenuItem; + this->MenuItem2 = gcnew System::Windows::Forms::MenuItem; + this->MenuItemFileProperties = gcnew System::Windows::Forms::MenuItem; + this->TextBoxAddress = gcnew System::Windows::Forms::TextBox; + this->ButtonGo = gcnew System::Windows::Forms::Button; + this->backButton = gcnew System::Windows::Forms::Button; + this->ButtonForward = gcnew System::Windows::Forms::Button; + this->ButtonStop = gcnew System::Windows::Forms::Button; + this->ButtonRefresh = gcnew System::Windows::Forms::Button; + this->ButtonHome = gcnew System::Windows::Forms::Button; + this->ButtonSearch = gcnew System::Windows::Forms::Button; + this->ButtonPrint = gcnew System::Windows::Forms::Button; + this->Panel1 = gcnew System::Windows::Forms::Panel; + this->WebBrowser1 = gcnew System::Windows::Forms::WebBrowser; + this->StatusBar1 = gcnew System::Windows::Forms::StatusBar; + this->Panel1->SuspendLayout(); + this->SuspendLayout(); + + // + // MainMenu1 + // + array^temp0 = {this->MenuItemFile}; + this->MainMenu1->MenuItems->AddRange( temp0 ); + this->MainMenu1->Name = "MainMenu1"; + + // + // MenuItemFile + // + this->MenuItemFile->Index = 0; + array^temp1 = {this->MenuItemFileSaveAs,this->MenuItem1,this->MenuItemFilePageSetup,this->MenuItemFilePrint,this->MenuItemFilePrintPreview,this->MenuItem2,this->MenuItemFileProperties}; + this->MenuItemFile->MenuItems->AddRange( temp1 ); + this->MenuItemFile->Name = "MenuItemFile"; + this->MenuItemFile->Text = "&File"; + + // + // MenuItemFileSaveAs + // + this->MenuItemFileSaveAs->Index = 0; + this->MenuItemFileSaveAs->Name = "MenuItemFileSaveAs"; + this->MenuItemFileSaveAs->Text = " Save &As"; + this->MenuItemFileSaveAs->Click += gcnew System::EventHandler( this, &Form1::MenuItemFileSaveAs_Click ); + + // + // MenuItem1 + // + this->MenuItem1->Index = 1; + this->MenuItem1->Name = "MenuItem1"; + this->MenuItem1->Text = "-"; + + // + // MenuItemFilePageSetup + // + this->MenuItemFilePageSetup->Index = 2; + this->MenuItemFilePageSetup->Name = "MenuItemFilePageSetup"; + this->MenuItemFilePageSetup->Text = "Page Set&up..."; + this->MenuItemFilePageSetup->Click += gcnew System::EventHandler( this, &Form1::MenuItemFilePageSetup_Click ); + + // + // MenuItemFilePrint + // + this->MenuItemFilePrint->Index = 3; + this->MenuItemFilePrint->Name = "MenuItemFilePrint"; + this->MenuItemFilePrint->Text = "&Print..."; + this->MenuItemFilePrint->Click += gcnew System::EventHandler( this, &Form1::MenuItemFilePrint_Click ); + + // + // MenuItemFilePrintPreview + // + this->MenuItemFilePrintPreview->Index = 4; + this->MenuItemFilePrintPreview->Name = "MenuItemFilePrintPreview"; + this->MenuItemFilePrintPreview->Text = "Print Pre&view..."; + this->MenuItemFilePrintPreview->Click += gcnew System::EventHandler( this, &Form1::MenuItemFilePrintPreview_Click ); + + // + // MenuItem2 + // + this->MenuItem2->Index = 5; + this->MenuItem2->Name = "MenuItem2"; + this->MenuItem2->Text = "-"; + + // + // MenuItemFileProperties + // + this->MenuItemFileProperties->Index = 6; + this->MenuItemFileProperties->Name = "MenuItemFileProperties"; + this->MenuItemFileProperties->Text = "P&roperties"; + this->MenuItemFileProperties->Click += gcnew System::EventHandler( this, &Form1::MenuItemFileProperties_Click ); + + // + // TextBoxAddress + // + this->TextBoxAddress->Location = System::Drawing::Point( 0, 0 ); + this->TextBoxAddress->Name = "TextBoxAddress"; + this->TextBoxAddress->Size = System::Drawing::Size( 240, 20 ); + this->TextBoxAddress->TabIndex = 1; + this->TextBoxAddress->Text = ""; + this->TextBoxAddress->KeyDown += gcnew System::Windows::Forms::KeyEventHandler( this, &Form1::TextBoxAddress_KeyDown ); + + // + // ButtonGo + // + this->ButtonGo->Location = System::Drawing::Point( 240, 0 ); + this->ButtonGo->Name = "ButtonGo"; + this->ButtonGo->Size = System::Drawing::Size( 48, 24 ); + this->ButtonGo->TabIndex = 2; + this->ButtonGo->Text = "Go"; + this->ButtonGo->Click += gcnew System::EventHandler( this, &Form1::ButtonGo_Click ); + + // + // backButton + // + this->backButton->Location = System::Drawing::Point( 288, 0 ); + this->backButton->Name = "backButton"; + this->backButton->Size = System::Drawing::Size( 48, 24 ); + this->backButton->TabIndex = 3; + this->backButton->Text = "Back"; + this->backButton->Click += gcnew System::EventHandler( this, &Form1::backButton_Click ); + + // + // ButtonForward + // + this->ButtonForward->Location = System::Drawing::Point( 336, 0 ); + this->ButtonForward->Name = "ButtonForward"; + this->ButtonForward->Size = System::Drawing::Size( 48, 24 ); + this->ButtonForward->TabIndex = 4; + this->ButtonForward->Text = "Forward"; + this->ButtonForward->Click += gcnew System::EventHandler( this, &Form1::ButtonForward_Click ); + + // + // ButtonStop + // + this->ButtonStop->Location = System::Drawing::Point( 384, 0 ); + this->ButtonStop->Name = "ButtonStop"; + this->ButtonStop->Size = System::Drawing::Size( 48, 24 ); + this->ButtonStop->TabIndex = 5; + this->ButtonStop->Text = "Stop"; + this->ButtonStop->Click += gcnew System::EventHandler( this, &Form1::ButtonStop_Click ); + + // + // ButtonRefresh + // + this->ButtonRefresh->Location = System::Drawing::Point( 432, 0 ); + this->ButtonRefresh->Name = "ButtonRefresh"; + this->ButtonRefresh->Size = System::Drawing::Size( 48, 24 ); + this->ButtonRefresh->TabIndex = 6; + this->ButtonRefresh->Text = "Refresh"; + this->ButtonRefresh->Click += gcnew System::EventHandler( this, &Form1::ButtonRefresh_Click ); + + // + // ButtonHome + // + this->ButtonHome->Location = System::Drawing::Point( 480, 0 ); + this->ButtonHome->Name = "ButtonHome"; + this->ButtonHome->Size = System::Drawing::Size( 48, 24 ); + this->ButtonHome->TabIndex = 7; + this->ButtonHome->Text = "Home"; + this->ButtonHome->Click += gcnew System::EventHandler( this, &Form1::ButtonHome_Click ); + + // + // ButtonSearch + // + this->ButtonSearch->Location = System::Drawing::Point( 528, 0 ); + this->ButtonSearch->Name = "ButtonSearch"; + this->ButtonSearch->Size = System::Drawing::Size( 48, 24 ); + this->ButtonSearch->TabIndex = 8; + this->ButtonSearch->Text = "Search"; + this->ButtonSearch->Click += gcnew System::EventHandler( this, &Form1::ButtonSearch_Click ); + + // + // ButtonPrint + // + this->ButtonPrint->Location = System::Drawing::Point( 576, 0 ); + this->ButtonPrint->Name = "ButtonPrint"; + this->ButtonPrint->Size = System::Drawing::Size( 48, 24 ); + this->ButtonPrint->TabIndex = 9; + this->ButtonPrint->Text = "Print"; + this->ButtonPrint->Click += gcnew System::EventHandler( this, &Form1::ButtonPrint_Click ); + + // + // Panel1 + // + this->Panel1->Controls->Add( this->ButtonPrint ); + this->Panel1->Controls->Add( this->TextBoxAddress ); + this->Panel1->Controls->Add( this->ButtonGo ); + this->Panel1->Controls->Add( this->backButton ); + this->Panel1->Controls->Add( this->ButtonForward ); + this->Panel1->Controls->Add( this->ButtonStop ); + this->Panel1->Controls->Add( this->ButtonRefresh ); + this->Panel1->Controls->Add( this->ButtonHome ); + this->Panel1->Controls->Add( this->ButtonSearch ); + this->Panel1->Dock = System::Windows::Forms::DockStyle::Top; + this->Panel1->Location = System::Drawing::Point( 0, 0 ); + this->Panel1->Name = "Panel1"; + this->Panel1->Size = System::Drawing::Size( 624, 24 ); + this->Panel1->TabIndex = 11; + + // + // WebBrowser1 + // + // + this->WebBrowser1->AllowWebBrowserDrop = false; + this->WebBrowser1->ScriptErrorsSuppressed = true; + this->WebBrowser1->WebBrowserShortcutsEnabled = false; + this->WebBrowser1->Dock = System::Windows::Forms::DockStyle::Fill; + this->WebBrowser1->IsWebBrowserContextMenuEnabled = false; + + // + this->WebBrowser1->Location = System::Drawing::Point( 0, 24 ); + this->WebBrowser1->Name = "WebBrowser1"; + this->WebBrowser1->Size = System::Drawing::Size( 624, 389 ); + this->WebBrowser1->TabIndex = 10; + this->WebBrowser1->StatusTextChanged += gcnew System::EventHandler( this, &Form1::WebBrowser1_StatusTextChanged ); + this->WebBrowser1->CanGoBackChanged += gcnew System::EventHandler( this, &Form1::WebBrowser1_CanGoBackChanged ); + this->WebBrowser1->Navigated += gcnew System::Windows::Forms::WebBrowserNavigatedEventHandler( this, &Form1::WebBrowser1_Navigated ); + this->WebBrowser1->CanGoForwardChanged += gcnew System::EventHandler( this, &Form1::WebBrowser1_CanGoForwardChanged ); + this->WebBrowser1->DocumentTitleChanged += gcnew System::EventHandler( this, &Form1::WebBrowser1_DocumentTitleChanged ); + + // + // StatusBar1 + // + this->StatusBar1->Location = System::Drawing::Point( 0, 413 ); + this->StatusBar1->Name = "StatusBar1"; + this->StatusBar1->Size = System::Drawing::Size( 624, 16 ); + this->StatusBar1->TabIndex = 12; + + // + // Form1 + // + this->ClientSize = System::Drawing::Size( 624, 429 ); + this->Controls->Add( this->WebBrowser1 ); + this->Controls->Add( this->Panel1 ); + this->Controls->Add( this->StatusBar1 ); + this->Menu = this->MainMenu1; + this->Name = "Form1"; + this->Text = "WebBrowser Example"; + this->Panel1->ResumeLayout( false ); + this->ResumeLayout( false ); + } + + +internal: + + static property Form1^ GetInstance + { + Form1^ get() + { + if ( m_DefaultInstance == nullptr || m_DefaultInstance->IsDisposed ) + { + System::Threading::Monitor::Enter( Form1::typeid ); + try + { + if ( m_DefaultInstance == nullptr || m_DefaultInstance->IsDisposed ) + { + m_DefaultInstance = gcnew Form1; + } + } + finally + { + System::Threading::Monitor::Exit( Form1::typeid ); + } + } + + return m_DefaultInstance; + } + } + +private: + static Form1^ m_DefaultInstance; + + // + // Displays the Save dialog box. + void MenuItemFileSaveAs_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->ShowSaveAsDialog(); + } + + // + // + // Displays the Page Setup dialog box. + void MenuItemFilePageSetup_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->ShowPageSetupDialog(); + } + // + + // + // Displays the Print dialog box. + void MenuItemFilePrint_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->ShowPrintDialog(); + } + // + + // + // Displays the Print Preview dialog box. + void MenuItemFilePrintPreview_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->ShowPrintPreviewDialog(); + } + // + + // + // Displays the Properties dialog box. + void MenuItemFileProperties_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->ShowPropertiesDialog(); + } + // + + // + // Navigates to the URL in the address text box when + // the ENTER key is pressed while the text box has focus. + void TextBoxAddress_KeyDown( Object^ /*sender*/, System::Windows::Forms::KeyEventArgs^ e ) + { + if ( e->KeyCode == System::Windows::Forms::Keys::Enter && !this->TextBoxAddress->Text->Equals( "" ) ) + { + this->WebBrowser1->Navigate( this->TextBoxAddress->Text ); + } + } + + // Navigates to the URL in the address text box when + // the Go button is clicked. + void ButtonGo_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + if ( !this->TextBoxAddress->Text->Equals( "" ) ) + { + this->WebBrowser1->Navigate( this->TextBoxAddress->Text ); + } + } + + // Updates the URL in TextBoxAddress upon navigation. + void WebBrowser1_Navigated( Object^ /*sender*/, System::Windows::Forms::WebBrowserNavigatedEventArgs^ /*e*/ ) + { + this->TextBoxAddress->Text = this->WebBrowser1->Url->ToString(); + } + + // + + // + // Navigates WebBrowser1 to the previous page in the history. + void backButton_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->GoBack(); + } + + // Disables the Back button at the beginning of the navigation history. + void WebBrowser1_CanGoBackChanged( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->backButton->Enabled = this->WebBrowser1->CanGoBack; + } + // + + // + // Navigates WebBrowser1 to the next page in history. + void ButtonForward_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->GoForward(); + } + + // Disables the Forward button at the end of navigation history. + void WebBrowser1_CanGoForwardChanged( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->ButtonForward->Enabled = this->WebBrowser1->CanGoForward; + } + // + + // + // Halts the current navigation and any sounds or animations on + // the page. + void ButtonStop_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->Stop(); + } + // + + // + // Reloads the current page. + void ButtonRefresh_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + + // Skip refresh if about:blank is loaded to avoid removing + // content specified by the DocumentText property. + if ( !this->WebBrowser1->Url->Equals( "about:blank" ) ) + { + this->WebBrowser1->Refresh(); + } + } + // + + // + // Navigates WebBrowser1 to the home page of the current user. + void ButtonHome_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->GoHome(); + } + // + + // + // Navigates WebBrowser1 to the search page of the current user. + void ButtonSearch_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->GoSearch(); + } + // + + // + // Prints the current document using the current print settings. + void ButtonPrint_Click( System::Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->WebBrowser1->Print(); + } + // + + // + // Updates StatusBar1 with the current browser status text. + void WebBrowser1_StatusTextChanged( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->StatusBar1->Text = WebBrowser1->StatusText; + } + // + + // + // Updates the title bar with the current document title. + void WebBrowser1_DocumentTitleChanged( Object^ /*sender*/, System::EventArgs^ /*e*/ ) + { + this->Text = WebBrowser1->DocumentTitle; + } + // +}; + +/// +/// The main entry point for the application. +/// + +[STAThread] +int main() +{ + System::Windows::Forms::Application::Run( gcnew Form1 ); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/form1.cpp new file mode 100644 index 0000000000..1a2b458218 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/form1.cpp @@ -0,0 +1,63 @@ +// +#using +#using +#using + +using namespace System; +using namespace System::Drawing; +using namespace System::Windows::Forms; +using namespace System::Windows::Forms::VisualStyles; + +namespace SimpleControlRenderingSample +{ + public ref class CustomComboBoxArrow : Control + { + public: + CustomComboBoxArrow() : Control() + { + this->Location = Point(50, 50); + this->Size = System::Drawing::Size(40, 40); + } + + // + // Render the drop-down arrow with or without visual styles. + protected: + virtual void OnPaint(PaintEventArgs^ e) override + { + __super::OnPaint(e); + + if (!ComboBoxRenderer::IsSupported) + { + ControlPaint::DrawComboButton(e->Graphics, + this->ClientRectangle, ButtonState::Normal); + } + else + { + ComboBoxRenderer::DrawDropDownButton(e->Graphics, + this->ClientRectangle, ComboBoxState::Normal); + } + } + // + }; + + public ref class SimpleControlRenderingForm : public Form + { + public: + SimpleControlRenderingForm() : Form() + { + this->Size = System::Drawing::Size(300, 300); + CustomComboBoxArrow^ testComboBox = gcnew CustomComboBoxArrow(); + Controls->Add(testComboBox); + } + }; +} + +using namespace SimpleControlRenderingSample; + +[STAThread] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew SimpleControlRenderingForm()); +} +// diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/makefile new file mode 100644 index 0000000000..397bbf80dc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/cpp/makefile @@ -0,0 +1,2 @@ +System.Windows.Forms_ControlRenderer.exe: form1.cpp + cl /clr:pure /FeSystem.Windows.Forms_ControlRenderer.exe form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/Form1.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/Form1.cpp new file mode 100644 index 0000000000..8d482c296b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/Form1.cpp @@ -0,0 +1,86 @@ +#using +#using +#using + +using namespace System; +using namespace System::Windows::Forms; +using namespace System::Drawing; +using namespace System::Collections; + +//Create a Class that inherits from System.Windows.Forms.Form. +ref class myForm : public Form +{ +public: + myForm() + { + InitializeComponent(); + InitializeMenuTreeView(); + } + + // + // Declare the TreeView and ContextMenuStrip +private: + TreeView^ menuTreeView; +private: + System::Windows::Forms::ContextMenuStrip^ docMenu; + +public: + void InitializeMenuTreeView() + { + // Create the TreeView. + menuTreeView = gcnew TreeView(); + menuTreeView->Size = System::Drawing::Size(200, 200); + + // Create the root node. + TreeNode^ docNode = gcnew TreeNode("Documents"); + + // Add some additional nodes. + docNode->Nodes->Add("phoneList.doc"); + docNode->Nodes->Add("resume.doc"); + + // Add the root nodes to the TreeView. + menuTreeView->Nodes->Add(docNode); + + // Create the ContextMenuStrip. + docMenu = gcnew System::Windows::Forms::ContextMenuStrip(); + + //Create some menu items. + ToolStripMenuItem^ openLabel = gcnew ToolStripMenuItem(); + openLabel->Text = "Open"; + ToolStripMenuItem^ deleteLabel = gcnew ToolStripMenuItem(); + deleteLabel->Text = "Delete"; + ToolStripMenuItem^ renameLabel = gcnew ToolStripMenuItem(); + renameLabel->Text = "Rename"; + + //Add the menu items to the menu. + docMenu->Items->AddRange(gcnew array{openLabel, + deleteLabel, renameLabel}); + + // Set the ContextMenuStrip property to the ContextMenuStrip. + docNode->ContextMenuStrip = docMenu; + + // Add the TreeView to the form. + this->Controls->Add(menuTreeView); + } + // +private: + void InitializeComponent() + { + this->SuspendLayout(); + + // + // myForm + // + this->AutoScaleBaseSize = System::Drawing::Size(5, 13); + this->ClientSize = System::Drawing::Size(292, 266); + this->Name = "myForm"; + this->ResumeLayout(false); + } +}; + +[STAThreadAttribute] +int main() +{ + Application::EnableVisualStyles(); + Application::Run(gcnew myForm()); +} diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/makefile b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/makefile new file mode 100644 index 0000000000..f815b09251 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/cpp/makefile @@ -0,0 +1,2 @@ +system.windows.forms.TreeNodeContextMenuStrip.exe: Form1.cpp + cl /clr:pure /Fesystem.windows.forms.TreeNodeContextMenuStrip.exe Form1.cpp diff --git a/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cpp/add.cpp b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cpp/add.cpp new file mode 100644 index 0000000000..aedfdd507a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/cpp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cpp/add.cpp @@ -0,0 +1,28 @@ +#using +#using +#using + +using namespace System::Drawing; +using namespace System::Windows::Forms; +public ref class Form1: public Form +{ +private: + +public: + Form1() + { + TabPage^ tabPage1; + tabPage1 = gcnew TabPage; + + // + tabPage1->Controls->Add(gcnew Button); + // + } + +}; + +int main() +{ + Application::Run( gcnew Form1 ); +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/AccessHTMLDOMControlCSharp.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/AccessHTMLDOMControlCSharp.csproj new file mode 100644 index 0000000000..6587c992c7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/AccessHTMLDOMControlCSharp.csproj @@ -0,0 +1,61 @@ + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {267B4A3D-A09F-4067-A39A-F3BE7108AC65} + Library + AccessHTMLDOMControlCSharp + AccessHTMLDOMControlCSharp + 4 + + + true + full + false + .\bin\Debug\ + DEBUG;TRACE + + + pdbonly + true + .\bin\Release\ + TRACE + + + + + + + + + + + UserControl + + + UserControl1.cs + + + + ResXFileCodeGenerator + Resources.cs + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.cs + + + True + Settings.settings + True + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/AssemblyInfo.cs new file mode 100644 index 0000000000..7b4e6d8c47 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AccessHTMLDOMControlCSharp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("MS")] +[assembly: AssemblyProduct("AccessHTMLDOMControlCSharp")] +[assembly: AssemblyCopyright("Copyright @ MS 2004")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +/// Setting ComVisible to false makes the types in this assembly not visible +/// to COM componenets. If you need to access a type in this assembly from +/// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.*")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Resources.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Resources.cs new file mode 100644 index 0000000000..13201888d6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Resources.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.41021.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace AccessHTMLDOMControlCSharp.Configuration +{ + using System; + using System.IO; + using System.Resources; + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the Strongly Typed Resource Builder + // class via a tool like ResGen or Visual Studio.NET. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + class Resources + { + + private static System.Resources.ResourceManager _resMgr; + + private static System.Globalization.CultureInfo _resCulture; + + /*FamANDAssem*/ + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public static System.Resources.ResourceManager ResourceManager + { + get + { + if ((_resMgr == null)) + { + System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly); + _resMgr = temp; + } + return _resMgr; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public static System.Globalization.CultureInfo Culture + { + get + { + return _resCulture; + } + set + { + _resCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Resources.resx new file mode 100644 index 0000000000..3e18af958a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Settings.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Settings.cs new file mode 100644 index 0000000000..6eedc43a64 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Settings.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.41021.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace AccessHTMLDOMControlCSharp.Configuration +{ + public partial class Settings : System.Configuration.ApplicationSettingsBase + { + private static Settings m_Value; + + private static object m_SyncObject = new object(); + + public static Settings Value + { + get + { + if ((Settings.m_Value == null)) + { + System.Threading.Monitor.Enter(Settings.m_SyncObject); + if ((Settings.m_Value == null)) + { + try + { + Settings.m_Value = new Settings(); + } + finally + { + System.Threading.Monitor.Exit(Settings.m_SyncObject); + } + } + } + return Settings.m_Value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Settings.settings new file mode 100644 index 0000000000..4024694778 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/Configuration/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.Designer.cs new file mode 100644 index 0000000000..d0b661086f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.Designer.cs @@ -0,0 +1,44 @@ +namespace AccessHTMLDOMControlCSharp +{ + 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() + { + this.SuspendLayout(); + // + // UserControl1 + // + this.Name = "UserControl1"; + this.Size = new System.Drawing.Size(435, 401); + this.Load += new System.EventHandler(this.UserControl1_Load); + this.ResumeLayout(false); + + } + + #endregion + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.cs new file mode 100644 index 0000000000..a6c38242fc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/AccessHTMLDOMControl/cs/UserControl1.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Text; +using System.Windows.Forms; + +namespace AccessHTMLDOMControlCSharp +{ + public partial class UserControl1 : UserControl + { + public UserControl1() + { + InitializeComponent(); + } + + // + HtmlDocument doc = null; + + private void UserControl1_Load(object sender, EventArgs e) + { + if (this.Site != null) + { + doc = (HtmlDocument)this.Site.GetService(typeof(HtmlDocument)); + } + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/Application/CS/source.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/Application/CS/source.cs new file mode 100644 index 0000000000..7ac16e8710 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/Application/CS/source.cs @@ -0,0 +1,236 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; +using System.ComponentModel; +using System.Text; +using System.IO; + +namespace MyApplication +{ + // A simple form that represents a window in our application + public class AppForm2 : System.Windows.Forms.Form + { + public AppForm2() + { + this.Size = new System.Drawing.Size(300, 300); + this.Text = "AppForm2"; + } + } + + // A simple form that represents a window in our application + public class AppForm1 : System.Windows.Forms.Form + { + public AppForm1() + { + this.Size = new System.Drawing.Size(300, 300); + this.Text = "AppForm1"; + } + } + + // + // The class that handles the creation of the application windows + class MyApplicationContext : ApplicationContext + { + + private int _formCount; + private AppForm1 _form1; + private AppForm2 _form2; + + private Rectangle _form1Position; + private Rectangle _form2Position; + + private FileStream _userData; + + // + private MyApplicationContext() + { + _formCount = 0; + + // Handle the ApplicationExit event to know when the application is exiting. + Application.ApplicationExit += new EventHandler(this.OnApplicationExit); + + try + { + // Create a file that the application will store user specific data in. + _userData = new FileStream(Application.UserAppDataPath + "\\appdata.txt", FileMode.OpenOrCreate); + } + catch (IOException e) + { + // Inform the user that an error occurred. + MessageBox.Show("An error occurred while attempting to show the application." + + "The error is:" + e.ToString()); + + // Exit the current thread instead of showing the windows. + ExitThread(); + } + + // Create both application forms and handle the Closed event + // to know when both forms are closed. + _form1 = new AppForm1(); + _form1.Closed += new EventHandler(OnFormClosed); + _form1.Closing += new CancelEventHandler(OnFormClosing); + _formCount++; + + _form2 = new AppForm2(); + _form2.Closed += new EventHandler(OnFormClosed); + _form2.Closing += new CancelEventHandler(OnFormClosing); + _formCount++; + + // Get the form positions based upon the user specific data. + if (ReadFormDataFromFile()) + { + // If the data was read from the file, set the form + // positions manually. + _form1.StartPosition = FormStartPosition.Manual; + _form2.StartPosition = FormStartPosition.Manual; + + _form1.Bounds = _form1Position; + _form2.Bounds = _form2Position; + } + + // Show both forms. + _form1.Show(); + _form2.Show(); + } + + private void OnApplicationExit(object sender, EventArgs e) + { + // When the application is exiting, write the application data to the + // user file and close it. + WriteFormDataToFile(); + + try + { + // Ignore any errors that might occur while closing the file handle. + _userData.Close(); + } + catch { } + } + // + + private void OnFormClosing(object sender, CancelEventArgs e) + { + // When a form is closing, remember the form position so it + // can be saved in the user data file. + if (sender is AppForm1) + _form1Position = ((Form)sender).Bounds; + else if (sender is AppForm2) + _form2Position = ((Form)sender).Bounds; + } + + // + private void OnFormClosed(object sender, EventArgs e) + { + // When a form is closed, decrement the count of open forms. + + // When the count gets to 0, exit the app by calling + // ExitThread(). + _formCount--; + if (_formCount == 0) + { + ExitThread(); + } + } + // + + private bool WriteFormDataToFile() + { + // Write the form positions to the file. + UTF8Encoding encoding = new UTF8Encoding(); + + RectangleConverter rectConv = new RectangleConverter(); + string form1pos = rectConv.ConvertToString(_form1Position); + string form2pos = rectConv.ConvertToString(_form2Position); + + byte[] dataToWrite = encoding.GetBytes("~" + form1pos + "~" + form2pos); + + try + { + // Set the write position to the start of the file and write + _userData.Seek(0, SeekOrigin.Begin); + _userData.Write(dataToWrite, 0, dataToWrite.Length); + _userData.Flush(); + + _userData.SetLength(dataToWrite.Length); + return true; + } + catch + { + // An error occurred while attempting to write, return false. + return false; + } + } + + private bool ReadFormDataFromFile() + { + // Read the form positions from the file. + UTF8Encoding encoding = new UTF8Encoding(); + string data; + + if (_userData.Length != 0) + { + byte[] dataToRead = new byte[_userData.Length]; + + try + { + // Set the read position to the start of the file and read. + _userData.Seek(0, SeekOrigin.Begin); + _userData.Read(dataToRead, 0, dataToRead.Length); + } + catch (IOException e) + { + string errorInfo = e.ToString(); + // An error occurred while attempt to read, return false. + return false; + } + + // Parse out the data to get the window rectangles + data = encoding.GetString(dataToRead); + + try + { + // Convert the string data to rectangles + RectangleConverter rectConv = new RectangleConverter(); + string form1pos = data.Substring(1, data.IndexOf("~", 1) - 1); + + _form1Position = (Rectangle)rectConv.ConvertFromString(form1pos); + + string form2pos = data.Substring(data.IndexOf("~", 1) + 1); + _form2Position = (Rectangle)rectConv.ConvertFromString(form2pos); + + return true; + } + catch + { + // Error occurred while attempting to convert the rectangle data. + // Return false to use default values. + return false; + } + } + else + { + // No data in the file, return false to use default values. + return false; + } + } + + // + [STAThread] + static void Main(string[] args) + { + + // Create the MyApplicationContext, that derives from ApplicationContext, + // that manages when the application should exit. + + MyApplicationContext context = new MyApplicationContext(); + + // Run the application with the specific context. It will exit when + // all forms are closed. + Application.Run(context); + } + // + } + // +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/ApplicationSettingsArchitectureCS.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/ApplicationSettingsArchitectureCS.csproj new file mode 100644 index 0000000000..ee5c743568 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/ApplicationSettingsArchitectureCS.csproj @@ -0,0 +1,75 @@ + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {37FC2D7B-9F35-4D66-8CD2-C76F7E242552} + WinExe + Properties + ApplicationSettingsArchitectureCS + ApplicationSettingsArchitectureCS + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + Form + + + Form1.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/DummyClass.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/DummyClass.cs new file mode 100644 index 0000000000..e29c883ec5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/DummyClass.cs @@ -0,0 +1,44 @@ +// +using System; +using System.Collections.Generic; +using System.Text; +using System.Configuration; + +namespace ApplicationSettingsArchitectureCS +{ + [SettingsProvider("SqlSettingsProvider")] + class CustomSettings : ApplicationSettingsBase + { + // Implementation goes here. + } +} +// + +namespace ApplicationSettingsArchitectureCS +{ + public abstract class DummySettingsBase + { + public abstract string ApplicationName + { + get; + set; + } + } + + public class DummySettings : DummySettingsBase + { + // + public override string ApplicationName + { + get + { + return (System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); + } + set + { + // Do nothing. + } + } + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Form1.Designer.cs new file mode 100644 index 0000000000..af198f632f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Form1.Designer.cs @@ -0,0 +1,39 @@ +namespace ApplicationSettingsArchitectureCS +{ + 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.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Form1.cs new file mode 100644 index 0000000000..09e79633fd --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Form1.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace ApplicationSettingsArchitectureCS +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Program.cs new file mode 100644 index 0000000000..bf7270b54f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Program.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace ApplicationSettingsArchitectureCS +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..ca6b0bc8c3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ApplicationSettingsArchitectureCS")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ApplicationSettingsArchitectureCS")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2005")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("36af196a-a168-42a6-a697-3ae9594bb79b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Resources.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..9435178799 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ApplicationSettingsArchitectureCS.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ApplicationSettingsArchitectureCS.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Settings.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Settings.Designer.cs new file mode 100644 index 0000000000..5a1ba964c7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ApplicationSettingsArchitectureCS.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Settings.settings new file mode 100644 index 0000000000..39645652af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Architecture/CS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/AppSettingsArchitectureProject.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/AppSettingsArchitectureProject.csproj new file mode 100644 index 0000000000..90d67fca2e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/AppSettingsArchitectureProject.csproj @@ -0,0 +1,79 @@ + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {5C6D141F-0E63-486F-AEB3-E6766F89B6CB} + WinExe + Properties + AppSettingsArchitectureProject + AppSettingsArchitectureProject + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + Form + + + Form1.cs + + + + + + Designer + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.Designer.cs new file mode 100644 index 0000000000..d6fbb3817c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.Designer.cs @@ -0,0 +1,87 @@ +namespace AppSettingsArchitectureProject +{ + 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.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(72, 61); + 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); + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel1}); + this.statusStrip1.Location = new System.Drawing.Point(0, 251); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Size = new System.Drawing.Size(292, 22); + this.statusStrip1.TabIndex = 1; + this.statusStrip1.Text = "statusStrip1"; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + this.toolStripStatusLabel1.Size = new System.Drawing.Size(109, 17); + this.toolStripStatusLabel1.Text = "toolStripStatusLabel1"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.cs new file mode 100644 index 0000000000..6c0a6944d5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace AppSettingsArchitectureProject +{ + public partial class Form1 : Form + { + + public Form1() + { + InitializeComponent(); + this.FormClosing += new FormClosingEventHandler(Form1_FormClosing); + } + + // + //Make sure to hook up this event handler in the constructor! + //this.FormClosing += new FormClosingEventHandler(Form1_FormClosing); + void Form1_FormClosing(object sender, FormClosingEventArgs e) + { + mus.Save(); + } + // + + private void button1_Click(object sender, EventArgs e) + { + mus.BackgroundColor = Color.Black; + } + + // + MyUserSettings mus; + + private void Form1_Load(object sender, EventArgs e) + { + mus = new MyUserSettings(); + mus.BackgroundColor = Color.AliceBlue; + this.DataBindings.Add(new Binding("BackColor", mus, "BackgroundColor")); + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.resx new file mode 100644 index 0000000000..b9c202bfe3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Form1.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/MyAppSettings.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/MyAppSettings.cs new file mode 100644 index 0000000000..323fcfb482 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/MyAppSettings.cs @@ -0,0 +1,22 @@ +// +using System; +using System.Configuration; +using System.Drawing; + +public class MyUserSettings : ApplicationSettingsBase +{ + [UserScopedSetting()] + [DefaultSettingValue("white")] + public Color BackgroundColor + { + get + { + return ((Color)this["BackgroundColor"]); + } + set + { + this["BackgroundColor"] = (Color)value; + } + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Program.cs new file mode 100644 index 0000000000..11f6965c97 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Program.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace AppSettingsArchitectureProject +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..e024fcd689 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AppSettingsArchitectureProject")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("AppSettingsArchitectureProject")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2005")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("37cc6737-2577-424e-b0c9-b1b02d9c6333")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Resources.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..5acc386023 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace AppSettingsArchitectureProject.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AppSettingsArchitectureProject.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Settings.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Settings.Designer.cs new file mode 100644 index 0000000000..ef4c750556 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace AppSettingsArchitectureProject.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Settings.settings new file mode 100644 index 0000000000..39645652af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ApplicationSettings.Create/CS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.Designer.cs new file mode 100644 index 0000000000..bea8ca39b9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.Designer.cs @@ -0,0 +1,58 @@ +namespace DisplayWebBrowserCode +{ + partial class CodeForm + { + /// + /// 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.richTextBox1 = new System.Windows.Forms.RichTextBox(); + this.SuspendLayout(); + // + // richTextBox1 + // + this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; + this.richTextBox1.Location = new System.Drawing.Point(0, 0); + this.richTextBox1.Name = "richTextBox1"; + this.richTextBox1.Size = new System.Drawing.Size(776, 651); + this.richTextBox1.TabIndex = 0; + this.richTextBox1.Text = ""; + // + // CodeForm + // + this.ClientSize = new System.Drawing.Size(776, 651); + this.Controls.Add(this.richTextBox1); + this.Name = "CodeForm"; + this.Text = "HTML Source Code Window"; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.RichTextBox richTextBox1; + + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.cs new file mode 100644 index 0000000000..c3e81dd7cf --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace DisplayWebBrowserCode +{ + partial class CodeForm : Form + { + public CodeForm() + { + InitializeComponent(); + } + + // + public string Code + { + get + { + if (richTextBox1.Text != null) + { + return (richTextBox1.Text); + } + else + { + return (""); + } + } + set + { + richTextBox1.Text = value; + } + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.resx new file mode 100644 index 0000000000..25c2f26478 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/CodeForm.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/DisplayWebBrowserCode.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/DisplayWebBrowserCode.csproj new file mode 100644 index 0000000000..ce6c6a3c03 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/DisplayWebBrowserCode.csproj @@ -0,0 +1,76 @@ + + + Debug + AnyCPU + 8.0.41025 + 2.0 + {A1758485-65E5-4E5D-B57A-50F9B2838D3D} + WinExe + DisplayWebBrowserCode + DisplayWebBrowserCode + 4 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + + + pdbonly + true + bin\Release\ + TRACE + prompt + + + + + + + + + + + + Form + + + CodeForm.cs + + + Form + + + Form1.cs + + + + + CodeForm.cs + + + Form1.cs + + + ResXFileCodeGenerator + Resources.cs + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.cs + + + True + Settings.settings + True + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.Designer.cs new file mode 100644 index 0000000000..7e22a06816 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.Designer.cs @@ -0,0 +1,67 @@ +namespace DisplayWebBrowserCode +{ + 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.webBrowser1 = new System.Windows.Forms.WebBrowser(); + this.button1 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // webBrowser1 + // + this.webBrowser1.Location = new System.Drawing.Point(12, 250); + this.webBrowser1.Name = "webBrowser1"; + this.webBrowser1.Size = new System.Drawing.Size(744, 382); + this.webBrowser1.Url = new System.Uri("http://www.msn.com/"); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.TabIndex = 1; + this.button1.Text = "button1"; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(768, 644); + this.Controls.Add(this.button1); + this.Controls.Add(this.webBrowser1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.WebBrowser webBrowser1; + private System.Windows.Forms.Button button1; + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.cs new file mode 100644 index 0000000000..7df08b2775 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +namespace DisplayWebBrowserCode +{ + partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // + private void button1_Click(object sender, EventArgs e) + { + HtmlElement elem; + + if (webBrowser1.Document != null) + { + CodeForm cf = new CodeForm(); + HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("HTML"); + if (elems.Count == 1) + { + elem = elems[0]; + cf.Code = elem.OuterHtml; + cf.Show(); + } + } + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.resx new file mode 100644 index 0000000000..25c2f26478 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Form1.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Program.cs new file mode 100644 index 0000000000..c2872c0e1a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace DisplayWebBrowserCode +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..4116f7bd63 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DisplayWebBrowserCode")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("MS")] +[assembly: AssemblyProduct("DisplayWebBrowserCode")] +[assembly: AssemblyCopyright("Copyright @ MS 2004")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6b24619b-1c02-4b9b-a282-7aaa133b26a9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Resources.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Resources.cs new file mode 100644 index 0000000000..839ae79ab0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Resources.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.41025.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DisplayWebBrowserCode.Properties +{ + using System; + using System.IO; + using System.Resources; + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the Strongly Typed Resource Builder + // class via a tool like ResGen or Visual Studio.NET. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + class Resources + { + + private static System.Resources.ResourceManager _resMgr; + + private static System.Globalization.CultureInfo _resCulture; + + /*FamANDAssem*/ + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public static System.Resources.ResourceManager ResourceManager + { + get + { + if ((_resMgr == null)) + { + System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly); + _resMgr = temp; + } + return _resMgr; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public static System.Globalization.CultureInfo Culture + { + get + { + return _resCulture; + } + set + { + _resCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Resources.resx new file mode 100644 index 0000000000..3e18af958a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Settings.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Settings.cs new file mode 100644 index 0000000000..6e1b20a88e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Settings.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.41025.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DisplayWebBrowserCode.Properties +{ + public partial class Settings : System.Configuration.ApplicationSettingsBase + { + private static Settings m_Value; + + private static object m_SyncObject = new object(); + + public static Settings Value + { + get + { + if ((Settings.m_Value == null)) + { + System.Threading.Monitor.Enter(Settings.m_SyncObject); + if ((Settings.m_Value == null)) + { + try + { + Settings.m_Value = new Settings(); + } + finally + { + System.Threading.Monitor.Exit(Settings.m_SyncObject); + } + } + } + return Settings.m_Value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Settings.settings new file mode 100644 index 0000000000..4024694778 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/DisplayWebBrowserCode/CS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs new file mode 100644 index 0000000000..93ae5ecbed --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/LinesCurvesAndShapes/CS/Class1.cs @@ -0,0 +1,324 @@ +using System.Diagnostics; +using System.Windows.Forms; +using System.Xml; +using System.Data; +using System; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; + +public class LinesCurvesAndShapes : Form +{ + // 0195df81-66be-452d-bb53-5a582ebfdc09 + // Vector Graphics Overview + + Pen myPen = Pens.Black; + SolidBrush mySolidBrush = (SolidBrush)Brushes.Red; + GraphicsPath myGraphicsPath = new GraphicsPath(); + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new LinesCurvesAndShapes()); + } + public void Method11(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.DrawRectangle(myPen, 20, 10, 100, 50); + // + } + // 08d2cc9a-dc9d-4eed-bcbb-2c8e2ca5d3ae + // Open and Closed Curves in GDI+ + + public void Method21(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.FillPie(mySolidBrush, 0, 0, 140, 70, 0, 120); + myGraphics.DrawArc(myPen, 0, 0, 140, 70, 0, 120); + // + } + public void Method22(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Point[] myPointArray = + { + new Point(0, 0), + new Point(60, 20), + new Point(40, 50) + }; + myGraphics.DrawClosedCurve(myPen, myPointArray); + myGraphics.FillClosedCurve(mySolidBrush, myPointArray); + // + } + public void Method23(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + SolidBrush mySolidBrush = new SolidBrush(Color.Aqua); + GraphicsPath myGraphicsPath = new GraphicsPath(); + + Point[] myPointArray = + { + new Point(15, 20), + new Point(20, 40), + new Point(50, 30) + }; + + FontFamily myFontFamily = new FontFamily("Times New Roman"); + PointF myPointF = new PointF(50, 20); + StringFormat myStringFormat = new StringFormat(); + + myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180); + myGraphicsPath.AddCurve(myPointArray); + myGraphicsPath.AddString("a string in a path", myFontFamily, + 0, 24, myPointF, myStringFormat); + myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110); + + myGraphics.FillPath(mySolidBrush, myGraphicsPath); + myGraphics.DrawPath(myPen, myGraphicsPath); + // + } + // 09b3797a-6294-422d-9adf-a5a0a7695c0c + // Cardinal Splines in GDI+ + + public void Method31(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + Point[] myPointArray = + { + new Point(10, 10), + new Point(50, 40), + new Point(123, 200) + }; + // + myGraphics.DrawCurve(myPen, myPointArray, 1.5f); + // + } + // 30b25aae-e3eb-4479-bdb8-187cf651fc84 + // Pens, Lines, and Rectangles in GDI+ + + public void Method41(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.DrawLine(myPen, 4, 2, 12, 6); + // + } + public void Method42(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Point myStartPoint = new Point(4, 2); + Point myEndPoint = new Point(12, 6); + myGraphics.DrawLine(myPen, myStartPoint, myEndPoint); + // + } + public void Method43(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Pen myPen = new Pen(Color.Blue, 2); + myGraphics.DrawLine(myPen, 0, 0, 60, 30); + // + } + public void Method44(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myPen.DashStyle = DashStyle.Dash; + myGraphics.DrawLine(myPen, 100, 50, 300, 80); + // + } + public void Method45(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.DrawRectangle(myPen, 100, 50, 80, 40); + // + } + public void Method46(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Rectangle myRectangle = new Rectangle(100, 50, 80, 40); + myGraphics.DrawRectangle(myPen, myRectangle); + // + } + // 34f35133-a835-4ca4-81f6-0dfedee8b683 + // Ellipses and Arcs in GDI+ + + public void Method51(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.DrawEllipse(myPen, 100, 50, 80, 40); + // + } + public void Method52(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Rectangle myRectangle = new Rectangle(100, 50, 80, 40); + myGraphics.DrawEllipse(myPen, myRectangle); + // + } + public void Method53(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.DrawArc(myPen, 100, 50, 140, 70, 30, 180); + // + } + // 52184f9b-16dd-4bbd-85be-029112644ceb + // Regions in GDI+ + + public void Method61(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + Region myRegion = new Region(this.ClientRectangle); + // + myGraphics.FillRegion(mySolidBrush, myRegion); + // + } + // 5774ce1e-87d4-4bc7-88c4-4862052781b8 + // Bézier Splines in GDI+ + + public void Method71(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.DrawBezier(myPen, 0, 0, 40, 20, 80, 150, 100, 10); + // + } + // 810da1a4-c136-4abf-88df-68e49efdd8d4 + // Antialiasing with Lines and Curves + + public void Method81(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphics.SmoothingMode = SmoothingMode.AntiAlias; + myGraphics.DrawLine(myPen, 0, 0, 12, 8); + // + } + // 8b5f71d9-d2f0-4540-9c41-740f90fd4c26 + // Restricting the Drawing Surface in GDI+ + + public void Method91(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + Region myRegion = new Region(this.ClientRectangle); + // + myGraphics.Clip = myRegion; + myGraphics.DrawLine(myPen, 0, 0, 200, 200); + // + } + // a5500dec-666c-41fd-9da3-2169dd89c5eb + // Graphics Paths in GDI+ + + public void Method101(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + myGraphicsPath.AddLine(0, 0, 30, 20); + myGraphicsPath.AddEllipse(20, 20, 20, 40); + myGraphicsPath.AddBezier(30, 60, 70, 60, 50, 30, 100, 10); + myGraphics.DrawPath(myPen, myGraphicsPath); + // + } + public void Method102() + { + GraphicsPath graphicsPath1 = new GraphicsPath(); + GraphicsPath graphicsPath2 = new GraphicsPath(); + // + myGraphicsPath.AddPath(graphicsPath1, false); + myGraphicsPath.AddPath(graphicsPath2, false); + // + } + public void Method103(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + GraphicsPath myGraphicsPath = new GraphicsPath(); + + Point[] myPointArray = + { + new Point(5, 30), + new Point(20, 40), + new Point(50, 30) + }; + + FontFamily myFontFamily = new FontFamily("Times New Roman"); + PointF myPointF = new PointF(50, 20); + StringFormat myStringFormat = new StringFormat(); + + myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180); + myGraphicsPath.StartFigure(); + myGraphicsPath.AddCurve(myPointArray); + myGraphicsPath.AddString("a string in a path", myFontFamily, + 0, 24, myPointF, myStringFormat); + myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110); + myGraphics.DrawPath(myPen, myGraphicsPath); + // + } + // a72213d2-d69a-4c2b-a75c-be7b20390c13 + // Polygons in GDI+ + + public void Method111(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Point[] myPointArray = + { + new Point(0, 0), + new Point(50, 30), + new Point(30, 60) + }; + myGraphics.DrawPolygon(myPen, myPointArray); + // + } + // e863e2a7-0294-4130-99b6-f1ea3201e7cd + // Brushes and Filled Shapes in GDI+ + + public void Method121(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + SolidBrush mySolidBrush = new SolidBrush(Color.Red); + myGraphics.FillEllipse(mySolidBrush, 0, 0, 60, 40); + // + } + public void Method122() + { + // + HatchBrush myHatchBrush = + new HatchBrush(HatchStyle.Vertical, Color.Blue, Color.Green); + // + } + public void Method123(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + // + Image myImage = Image.FromFile("MyTexture.bmp"); + TextureBrush myTextureBrush = new TextureBrush(myImage); + myGraphics.FillEllipse(myTextureBrush, 0, 0, 100, 50); + // + } + public void Method124(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + Rectangle myRectangle = new Rectangle(new Point(10, 10), new Size(40, 50)); + // + LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush( + myRectangle, + Color.Blue, + Color.Green, + LinearGradientMode.Horizontal); + myGraphics.FillEllipse(myLinearGradientBrush, myRectangle); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.Designer.cs new file mode 100644 index 0000000000..85f76e4069 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.Designer.cs @@ -0,0 +1,61 @@ +namespace ManagedDOMStyles +{ + 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.webBrowser1 = new System.Windows.Forms.WebBrowser(); + this.SuspendLayout(); + // + // webBrowser1 + // + this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; + this.webBrowser1.Location = new System.Drawing.Point(0, 0); + this.webBrowser1.Name = "webBrowser1"; + this.webBrowser1.Size = new System.Drawing.Size(742, 318); + this.webBrowser1.Url = new System.Uri("c:\\userfiles\\jayallen\\ManagedDOMStyles\\test.htm", System.UriKind.Absolute); + this.webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(742, 318); + this.Controls.Add(this.webBrowser1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.WebBrowser webBrowser1; + + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.cs new file mode 100644 index 0000000000..e7a5dda8ca --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.Security.Permissions; + +namespace ManagedDOMStyles +{ + [PermissionSet(SecurityAction.Demand, Name="FullTrust")] + public partial class Form1 : Form + { + + public Form1() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + } + + // + StyleGenerator sg = null; + HtmlElement elem = null; + + private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) + { + sg = new StyleGenerator(); + + webBrowser1.Document.MouseOver += new HtmlElementEventHandler(Document_MouseOver); + webBrowser1.Document.MouseLeave += new HtmlElementEventHandler(Document_MouseLeave); + } + + void Document_MouseOver(object sender, HtmlElementEventArgs e) + { + elem = webBrowser1.Document.GetElementFromPoint(e.MousePosition); + if (elem.TagName.Equals("DIV")) + { + sg.ParseStyleString(elem.Style); + sg.SetStyle("font-style", "italic"); + elem.Style = sg.GetStyleString(); + } + } + + void Document_MouseLeave(object sender, HtmlElementEventArgs e) + { + if (elem != null) + { + sg.RemoveStyle("font-style"); + elem.Style = sg.GetStyleString(); + // Reset, since we may mouse over a new DIV element next time. + sg.Clear(); + } + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.resx new file mode 100644 index 0000000000..02bbfa2c72 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Form1.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/ManagedDOMStyles.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/ManagedDOMStyles.csproj new file mode 100644 index 0000000000..65b5d0003d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/ManagedDOMStyles.csproj @@ -0,0 +1,71 @@ + + + Debug + AnyCPU + 8.0.50304 + 2.0 + {6531B7A2-E512-4AC0-A5BF-4A41259FE13D} + WinExe + Properties + ManagedDOMStyles + ManagedDOMStyles + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Program.cs new file mode 100644 index 0000000000..d3d82caa63 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace ManagedDOMStyles +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..71bcd193f7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ManagedDOMStyles")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("MS")] +[assembly: AssemblyProduct("ManagedDOMStyles")] +[assembly: AssemblyCopyright("Copyright © MS 2005")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("401692d3-2767-47ab-a9d5-9213495a5054")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Resources.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..b9f49be438 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Resources.Designer.cs @@ -0,0 +1,74 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50304.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Resources.get_ResourceManager():System.Resources.ResourceManager")] +[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Resources.get_Culture():System.Globalization.CultureInfo")] +[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Resources.set_Culture(System.Globalization.CultureInfo):Void")] + +namespace ManagedDOMStyles.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ManagedDOMStyles.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Settings.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Settings.Designer.cs new file mode 100644 index 0000000000..56b7f6c10d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Settings.Designer.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50304.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Settings.get_Default():ManagedDOMStyles.Properties.Settings")] + +namespace ManagedDOMStyles.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = new Settings(); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Settings.settings new file mode 100644 index 0000000000..39645652af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/StyleGenerator.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/StyleGenerator.cs new file mode 100644 index 0000000000..9ad7216fa6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ManagedDOMStyles/CS/StyleGenerator.cs @@ -0,0 +1,113 @@ +// +using System; +using System.Collections.Generic; +using System.Text; + +namespace ManagedDOMStyles +{ + public class StyleGenerator + { + private Dictionary styleDB; + + public StyleGenerator() + { + styleDB = new Dictionary(); + } + + public bool ContainsStyle(string name) + { + return(styleDB.ContainsKey(name)); + } + + public string SetStyle(string name, string value) + { + string oldValue = ""; + + if (!(name.Length > 0)) + { + throw (new ArgumentException("Parameter name cannot be zero-length.")); + } + if (!(value.Length > 0)) + { + throw (new ArgumentException("Parameter value cannot be zero-length.")); + } + + if (styleDB.ContainsKey(name)) + { + oldValue = styleDB[name]; + } + + styleDB[name] = value; + + return (oldValue); + } + + public string GetStyle(string name) + { + if (!(name.Length > 0)) + { + throw (new ArgumentException("Parameter name cannot be zero-length.")); + } + + if (styleDB.ContainsKey(name)) + { + return (styleDB[name]); + } + else + { + return (""); + } + } + + public void RemoveStyle(string name) + { + if (styleDB.ContainsKey(name)) + { + styleDB.Remove(name); + } + } + + public string GetStyleString() + { + if (styleDB.Count > 0) + { + StringBuilder styleString = new StringBuilder(""); + foreach (string key in styleDB.Keys) + { + styleString.Append(String.Format("{0}:{1};", (object)key, (object)styleDB[key])); + } + + return (styleString.ToString()); + } + else + { + return (""); + } + } + + public void ParseStyleString(string styles) + { + if (styles.Length > 0) + { + string[] stylePairs = styles.Split(new char[] { ';' }); + foreach(string stylePair in stylePairs) + { + if (stylePairs.Length > 0) + { + string[] styleNameValue = stylePair.Split(new char[] { ':' }); + if (styleNameValue.Length == 2) + { + styleDB[styleNameValue[0]] = styleNameValue[1]; + } + } + } + } + } + + public void Clear() + { + styleDB.Clear(); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/Form1.Designer.cs new file mode 100644 index 0000000000..f6a5873dd7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/Form1.Designer.cs @@ -0,0 +1,100 @@ +namespace MaskedTextBoxDataCSharp +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + 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.firstName = new System.Windows.Forms.TextBox(); + this.lastName = new System.Windows.Forms.TextBox(); + this.phoneMask = new System.Windows.Forms.MaskedTextBox(); + this.previousButton = new System.Windows.Forms.Button(); + this.nextButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); +// +// firstName +// + this.firstName.Location = new System.Drawing.Point(13, 14); + this.firstName.Name = "firstName"; + this.firstName.Size = new System.Drawing.Size(184, 20); + this.firstName.TabIndex = 0; +// +// lastName +// + this.lastName.Location = new System.Drawing.Point(204, 14); + this.lastName.Name = "lastName"; + this.lastName.Size = new System.Drawing.Size(184, 20); + this.lastName.TabIndex = 1; +// +// phoneMask +// + this.phoneMask.Location = new System.Drawing.Point(441, 14); + this.phoneMask.Mask = "(009) 000-0000 x9999"; + this.phoneMask.Name = "phoneMask"; + this.phoneMask.Size = new System.Drawing.Size(169, 20); + this.phoneMask.TabIndex = 2; +// +// previousButton +// + this.previousButton.Location = new System.Drawing.Point(630, 14); + this.previousButton.Name = "previousButton"; + this.previousButton.TabIndex = 3; + this.previousButton.Text = "Previous"; + this.previousButton.Click += new System.EventHandler(this.previousButton_Click); +// +// nextButton +// + this.nextButton.Location = new System.Drawing.Point(723, 14); + this.nextButton.Name = "nextButton"; + this.nextButton.TabIndex = 4; + this.nextButton.Text = "Next"; + this.nextButton.Click += new System.EventHandler(this.nextButton_Click); +// +// Form1 +// + this.ClientSize = new System.Drawing.Size(887, 46); + this.Controls.Add(this.nextButton); + this.Controls.Add(this.previousButton); + this.Controls.Add(this.phoneMask); + this.Controls.Add(this.lastName); + this.Controls.Add(this.firstName); + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox firstName; + private System.Windows.Forms.TextBox lastName; + private System.Windows.Forms.MaskedTextBox phoneMask; + private System.Windows.Forms.Button previousButton; + private System.Windows.Forms.Button nextButton; + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/Program.cs new file mode 100644 index 0000000000..89ae88f6a0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/Program.cs @@ -0,0 +1,23 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +#endregion + +namespace MaskedTextBoxDataCSharp +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/form1.cs new file mode 100644 index 0000000000..54fae72c19 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/form1.cs @@ -0,0 +1,118 @@ +// +#region Using directives + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; +using System.Data.SqlClient; + +#endregion + +namespace MaskedTextBoxDataCSharp +{ + partial class Form1 : Form + { + Binding currentBinding, phoneBinding; + DataSet employeesTable = new DataSet(); + SqlConnection sc; + SqlDataAdapter dataConnect; + + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + DoMaskBinding(); + } + + private void DoMaskBinding() + { + try + { + sc = new SqlConnection("Data Source=localhost;Initial Catalog=NORTHWIND;Integrated Security=SSPI"); + sc.Open(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + return; + } + + dataConnect = new SqlDataAdapter("SELECT * FROM Employees", sc); + dataConnect.Fill(employeesTable, "Employees"); + + // Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects + // before adding them to the control - otherwise, we won't get a Format event on the + // initial load. + try + { + currentBinding = new Binding("Text", employeesTable, "Employees.FirstName"); + firstName.DataBindings.Add(currentBinding); + + currentBinding = new Binding("Text", employeesTable, "Employees.LastName"); + lastName.DataBindings.Add(currentBinding); + + phoneBinding =new Binding("Text", employeesTable, "Employees.HomePhone"); + // We must add the event handlers before we bind, or the Format event will not get called + // for the first record. + phoneBinding.Format += new ConvertEventHandler(phoneBinding_Format); + phoneBinding.Parse += new ConvertEventHandler(phoneBinding_Parse); + phoneMask.DataBindings.Add(phoneBinding); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + return; + } + } + + private void phoneBinding_Format(Object sender, ConvertEventArgs e) + { + String ext; + + DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current; + if (currentRow["Extension"] == null) + { + ext = ""; + } else + { + ext = currentRow["Extension"].ToString(); + } + + e.Value = e.Value.ToString().Trim() + " x" + ext; + } + + private void phoneBinding_Parse(Object sender, ConvertEventArgs e) + { + String phoneNumberAndExt = e.Value.ToString(); + + int extIndex = phoneNumberAndExt.IndexOf("x"); + String ext = phoneNumberAndExt.Substring(extIndex).Trim(); + String phoneNumber = phoneNumberAndExt.Substring(0, extIndex).Trim(); + + //Get the current binding object, and set the new extension manually. + DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current; + // Remove the "x" from the extension. + currentRow["Extension"] = ext.Substring(1); + + //Return the phone number. + e.Value = phoneNumber; + } + + private void previousButton_Click(object sender, EventArgs e) + { + BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position - 1; + } + + private void nextButton_Click(object sender, EventArgs e) + { + BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position + 1; + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/makefile new file mode 100644 index 0000000000..ec684468ea --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/MaskedTextBoxData/CS/makefile @@ -0,0 +1,2 @@ +all: + csc /t:library /out:mydll.dll Form1.Designer.cs Program.cs form1.cs \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AsyncOperationManager/CS/primenumbercalculatormain.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AsyncOperationManager/CS/primenumbercalculatormain.cs new file mode 100644 index 0000000000..5193171b99 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AsyncOperationManager/CS/primenumbercalculatormain.cs @@ -0,0 +1,1042 @@ +// +// +using System; +using System.Collections; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Globalization; +using System.Threading; +using System.Windows.Forms; +// + +namespace AsyncOperationManagerExample +{ + // This form tests the PrimeNumberCalculator component. + public class PrimeNumberCalculatorMain : System.Windows.Forms.Form + { + ///////////////////////////////////////////////////////////// + // Private fields + // + #region Private fields + + private PrimeNumberCalculator primeNumberCalculator1; + private System.Windows.Forms.GroupBox taskGroupBox; + private System.Windows.Forms.ListView listView1; + private System.Windows.Forms.ColumnHeader taskIdColHeader; + private System.Windows.Forms.ColumnHeader progressColHeader; + private System.Windows.Forms.ColumnHeader currentColHeader; + private System.Windows.Forms.Panel buttonPanel; + private System.Windows.Forms.Panel panel2; + private System.Windows.Forms.Button startAsyncButton; + private System.Windows.Forms.Button cancelButton; + private System.Windows.Forms.ColumnHeader testNumberColHeader; + private System.Windows.Forms.ColumnHeader resultColHeader; + private System.Windows.Forms.ColumnHeader firstDivisorColHeader; + private System.ComponentModel.IContainer components; + private int progressCounter; + private int progressInterval = 100; + + #endregion // Private fields + + ///////////////////////////////////////////////////////////// + // Construction and destruction + // + #region Private fields + public PrimeNumberCalculatorMain () + { + // + // Required for Windows Form Designer support + // + InitializeComponent(); + + // Hook up event handlers. + this.primeNumberCalculator1.CalculatePrimeCompleted += + new CalculatePrimeCompletedEventHandler( + primeNumberCalculator1_CalculatePrimeCompleted); + + this.primeNumberCalculator1.ProgressChanged += + new ProgressChangedEventHandler( + primeNumberCalculator1_ProgressChanged); + + this.listView1.SelectedIndexChanged += + new EventHandler(listView1_SelectedIndexChanged); + } + + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose( disposing ); + } + + #endregion // Construction and destruction + + ///////////////////////////////////////////////////////////// + // + #region Implementation + + // This event handler selects a number randomly to test + // for primality. It then starts the asynchronous + // calculation by calling the PrimeNumberCalculator + // component's CalculatePrimeAsync method. + private void startAsyncButton_Click ( + System.Object sender, System.EventArgs e) + { + // Randomly choose test numbers + // up to 200,000 for primality. + Random rand = new Random(); + int testNumber = rand.Next(200000); + + // Task IDs are Guids. + Guid taskId = Guid.NewGuid(); + this.AddListViewItem(taskId, testNumber); + + // Start the asynchronous task. + this.primeNumberCalculator1.CalculatePrimeAsync( + testNumber, + taskId); + } + + private void listView1_SelectedIndexChanged( + object sender, + EventArgs e) + { + this.cancelButton.Enabled = CanCancel(); + } + + // This event handler cancels all pending tasks that are + // selected in the ListView control. + private void cancelButton_Click( + System.Object sender, + System.EventArgs e) + { + Guid taskId = Guid.Empty; + + // Cancel all selected tasks. + foreach(ListViewItem lvi in this.listView1.SelectedItems) + { + // Tasks that have been completed or canceled have + // their corresponding ListViewItem.Tag property + // set to null. + if (lvi.Tag != null) + { + taskId = (Guid)lvi.Tag; + this.primeNumberCalculator1.CancelAsync(taskId); + lvi.Selected = false; + } + } + + cancelButton.Enabled = false; + } + + // + // This event handler updates the ListView control when the + // PrimeNumberCalculator raises the ProgressChanged event. + // + // On fast computers, the PrimeNumberCalculator can raise many + // successive ProgressChanged events, so the user interface + // may be flooded with messages. To prevent the user interface + // from hanging, progress is only reported at intervals. + private void primeNumberCalculator1_ProgressChanged( + ProgressChangedEventArgs e) + { + if (this.progressCounter++ % this.progressInterval == 0) + { + Guid taskId = (Guid)e.UserState; + + if (e is CalculatePrimeProgressChangedEventArgs) + { + CalculatePrimeProgressChangedEventArgs cppcea = + e as CalculatePrimeProgressChangedEventArgs; + + this.UpdateListViewItem( + taskId, + cppcea.ProgressPercentage, + cppcea.LatestPrimeNumber); + } + else + { + this.UpdateListViewItem( + taskId, + e.ProgressPercentage); + } + } + else if (this.progressCounter > this.progressInterval) + { + this.progressCounter = 0; + } + } + // + + // + // This event handler updates the ListView control when the + // PrimeNumberCalculator raises the CalculatePrimeCompleted + // event. The ListView item is updated with the appropriate + // outcome of the calculation: Canceled, Error, or result. + private void primeNumberCalculator1_CalculatePrimeCompleted( + object sender, + CalculatePrimeCompletedEventArgs e) + { + Guid taskId = (Guid)e.UserState; + + if (e.Cancelled) + { + string result = "Canceled"; + + ListViewItem lvi = UpdateListViewItem(taskId, result); + + if (lvi != null) + { + lvi.BackColor = Color.Pink; + lvi.Tag = null; + } + } + else if (e.Error != null) + { + string result = "Error"; + + ListViewItem lvi = UpdateListViewItem(taskId, result); + + if (lvi != null) + { + lvi.BackColor = Color.Red; + lvi.ForeColor = Color.White; + lvi.Tag = null; + } + } + else + { + bool result = e.IsPrime; + + ListViewItem lvi = UpdateListViewItem( + taskId, + result, + e.FirstDivisor); + + if (lvi != null) + { + lvi.BackColor = Color.LightGray; + lvi.Tag = null; + } + } + } + // + + #endregion // Implementation + + ///////////////////////////////////////////////////////////// + // + #region Private Methods + + private ListViewItem AddListViewItem( + Guid guid, + int testNumber ) + { + ListViewItem lvi = new ListViewItem(); + lvi.Text = testNumber.ToString( + CultureInfo.CurrentCulture.NumberFormat); + + lvi.SubItems.Add("Not Started"); + lvi.SubItems.Add("1"); + lvi.SubItems.Add(guid.ToString()); + lvi.SubItems.Add("---"); + lvi.SubItems.Add("---"); + lvi.Tag = guid; + + this.listView1.Items.Add( lvi ); + + return lvi; + } + + private ListViewItem UpdateListViewItem( + Guid guid, + int percentComplete, + int current ) + { + ListViewItem lviRet = null; + + foreach (ListViewItem lvi in this.listView1.Items) + { + if (lvi.Tag != null) + { + if ((Guid)lvi.Tag == guid) + { + lvi.SubItems[1].Text = + percentComplete.ToString( + CultureInfo.CurrentCulture.NumberFormat); + lvi.SubItems[2].Text = + current.ToString( + CultureInfo.CurrentCulture.NumberFormat); + lviRet = lvi; + break; + } + } + } + + return lviRet; + } + + private ListViewItem UpdateListViewItem( + Guid guid, + int percentComplete, + int current, + bool result, + int firstDivisor ) + { + ListViewItem lviRet = null; + + foreach (ListViewItem lvi in this.listView1.Items) + { + if ((Guid)lvi.Tag == guid) + { + lvi.SubItems[1].Text = + percentComplete.ToString( + CultureInfo.CurrentCulture.NumberFormat); + lvi.SubItems[2].Text = + current.ToString( + CultureInfo.CurrentCulture.NumberFormat); + lvi.SubItems[4].Text = + result ? "Prime" : "Composite"; + lvi.SubItems[5].Text = + firstDivisor.ToString( + CultureInfo.CurrentCulture.NumberFormat); + + lviRet = lvi; + + break; + } + } + + return lviRet; + } + + private ListViewItem UpdateListViewItem( + Guid guid, + int percentComplete ) + { + ListViewItem lviRet = null; + + foreach (ListViewItem lvi in this.listView1.Items) + { + if (lvi.Tag != null) + { + if ((Guid)lvi.Tag == guid) + { + lvi.SubItems[1].Text = + percentComplete.ToString( + CultureInfo.CurrentCulture.NumberFormat); + lviRet = lvi; + break; + } + } + } + + return lviRet; + } + + private ListViewItem UpdateListViewItem( + Guid guid, + bool result, + int firstDivisor ) + { + ListViewItem lviRet = null; + + foreach (ListViewItem lvi in this.listView1.Items) + { + if (lvi.Tag != null) + { + if ((Guid)lvi.Tag == guid) + { + lvi.SubItems[4].Text = + result ? "Prime" : "Composite"; + lvi.SubItems[5].Text = + firstDivisor.ToString( + CultureInfo.CurrentCulture.NumberFormat); + lviRet = lvi; + break; + } + } + } + + return lviRet; + } + + private ListViewItem UpdateListViewItem( + Guid guid, + string result) + { + ListViewItem lviRet = null; + + foreach (ListViewItem lvi in this.listView1.Items) + { + if (lvi.Tag != null) + { + if ((Guid)lvi.Tag == guid) + { + lvi.SubItems[4].Text = result; + lviRet = lvi; + break; + } + } + } + + return lviRet; + } + + private bool CanCancel() + { + bool oneIsActive = false; + + foreach(ListViewItem lvi in this.listView1.SelectedItems) + { + if (lvi.Tag != null) + { + oneIsActive = true; + break; + } + } + + return( oneIsActive == true ); + } + + #endregion + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.taskGroupBox = new System.Windows.Forms.GroupBox(); + this.buttonPanel = new System.Windows.Forms.Panel(); + this.cancelButton = new System.Windows.Forms.Button(); + this.startAsyncButton = new System.Windows.Forms.Button(); + this.listView1 = new System.Windows.Forms.ListView(); + this.testNumberColHeader = new System.Windows.Forms.ColumnHeader(); + this.progressColHeader = new System.Windows.Forms.ColumnHeader(); + this.currentColHeader = new System.Windows.Forms.ColumnHeader(); + this.taskIdColHeader = new System.Windows.Forms.ColumnHeader(); + this.resultColHeader = new System.Windows.Forms.ColumnHeader(); + this.firstDivisorColHeader = new System.Windows.Forms.ColumnHeader(); + this.panel2 = new System.Windows.Forms.Panel(); + this.primeNumberCalculator1 = new AsyncOperationManagerExample.PrimeNumberCalculator(this.components); + this.taskGroupBox.SuspendLayout(); + this.buttonPanel.SuspendLayout(); + this.SuspendLayout(); + // + // taskGroupBox + // + this.taskGroupBox.Controls.Add(this.buttonPanel); + this.taskGroupBox.Controls.Add(this.listView1); + this.taskGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.taskGroupBox.Location = new System.Drawing.Point(0, 0); + this.taskGroupBox.Name = "taskGroupBox"; + this.taskGroupBox.Size = new System.Drawing.Size(608, 254); + this.taskGroupBox.TabIndex = 1; + this.taskGroupBox.TabStop = false; + this.taskGroupBox.Text = "Tasks"; + // + // buttonPanel + // + this.buttonPanel.Controls.Add(this.cancelButton); + this.buttonPanel.Controls.Add(this.startAsyncButton); + this.buttonPanel.Dock = System.Windows.Forms.DockStyle.Bottom; + this.buttonPanel.Location = new System.Drawing.Point(3, 176); + this.buttonPanel.Name = "buttonPanel"; + this.buttonPanel.Size = new System.Drawing.Size(602, 75); + this.buttonPanel.TabIndex = 1; + // + // cancelButton + // + this.cancelButton.Enabled = false; + this.cancelButton.Location = new System.Drawing.Point(128, 24); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(88, 23); + this.cancelButton.TabIndex = 1; + this.cancelButton.Text = "Cancel"; + this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); + // + // startAsyncButton + // + this.startAsyncButton.Location = new System.Drawing.Point(24, 24); + this.startAsyncButton.Name = "startAsyncButton"; + this.startAsyncButton.Size = new System.Drawing.Size(88, 23); + this.startAsyncButton.TabIndex = 0; + this.startAsyncButton.Text = "Start New Task"; + this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click); + // + // listView1 + // + this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.testNumberColHeader, + this.progressColHeader, + this.currentColHeader, + this.taskIdColHeader, + this.resultColHeader, + this.firstDivisorColHeader}); + this.listView1.Dock = System.Windows.Forms.DockStyle.Fill; + this.listView1.FullRowSelect = true; + this.listView1.GridLines = true; + this.listView1.Location = new System.Drawing.Point(3, 16); + this.listView1.Name = "listView1"; + this.listView1.Size = new System.Drawing.Size(602, 160); + this.listView1.TabIndex = 0; + this.listView1.View = System.Windows.Forms.View.Details; + // + // testNumberColHeader + // + this.testNumberColHeader.Text = "Test Number"; + this.testNumberColHeader.Width = 80; + // + // progressColHeader + // + this.progressColHeader.Text = "Progress"; + // + // currentColHeader + // + this.currentColHeader.Text = "Current"; + // + // taskIdColHeader + // + this.taskIdColHeader.Text = "Task ID"; + this.taskIdColHeader.Width = 200; + // + // resultColHeader + // + this.resultColHeader.Text = "Result"; + this.resultColHeader.Width = 80; + // + // firstDivisorColHeader + // + this.firstDivisorColHeader.Text = "First Divisor"; + this.firstDivisorColHeader.Width = 80; + // + // panel2 + // + this.panel2.Location = new System.Drawing.Point(200, 128); + this.panel2.Name = "panel2"; + this.panel2.TabIndex = 2; + // + // PrimeNumberCalculatorMain + // + this.ClientSize = new System.Drawing.Size(608, 254); + this.Controls.Add(this.taskGroupBox); + this.Name = "PrimeNumberCalculatorMain"; + this.Text = "Prime Number Calculator"; + this.taskGroupBox.ResumeLayout(false); + this.buttonPanel.ResumeLayout(false); + this.ResumeLayout(false); + } + #endregion + + [STAThread] + static void Main() + { + Application.Run(new PrimeNumberCalculatorMain()); + } + } + + // + + ///////////////////////////////////////////////////////////// + #region PrimeNumberCalculator Implementation + + // + public delegate void ProgressChangedEventHandler( + ProgressChangedEventArgs e); + + public delegate void CalculatePrimeCompletedEventHandler( + object sender, + CalculatePrimeCompletedEventArgs e); + // + + // This class implements the Event-based Asynchronous Pattern. + // It asynchronously computes whether a number is prime or + // composite (not prime). + public class PrimeNumberCalculator : Component + { + // + private delegate void WorkerEventHandler( + int numberToCheck, + AsyncOperation asyncOp); + // + + // + private SendOrPostCallback onProgressReportDelegate; + private SendOrPostCallback onCompletedDelegate; + // + + // + private HybridDictionary userStateToLifetime = + new HybridDictionary(); + // + + private System.ComponentModel.Container components = null; + + ///////////////////////////////////////////////////////////// + #region Public events + + // + public event ProgressChangedEventHandler ProgressChanged; + public event CalculatePrimeCompletedEventHandler CalculatePrimeCompleted; + // + + #endregion + + ///////////////////////////////////////////////////////////// + #region Construction and destruction + + public PrimeNumberCalculator(IContainer container) + { + container.Add(this); + InitializeComponent(); + + InitializeDelegates(); + } + + // + public PrimeNumberCalculator() + { + InitializeComponent(); + + InitializeDelegates(); + } + // + + // + protected virtual void InitializeDelegates() + { + onProgressReportDelegate = + new SendOrPostCallback(ReportProgress); + onCompletedDelegate = + new SendOrPostCallback(CalculateCompleted); + } + // + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + #endregion // Construction and destruction + + ///////////////////////////////////////////////////////////// + /// + #region Implementation + + // + // This method starts an asynchronous calculation. + // First, it checks the supplied task ID for uniqueness. + // If taskId is unique, it creates a new WorkerEventHandler + // and calls its BeginInvoke method to start the calculation. + public virtual void CalculatePrimeAsync( + int numberToTest, + object taskId) + { + // Create an AsyncOperation for taskId. + AsyncOperation asyncOp = + AsyncOperationManager.CreateOperation(taskId); + + // Multiple threads will access the task dictionary, + // so it must be locked to serialize access. + lock (userStateToLifetime.SyncRoot) + { + if (userStateToLifetime.Contains(taskId)) + { + throw new ArgumentException( + "Task ID parameter must be unique", + "taskId"); + } + + userStateToLifetime[taskId] = asyncOp; + } + + // Start the asynchronous operation. + WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker); + workerDelegate.BeginInvoke( + numberToTest, + asyncOp, + null, + null); + } + // + + // + // Utility method for determining if a + // task has been canceled. + private bool TaskCanceled(object taskId) + { + return( userStateToLifetime[taskId] == null ); + } + // + + // + // This method cancels a pending asynchronous operation. + public void CancelAsync(object taskId) + { + AsyncOperation asyncOp = userStateToLifetime[taskId] as AsyncOperation; + if (asyncOp != null) + { + lock (userStateToLifetime.SyncRoot) + { + userStateToLifetime.Remove(taskId); + } + } + } + // + + // + // This method performs the actual prime number computation. + // It is executed on the worker thread. + private void CalculateWorker( + int numberToTest, + AsyncOperation asyncOp) + { + bool isPrime = false; + int firstDivisor = 1; + Exception e = null; + + // Check that the task is still active. + // The operation may have been canceled before + // the thread was scheduled. + if (!TaskCanceled(asyncOp.UserSuppliedState)) + { + try + { + // Find all the prime numbers up to + // the square root of numberToTest. + ArrayList primes = BuildPrimeNumberList( + numberToTest, + asyncOp); + + // Now we have a list of primes less than + // numberToTest. + isPrime = IsPrime( + primes, + numberToTest, + out firstDivisor); + } + catch (Exception ex) + { + e = ex; + } + } + + //CalculatePrimeState calcState = new CalculatePrimeState( + // numberToTest, + // firstDivisor, + // isPrime, + // e, + // TaskCanceled(asyncOp.UserSuppliedState), + // asyncOp); + + //this.CompletionMethod(calcState); + + this.CompletionMethod( + numberToTest, + firstDivisor, + isPrime, + e, + TaskCanceled(asyncOp.UserSuppliedState), + asyncOp); + + //completionMethodDelegate(calcState); + } + // + + // + // This method computes the list of prime numbers used by the + // IsPrime method. + private ArrayList BuildPrimeNumberList( + int numberToTest, + AsyncOperation asyncOp) + { + ProgressChangedEventArgs e = null; + ArrayList primes = new ArrayList(); + int firstDivisor; + int n = 5; + + // Add the first prime numbers. + primes.Add(2); + primes.Add(3); + + // Do the work. + while (n < numberToTest && + !TaskCanceled( asyncOp.UserSuppliedState ) ) + { + if (IsPrime(primes, n, out firstDivisor)) + { + // Report to the client that a prime was found. + e = new CalculatePrimeProgressChangedEventArgs( + n, + (int)((float)n / (float)numberToTest * 100), + asyncOp.UserSuppliedState); + + asyncOp.Post(this.onProgressReportDelegate, e); + + primes.Add(n); + + // Yield the rest of this time slice. + Thread.Sleep(0); + } + + // Skip even numbers. + n += 2; + } + + return primes; + } + // + + // + // This method tests n for primality against the list of + // prime numbers contained in the primes parameter. + private bool IsPrime( + ArrayList primes, + int n, + out int firstDivisor) + { + bool foundDivisor = false; + bool exceedsSquareRoot = false; + + int i = 0; + int divisor = 0; + firstDivisor = 1; + + // Stop the search if: + // there are no more primes in the list, + // there is a divisor of n in the list, or + // there is a prime that is larger than + // the square root of n. + while ( + (i < primes.Count) && + !foundDivisor && + !exceedsSquareRoot) + { + // The divisor variable will be the smallest + // prime number not yet tried. + divisor = (int)primes[i++]; + + // Determine whether the divisor is greater + // than the square root of n. + if (divisor * divisor > n) + { + exceedsSquareRoot = true; + } + // Determine whether the divisor is a factor of n. + else if (n % divisor == 0) + { + firstDivisor = divisor; + foundDivisor = true; + } + } + + return !foundDivisor; + } + // + + // + // This method is invoked via the AsyncOperation object, + // so it is guaranteed to be executed on the correct thread. + private void CalculateCompleted(object operationState) + { + CalculatePrimeCompletedEventArgs e = + operationState as CalculatePrimeCompletedEventArgs; + + OnCalculatePrimeCompleted(e); + } + + // This method is invoked via the AsyncOperation object, + // so it is guaranteed to be executed on the correct thread. + private void ReportProgress(object state) + { + ProgressChangedEventArgs e = + state as ProgressChangedEventArgs; + + OnProgressChanged(e); + } + + protected void OnCalculatePrimeCompleted( + CalculatePrimeCompletedEventArgs e) + { + if (CalculatePrimeCompleted != null) + { + CalculatePrimeCompleted(this, e); + } + } + + protected void OnProgressChanged(ProgressChangedEventArgs e) + { + if (ProgressChanged != null) + { + ProgressChanged(e); + } + } + // + + // + // This is the method that the underlying, free-threaded + // asynchronous behavior will invoke. This will happen on + // an arbitrary thread. + private void CompletionMethod( + int numberToTest, + int firstDivisor, + bool isPrime, + Exception exception, + bool canceled, + AsyncOperation asyncOp ) + + { + // If the task was not previously canceled, + // remove the task from the lifetime collection. + if (!canceled) + { + lock (userStateToLifetime.SyncRoot) + { + userStateToLifetime.Remove(asyncOp.UserSuppliedState); + } + } + + // Package the results of the operation in a + // CalculatePrimeCompletedEventArgs. + CalculatePrimeCompletedEventArgs e = + new CalculatePrimeCompletedEventArgs( + numberToTest, + firstDivisor, + isPrime, + exception, + canceled, + asyncOp.UserSuppliedState); + + // End the task. The asyncOp object is responsible + // for marshaling the call. + asyncOp.PostOperationCompleted(onCompletedDelegate, e); + + // Note that after the call to OperationCompleted, + // asyncOp is no longer usable, and any attempt to use it + // will cause an exception to be thrown. + } + // + + #endregion + + ///////////////////////////////////////////////////////////// + #region Component Designer generated code + + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + + } + + // + public class CalculatePrimeProgressChangedEventArgs : + ProgressChangedEventArgs + { + private int latestPrimeNumberValue = 1; + + public CalculatePrimeProgressChangedEventArgs( + int latestPrime, + int progressPercentage, + object userToken) : base( progressPercentage, userToken ) + { + this.latestPrimeNumberValue = latestPrime; + } + + public int LatestPrimeNumber + { + get + { + return latestPrimeNumberValue; + } + } + } + // + + // + public class CalculatePrimeCompletedEventArgs : + AsyncCompletedEventArgs + { + private int numberToTestValue = 0; + private int firstDivisorValue = 1; + private bool isPrimeValue; + + public CalculatePrimeCompletedEventArgs( + int numberToTest, + int firstDivisor, + bool isPrime, + Exception e, + bool canceled, + object state) : base(e, canceled, state) + { + this.numberToTestValue = numberToTest; + this.firstDivisorValue = firstDivisor; + this.isPrimeValue = isPrime; + } + + public int NumberToTest + { + get + { + // Raise an exception if the operation failed or + // was canceled. + RaiseExceptionIfNecessary(); + + // If the operation was successful, return the + // property value. + return numberToTestValue; + } + } + + public int FirstDivisor + { + get + { + // Raise an exception if the operation failed or + // was canceled. + RaiseExceptionIfNecessary(); + + // If the operation was successful, return the + // property value. + return firstDivisorValue; + } + } + + public bool IsPrime + { + get + { + // Raise an exception if the operation failed or + // was canceled. + RaiseExceptionIfNecessary(); + + // If the operation was successful, return the + // property value. + return isPrimeValue; + } + } + } + + // + + #endregion + + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs new file mode 100644 index 0000000000..4229689d88 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/attributesdemocontrol.cs @@ -0,0 +1,632 @@ +// +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing; +using System.Data; +using System.Reflection; +using System.Text; +using System.Windows.Forms; +// + +// This sample demonstrates the use of various attributes for +// authoring a control. +namespace AttributesDemoControlLibrary +{ + // This is the event handler delegate for the ThresholdExceeded event. + public delegate void ThresholdExceededEventHandler(ThresholdExceededEventArgs e); + + // + // + // This control demonstrates a simple logging capability. + [ComplexBindingProperties("DataSource", "DataMember")] + [DefaultBindingProperty("TitleText")] + [DefaultEvent("ThresholdExceeded")] + [DefaultProperty("Threshold")] + [HelpKeywordAttribute(typeof(UserControl))] + [ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")] + public class AttributesDemoControl : UserControl + { + // + + // This backs the Threshold property. + private object thresholdValue; + + // The default fore color value for DataGridView cells that + // contain values that exceed the threshold. + private static Color defaultAlertForeColorValue = Color.White; + + // The default back color value for DataGridView cells that + // contain values that exceed the threshold. + private static Color defaultAlertBackColorValue = Color.Red; + + // The ambient color value. + private static Color ambientColorValue = Color.Empty; + + // The fore color value for DataGridView cells that + // contain values that exceed the threshold. + private Color alertForeColorValue = defaultAlertForeColorValue; + + // The back color value for DataGridView cells that + // contain values that exceed the threshold. + private Color alertBackColorValue = defaultAlertBackColorValue; + + // Child controls that comprise this UserControl. + private TableLayoutPanel tableLayoutPanel1; + private DataGridView dataGridView1; + private Label label1; + + // Required for designer support. + private System.ComponentModel.IContainer components = null; + + // Default constructor. + public AttributesDemoControl() + { + InitializeComponent(); + } + + // + [Category("Appearance")] + [Description("The title of the log data.")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] + [Localizable(true)] + [HelpKeywordAttribute("AttributesDemoControlLibrary.AttributesDemoControl.TitleText")] + public string TitleText + { + get + { + return this.label1.Text; + } + + set + { + this.label1.Text = value; + } + } + // + + // + // The inherited Text property is hidden at design time and + // raises an exception at run time. This enforces a requirement + // that client code uses the TitleText property instead. + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public override string Text + { + get + { + throw new NotSupportedException(); + } + set + { + throw new NotSupportedException(); + } + } + // + + // + [AmbientValue(typeof(Color), "Empty")] + [Category("Appearance")] + [DefaultValue(typeof(Color), "White")] + [Description("The color used for painting alert text.")] + public Color AlertForeColor + { + get + { + if (this.alertForeColorValue == Color.Empty && + this.Parent != null) + { + return Parent.ForeColor; + } + + return this.alertForeColorValue; + } + + set + { + this.alertForeColorValue = value; + } + } + + // This method is used by designers to enable resetting the + // property to its default value. + public void ResetAlertForeColor() + { + this.AlertForeColor = AttributesDemoControl.defaultAlertForeColorValue; + } + + // This method indicates to designers whether the property + // value is different from the ambient value, in which case + // the designer should persist the value. + private bool ShouldSerializeAlertForeColor() + { + return (this.alertForeColorValue != AttributesDemoControl.ambientColorValue); + } + // + + // + [AmbientValue(typeof(Color), "Empty")] + [Category("Appearance")] + [DefaultValue(typeof(Color), "Red")] + [Description("The background color for painting alert text.")] + public Color AlertBackColor + { + get + { + if (this.alertBackColorValue == Color.Empty && + this.Parent != null) + { + return Parent.BackColor; + } + + return this.alertBackColorValue; + } + + set + { + this.alertBackColorValue = value; + } + } + + // This method is used by designers to enable resetting the + // property to its default value. + public void ResetAlertBackColor() + { + this.AlertBackColor = AttributesDemoControl.defaultAlertBackColorValue; + } + + // This method indicates to designers whether the property + // value is different from the ambient value, in which case + // the designer should persist the value. + private bool ShouldSerializeAlertBackColor() + { + return (this.alertBackColorValue != AttributesDemoControl.ambientColorValue); + } + // + + // + [Category("Data")] + [Description("Indicates the source of data for the control.")] + [RefreshProperties(RefreshProperties.Repaint)] + [AttributeProvider(typeof(IListSource))] + public object DataSource + { + get + { + return this.dataGridView1.DataSource; + } + + set + { + this.dataGridView1.DataSource = value; + } + } + // + + // + [Category("Data")] + [Description("Indicates a sub-list of the data source to show in the control.")] + public string DataMember + { + get + { + return this.dataGridView1.DataMember; + } + + set + { + this.dataGridView1.DataMember = value; + } + } + // + + // + // This property would normally have its BrowsableAttribute + // set to false, but this code demonstrates using + // ReadOnlyAttribute, so BrowsableAttribute is true to show + // it in any attached PropertyGrid control. + [Browsable(true)] + [Category("Behavior")] + [Description("The timestamp of the latest entry.")] + [ReadOnly(true)] + public DateTime CurrentLogTime + { + get + { + int lastRowIndex = + this.dataGridView1.Rows.GetLastRow( + DataGridViewElementStates.Visible); + + if (lastRowIndex > -1) + { + DataGridViewRow lastRow = this.dataGridView1.Rows[lastRowIndex]; + DataGridViewCell lastCell = lastRow.Cells["EntryTime"]; + return ((DateTime)lastCell.Value); + } + else + { + return DateTime.MinValue; + } + } + + set + { + } + } + // + + // + [Category("Behavior")] + [Description("The value above which the ThresholdExceeded event will be raised.")] + public object Threshold + { + get + { + return this.thresholdValue; + } + + set + { + this.thresholdValue = value; + } + } + // + + // + // This property exists only to demonstrate the + // PasswordPropertyText attribute. When this control + // is attached to a PropertyGrid control, the returned + // string will be displayed with obscuring characters + // such as asterisks. This property has no other effect. + [Category("Security")] + [Description("Demonstrates PasswordPropertyTextAttribute.")] + [PasswordPropertyText(true)] + public string Password + { + get + { + return "This is a demo password."; + } + } + // + + // + // This property exists only to demonstrate the + // DisplayName attribute. When this control + // is attached to a PropertyGrid control, the + // property will be appear as "RenamedProperty" + // instead of "MisnamedProperty". + [Description("Demonstrates DisplayNameAttribute.")] + [DisplayName("RenamedProperty")] + public bool MisnamedProperty + { + get + { + return true; + } + } + // + + // This is the declaration for the ThresholdExceeded event. + public event ThresholdExceededEventHandler ThresholdExceeded; + + #region Implementation + + // + // This is the event handler for the DataGridView control's + // CellFormatting event. Handling this event allows the + // AttributesDemoControl to examine the incoming log entries + // from the data source as they arrive. + // + // If the cell for which this event is raised holds the + // log entry's timestamp, the cell value is formatted with + // the full date/time pattern. + // + // Otherwise, the cell's value is assumed to hold the log + // entry value. If the value exceeds the threshold value, + // the cell is painted with the colors specified by the + // AlertForeColor and AlertBackColor properties, after which + // the ThresholdExceeded is raised. For this comparison to + // succeed, the log entry's type must implement the IComparable + // interface. + private void dataGridView1_CellFormatting( + object sender, + DataGridViewCellFormattingEventArgs e) + { + try + { + if (e.Value != null) + { + if (e.Value is DateTime) + { + // Display the log entry time with the + // full date/time pattern (long time). + e.CellStyle.Format = "F"; + } + else + { + // Scroll to the most recent entry. + DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex]; + DataGridViewCell cell = row.Cells[e.ColumnIndex]; + this.dataGridView1.FirstDisplayedCell = cell; + + if (this.thresholdValue != null) + { + // Get the type of the log entry. + object val = e.Value; + Type paramType = val.GetType(); + + // Compare the log entry value to the threshold value. + // Use reflection to call the CompareTo method on the + // template parameter's type. + int compareVal = (int)paramType.InvokeMember( + "CompareTo", + BindingFlags.Default | BindingFlags.InvokeMethod, + null, + e.Value, + new object[] { this.thresholdValue }, + System.Globalization.CultureInfo.InvariantCulture); + + // If the log entry value exceeds the threshold value, + // set the cell's fore color and back color properties + // and raise the ThresholdExceeded event. + if (compareVal > 0) + { + e.CellStyle.BackColor = this.alertBackColorValue; + e.CellStyle.ForeColor = this.alertForeColorValue; + + ThresholdExceededEventArgs teea = + new ThresholdExceededEventArgs( + this.thresholdValue, + e.Value); + this.ThresholdExceeded(teea); + } + } + } + } + } + catch (Exception ex) + { + Trace.WriteLine(ex.Message); + } + } + // + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.label1 = new System.Windows.Forms.Label(); + this.tableLayoutPanel1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.SuspendLayout(); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.AutoSize = true; + this.tableLayoutPanel1.ColumnCount = 1; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 1); + this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); + this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel1.Location = new System.Drawing.Point(10, 10); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10); + this.tableLayoutPanel1.RowCount = 2; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(425, 424); + this.tableLayoutPanel1.TabIndex = 0; + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + this.dataGridView1.AllowUserToOrderColumns = true; + this.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; + dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; + dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; + dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; + dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; + dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; + dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False; + this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.ColumnHeadersHeight = 4; + this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView1.Location = new System.Drawing.Point(13, 57); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.ReadOnly = true; + this.dataGridView1.RowHeadersVisible = false; + this.dataGridView1.Size = new System.Drawing.Size(399, 354); + this.dataGridView1.TabIndex = 1; + this.dataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dataGridView1_CellFormatting); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.BackColor = System.Drawing.SystemColors.Control; + this.label1.Dock = System.Windows.Forms.DockStyle.Fill; + this.label1.Location = new System.Drawing.Point(13, 13); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(399, 38); + this.label1.TabIndex = 2; + this.label1.Text = "label1"; + this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // AttributesDemoControl + // + this.Controls.Add(this.tableLayoutPanel1); + this.Name = "AttributesDemoControl"; + this.Padding = new System.Windows.Forms.Padding(10); + this.Size = new System.Drawing.Size(445, 444); + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + } + // + + // + // This is the EventArgs class for the ThresholdExceeded event. + public class ThresholdExceededEventArgs : EventArgs + { + private object thresholdValue = null; + private object exceedingValue = null; + + public ThresholdExceededEventArgs( + object thresholdValue, + object exceedingValue) + { + this.thresholdValue = thresholdValue; + this.exceedingValue = exceedingValue; + } + + public object ThresholdValue + { + get + { + return this.thresholdValue; + } + } + + public object ExceedingValue + { + get + { + return this.exceedingValue; + } + } + } + // + + // + // This class encapsulates a log entry. It is a parameterized + // type (also known as a template class). The parameter type T + // defines the type of data being logged. For threshold detection + // to work, this type must implement the IComparable interface. + [TypeConverter("LogEntryTypeConverter")] + public class LogEntry where T : IComparable + { + private T entryValue; + private DateTime entryTimeValue; + + public LogEntry( + T value, + DateTime time) + { + this.entryValue = value; + this.entryTimeValue = time; + } + + public T Entry + { + get + { + return this.entryValue; + } + } + + public DateTime EntryTime + { + get + { + return this.entryTimeValue; + } + } + + // + // This is the TypeConverter for the LogEntry class. + public class LogEntryTypeConverter : TypeConverter + { + // + public override bool CanConvertFrom( + ITypeDescriptorContext context, + Type sourceType) + { + if (sourceType == typeof(string)) + { + return true; + } + + return base.CanConvertFrom(context, sourceType); + } + // + + // + public override object ConvertFrom( + ITypeDescriptorContext context, + System.Globalization.CultureInfo culture, + object value) + { + if (value is string) + { + string[] v = ((string)value).Split(new char[] { '|' }); + + Type paramType = typeof(T); + T entryValue = (T)paramType.InvokeMember( + "Parse", + BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, + null, + null, + new string[] { v[0] }, + culture); + + return new LogEntry( + entryValue, + DateTime.Parse(v[2])); + } + + return base.ConvertFrom(context, culture, value); + } + // + + // + public override object ConvertTo( + ITypeDescriptorContext context, + System.Globalization.CultureInfo culture, + object value, + Type destinationType) + { + if (destinationType == typeof(string)) + { + LogEntry le = value as LogEntry; + + string stringRepresentation = + String.Format("{0} | {1}", + le.Entry, + le.EntryTime); + + return stringRepresentation; + } + + return base.ConvertTo(context, culture, value, destinationType); + } + // + } + // + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/form1.cs new file mode 100644 index 0000000000..21001c62de --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/form1.cs @@ -0,0 +1,284 @@ +// +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing; +using System.Windows.Forms; +using AttributesDemoControlLibrary; +// + +// This sample demonstrates using the AttributesDemoControl to log +// data from a data source. +namespace AttributesDemoControlTest +{ + public class Form1 : Form + { + private BindingSource bindingSource1; + private System.Diagnostics.PerformanceCounter performanceCounter1; + private Button startButton; + private Button stopButton; + private System.Timers.Timer timer1; + private ToolStripStatusLabel statusStripPanel1; + private NumericUpDown numericUpDown1; + private GroupBox groupBox1; + private GroupBox groupBox2; + private TableLayoutPanel tableLayoutPanel1; + private AttributesDemoControl attributesDemoControl1; + private System.ComponentModel.IContainer components = null; + + // This form uses an AttributesDemoControl to display a stream + // of LogEntry objects. The data stream is generated by polling + // a performance counter and communicating the counter values + // to the control with data binding. + public Form1() + { + InitializeComponent(); + + // Set the initial value of the threshold up/down control + // to the control's threshold value. + this.numericUpDown1.Value = + (decimal)(float)this.attributesDemoControl1.Threshold; + + // Assign the performance counter's name to the control's + // title text. + this.attributesDemoControl1.TitleText = + this.performanceCounter1.CounterName; + } + + // This method handles the ThresholdExceeded event. It posts + // the value that exceeded the threshold to the status strip. + private void attributesDemoControl1_ThresholdExceeded( + ThresholdExceededEventArgs e) + { + string msg = String.Format( + "{0}: Value {1} exceeded threshold {2}", + this.attributesDemoControl1.CurrentLogTime, + e.ExceedingValue, + e.ThresholdValue); + + this.ReportStatus( msg ); + } + + // + // This method handles the timer's Elapsed event. It queries + // the performance counter for the next value, packs the + // value in a LogEntry object, and adds the new LogEntry to + // the list managed by the BindingSource. + private void timer1_Elapsed( + object sender, + System.Timers.ElapsedEventArgs e) + { + // Get the latest value from the performance counter. + float val = this.performanceCounter1.NextValue(); + + // The performance counter returns values of type float, + // but any type that implements the IComparable interface + // will work. + LogEntry entry = new LogEntry(val, DateTime.Now); + + // Add the new LogEntry to the BindingSource list. + this.bindingSource1.Add(entry); + } + // + + private void numericUpDown1_ValueChanged(object sender, EventArgs e) + { + this.attributesDemoControl1.Threshold = + (float)this.numericUpDown1.Value; + + string msg = String.Format( + "Threshold changed to {0}", + this.attributesDemoControl1.Threshold); + + this.ReportStatus(msg); + } + + private void startButton_Click(object sender, EventArgs e) + { + this.ReportStatus(DateTime.Now + ": Starting"); + + this.timer1.Start(); + } + + private void stopButton_Click(object sender, EventArgs e) + { + this.ReportStatus(DateTime.Now + ": Stopping"); + + this.timer1.Stop(); + } + + private void ReportStatus(string msg) + { + if (msg != null) + { + this.statusStripPanel1.Text = msg; + } + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components); + this.performanceCounter1 = new System.Diagnostics.PerformanceCounter(); + this.startButton = new System.Windows.Forms.Button(); + this.stopButton = new System.Windows.Forms.Button(); + this.timer1 = new System.Timers.Timer(); + this.statusStripPanel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.attributesDemoControl1 = new AttributesDemoControlLibrary.AttributesDemoControl(); + ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit(); + + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); + this.groupBox1.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // performanceCounter1 + // + this.performanceCounter1.CategoryName = ".NET CLR Memory"; + this.performanceCounter1.CounterName = "Gen 0 heap size"; + this.performanceCounter1.InstanceName = "_Global_"; + // + // startButton + // + this.startButton.Location = new System.Drawing.Point(31, 25); + this.startButton.Name = "startButton"; + this.startButton.TabIndex = 1; + this.startButton.Text = "Start"; + this.startButton.Click += new System.EventHandler(this.startButton_Click); + // + // stopButton + // + this.stopButton.Location = new System.Drawing.Point(112, 25); + this.stopButton.Name = "stopButton"; + this.stopButton.TabIndex = 2; + this.stopButton.Text = "Stop"; + this.stopButton.Click += new System.EventHandler(this.stopButton_Click); + // + // timer1 + // + this.timer1.Interval = 1000; + this.timer1.SynchronizingObject = this; + this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed); + // + // statusStripPanel1 + // + this.statusStripPanel1.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter; + this.statusStripPanel1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; + this.statusStripPanel1.Name = "statusStripPanel1"; + this.statusStripPanel1.Text = "Ready"; + // + // numericUpDown1 + // + this.numericUpDown1.Location = new System.Drawing.Point(37, 29); + this.numericUpDown1.Maximum = new decimal(new int[] { + 1410065408, + 2, + 0, + 0}); + this.numericUpDown1.Name = "numericUpDown1"; + this.numericUpDown1.TabIndex = 7; + this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); + // + // groupBox1 + // + this.groupBox1.Anchor = System.Windows.Forms.AnchorStyles.None; + this.groupBox1.Controls.Add(this.numericUpDown1); + this.groupBox1.Location = new System.Drawing.Point(280, 326); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(200, 70); + this.groupBox1.TabIndex = 13; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "Threshold Value"; + // + // groupBox2 + // + this.groupBox2.Anchor = System.Windows.Forms.AnchorStyles.None; + this.groupBox2.Controls.Add(this.startButton); + this.groupBox2.Controls.Add(this.stopButton); + this.groupBox2.Location = new System.Drawing.Point(26, 327); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(214, 68); + this.groupBox2.TabIndex = 14; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "Logging"; + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel1.Controls.Add(this.groupBox2, 0, 1); + this.tableLayoutPanel1.Controls.Add(this.groupBox1, 1, 1); + this.tableLayoutPanel1.Controls.Add(this.attributesDemoControl1, 0, 0); + this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10); + this.tableLayoutPanel1.RowCount = 2; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(514, 411); + this.tableLayoutPanel1.TabIndex = 15; + // + // attributesDemoControl1 + // + this.tableLayoutPanel1.SetColumnSpan(this.attributesDemoControl1, 2); + this.attributesDemoControl1.DataMember = ""; + this.attributesDemoControl1.DataSource = this.bindingSource1; + this.attributesDemoControl1.Dock = System.Windows.Forms.DockStyle.Fill; + this.attributesDemoControl1.Location = new System.Drawing.Point(13, 13); + this.attributesDemoControl1.Name = "attributesDemoControl1"; + this.attributesDemoControl1.Padding = new System.Windows.Forms.Padding(10); + this.attributesDemoControl1.Size = new System.Drawing.Size(488, 306); + this.attributesDemoControl1.TabIndex = 0; + this.attributesDemoControl1.Threshold = 200000F; + this.attributesDemoControl1.TitleText = "TITLE"; + this.attributesDemoControl1.ThresholdExceeded += new AttributesDemoControlLibrary.ThresholdExceededEventHandler(this.attributesDemoControl1_ThresholdExceeded); + // + // Form1 + // + this.BackColor = System.Drawing.SystemColors.Control; + this.ClientSize = new System.Drawing.Size(514, 430); + this.Controls.Add(this.tableLayoutPanel1); + this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Name = "Form1"; + this.Text = "Form1"; + ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); + this.groupBox1.ResumeLayout(false); + this.groupBox2.ResumeLayout(false); + this.tableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/makefile new file mode 100644 index 0000000000..cc48e87e95 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/CS/makefile @@ -0,0 +1,10 @@ +all: AttributesDemoControl.dll form1.exe + +AttributesDemoControl.dll: AttributesDemoControl.cs + csc /target:library AttributesDemoControl.cs + +Form1.exe: AttributesDemoControl.dll + csc form1.cs /r:AttributesDemoControl.dll + +clean: + del *.exe *.dll *.bin *.obj \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs new file mode 100644 index 0000000000..cae0ae241b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/CS/Form1.cs @@ -0,0 +1,232 @@ +// +// +using System; +using System.ComponentModel; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; +// + +namespace BackgroundWorkerExample +{ + public class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // + private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) + { + // Do not access the form's BackgroundWorker reference directly. + // Instead, use the reference provided by the sender parameter. + BackgroundWorker bw = sender as BackgroundWorker; + + // Extract the argument. + int arg = (int)e.Argument; + + // Start the time-consuming operation. + e.Result = TimeConsumingOperation(bw, arg); + + // If the operation was canceled by the user, + // set the DoWorkEventArgs.Cancel property to true. + if (bw.CancellationPending) + { + e.Cancel = true; + } + } + // + + // + // This event handler demonstrates how to interpret + // the outcome of the asynchronous operation implemented + // in the DoWork event handler. + private void backgroundWorker1_RunWorkerCompleted( + object sender, + RunWorkerCompletedEventArgs e) + { + if (e.Cancelled) + { + // The user canceled the operation. + MessageBox.Show("Operation was canceled"); + } + else if (e.Error != null) + { + // There was an error during the operation. + string msg = String.Format("An error occurred: {0}", e.Error.Message); + MessageBox.Show(msg); + } + else + { + // The operation completed normally. + string msg = String.Format("Result = {0}", e.Result); + MessageBox.Show(msg); + } + } + // + + // + // This method models an operation that may take a long time + // to run. It can be cancelled, it can raise an exception, + // or it can exit normally and return a result. These outcomes + // are chosen randomly. + private int TimeConsumingOperation( + BackgroundWorker bw, + int sleepPeriod ) + { + int result = 0; + + Random rand = new Random(); + + while (!bw.CancellationPending) + { + bool exit = false; + + switch (rand.Next(3)) + { + // Raise an exception. + case 0: + { + throw new Exception("An error condition occurred."); + break; + } + + // Sleep for the number of milliseconds + // specified by the sleepPeriod parameter. + case 1: + { + Thread.Sleep(sleepPeriod); + break; + } + + // Exit and return normally. + case 2: + { + result = 23; + exit = true; + break; + } + + default: + { + break; + } + } + + if( exit ) + { + break; + } + } + + return result; + } + // + + // + private void startBtn_Click(object sender, EventArgs e) + { + this.backgroundWorker1.RunWorkerAsync(2000); + } + // + + // + private void cancelBtn_Click(object sender, EventArgs e) + { + this.backgroundWorker1.CancelAsync(); + } + // + + /// + /// 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.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); + this.startBtn = new System.Windows.Forms.Button(); + this.cancelBtn = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // backgroundWorker1 + // + this.backgroundWorker1.WorkerSupportsCancellation = true; + this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); + this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); + // + // startBtn + // + this.startBtn.Location = new System.Drawing.Point(12, 12); + this.startBtn.Name = "startBtn"; + this.startBtn.Size = new System.Drawing.Size(75, 23); + this.startBtn.TabIndex = 0; + this.startBtn.Text = "Start"; + this.startBtn.Click += new System.EventHandler(this.startBtn_Click); + // + // cancelBtn + // + this.cancelBtn.Location = new System.Drawing.Point(94, 11); + this.cancelBtn.Name = "cancelBtn"; + this.cancelBtn.Size = new System.Drawing.Size(75, 23); + this.cancelBtn.TabIndex = 1; + this.cancelBtn.Text = "Cancel"; + this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(183, 49); + this.Controls.Add(this.cancelBtn); + this.Controls.Add(this.startBtn); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + #endregion + + private System.ComponentModel.BackgroundWorker backgroundWorker1; + private System.Windows.Forms.Button startBtn; + private System.Windows.Forms.Button cancelBtn; + } + + public class Program + { + private Program() + { + } + + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs new file mode 100644 index 0000000000..c64ac02b7a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/CS/Form1.cs @@ -0,0 +1,172 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; +using System.Xml; + +public class Form1 : Form +{ + private BackgroundWorker backgroundWorker1; + private Button downloadButton; + private ProgressBar progressBar1; + private XmlDocument document = null; + + public Form1() + { + InitializeComponent(); + + // Instantiate BackgroundWorker and attach handlers to its + // DoWork and RunWorkerCompleted events. + backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); + backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); + backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); + } + + // + private void downloadButton_Click(object sender, EventArgs e) + { + // Start the download operation in the background. + this.backgroundWorker1.RunWorkerAsync(); + + // Disable the button for the duration of the download. + this.downloadButton.Enabled = false; + + // Once you have started the background thread you + // can exit the handler and the application will + // wait until the RunWorkerCompleted event is raised. + + // Or if you want to do something else in the main thread, + // such as update a progress bar, you can do so in a loop + // while checking IsBusy to see if the background task is + // still running. + + while (this.backgroundWorker1.IsBusy) + { + progressBar1.Increment(1); + // Keep UI messages moving, so the form remains + // responsive during the asynchronous operation. + Application.DoEvents(); + } + } + // + + // + private void backgroundWorker1_DoWork( + object sender, + DoWorkEventArgs e) + { + document = new XmlDocument(); + + // Uncomment the following line to + // simulate a noticeable latency. + //Thread.Sleep(5000); + + // Replace this file name with a valid file name. + document.Load(@"http://www.tailspintoys.com/sample.xml"); + } + // + + // + private void backgroundWorker1_RunWorkerCompleted( + object sender, + RunWorkerCompletedEventArgs e) + { + // Set progress bar to 100% in case it's not already there. + progressBar1.Value = 100; + + if (e.Error == null) + { + MessageBox.Show(document.InnerXml, "Download Complete"); + } + else + { + MessageBox.Show( + "Failed to download file", + "Download failed", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + + // Enable the download button and reset the progress bar. + this.downloadButton.Enabled = true; + progressBar1.Value = 0; + } + // + + #region Windows Form Designer generated code + + /// + /// 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); + } + + /// + /// Required method for Designer support + /// + private void InitializeComponent() + { + this.downloadButton = new System.Windows.Forms.Button(); + this.progressBar1 = new System.Windows.Forms.ProgressBar(); + this.SuspendLayout(); + // + // downloadButton + // + this.downloadButton.Location = new System.Drawing.Point(12, 12); + this.downloadButton.Name = "downloadButton"; + this.downloadButton.Size = new System.Drawing.Size(100, 23); + this.downloadButton.TabIndex = 0; + this.downloadButton.Text = "Download file"; + this.downloadButton.UseVisualStyleBackColor = true; + this.downloadButton.Click += new System.EventHandler(this.downloadButton_Click); + // + // progressBar1 + // + this.progressBar1.Location = new System.Drawing.Point(12, 50); + this.progressBar1.Name = "progressBar1"; + this.progressBar1.Size = new System.Drawing.Size(100, 26); + this.progressBar1.TabIndex = 1; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(133, 104); + this.Controls.Add(this.progressBar1); + this.Controls.Add(this.downloadButton); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + #endregion +} + +static class Program +{ + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs new file mode 100644 index 0000000000..be4aae2d85 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/CS/fibonacciform.cs @@ -0,0 +1,318 @@ +// +// +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; +// + +namespace BackgroundWorkerExample +{ + public class FibonacciForm : System.Windows.Forms.Form + { + // + private int numberToCompute = 0; + private int highestPercentageReached = 0; + // + + private System.Windows.Forms.NumericUpDown numericUpDown1; + private System.Windows.Forms.Button startAsyncButton; + private System.Windows.Forms.Button cancelAsyncButton; + private System.Windows.Forms.ProgressBar progressBar1; + private System.Windows.Forms.Label resultLabel; + private System.ComponentModel.BackgroundWorker backgroundWorker1; + + public FibonacciForm() + { + InitializeComponent(); + + InitializeBackgroundWorker(); + } + + // Set up the BackgroundWorker object by + // attaching event handlers. + private void InitializeBackgroundWorker() + { + backgroundWorker1.DoWork += + new DoWorkEventHandler(backgroundWorker1_DoWork); + backgroundWorker1.RunWorkerCompleted += + new RunWorkerCompletedEventHandler( + backgroundWorker1_RunWorkerCompleted); + backgroundWorker1.ProgressChanged += + new ProgressChangedEventHandler( + backgroundWorker1_ProgressChanged); + } + + // + private void startAsyncButton_Click(System.Object sender, + System.EventArgs e) + { + // Reset the text in the result label. + resultLabel.Text = String.Empty; + + // Disable the UpDown control until + // the asynchronous operation is done. + this.numericUpDown1.Enabled = false; + + // Disable the Start button until + // the asynchronous operation is done. + this.startAsyncButton.Enabled = false; + + // Enable the Cancel button while + // the asynchronous operation runs. + this.cancelAsyncButton.Enabled = true; + + // Get the value from the UpDown control. + numberToCompute = (int)numericUpDown1.Value; + + // Reset the variable for percentage tracking. + highestPercentageReached = 0; + + // + // Start the asynchronous operation. + backgroundWorker1.RunWorkerAsync(numberToCompute); + // + } + // + + // + private void cancelAsyncButton_Click(System.Object sender, + System.EventArgs e) + { + // Cancel the asynchronous operation. + this.backgroundWorker1.CancelAsync(); + + // Disable the Cancel button. + cancelAsyncButton.Enabled = false; + } + // + + // + // This event handler is where the actual, + // potentially time-consuming work is done. + private void backgroundWorker1_DoWork(object sender, + DoWorkEventArgs e) + { + // Get the BackgroundWorker that raised this event. + BackgroundWorker worker = sender as BackgroundWorker; + + // Assign the result of the computation + // to the Result property of the DoWorkEventArgs + // object. This is will be available to the + // RunWorkerCompleted eventhandler. + e.Result = ComputeFibonacci((int)e.Argument, worker, e); + } + // + + // + // This event handler deals with the results of the + // background operation. + private void backgroundWorker1_RunWorkerCompleted( + object sender, RunWorkerCompletedEventArgs e) + { + // First, handle the case where an exception was thrown. + if (e.Error != null) + { + MessageBox.Show(e.Error.Message); + } + else if (e.Cancelled) + { + // Next, handle the case where the user canceled + // the operation. + // Note that due to a race condition in + // the DoWork event handler, the Cancelled + // flag may not have been set, even though + // CancelAsync was called. + resultLabel.Text = "Canceled"; + } + else + { + // Finally, handle the case where the operation + // succeeded. + resultLabel.Text = e.Result.ToString(); + } + + // Enable the UpDown control. + this.numericUpDown1.Enabled = true; + + // Enable the Start button. + startAsyncButton.Enabled = true; + + // Disable the Cancel button. + cancelAsyncButton.Enabled = false; + } + // + + // + // This event handler updates the progress bar. + private void backgroundWorker1_ProgressChanged(object sender, + ProgressChangedEventArgs e) + { + this.progressBar1.Value = e.ProgressPercentage; + } + // + + // + // This is the method that does the actual work. For this + // example, it computes a Fibonacci number and + // reports progress as it does its work. + long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e) + { + // The parameter n must be >= 0 and <= 91. + // Fib(n), with n > 91, overflows a long. + if ((n < 0) || (n > 91)) + { + throw new ArgumentException( + "value must be >= 0 and <= 91", "n"); + } + + long result = 0; + + // + // Abort the operation if the user has canceled. + // Note that a call to CancelAsync may have set + // CancellationPending to true just after the + // last invocation of this method exits, so this + // code will not have the opportunity to set the + // DoWorkEventArgs.Cancel flag to true. This means + // that RunWorkerCompletedEventArgs.Cancelled will + // not be set to true in your RunWorkerCompleted + // event handler. This is a race condition. + + // + if (worker.CancellationPending) + { + e.Cancel = true; + } + // + else + { + if (n < 2) + { + result = 1; + } + else + { + result = ComputeFibonacci(n - 1, worker, e) + + ComputeFibonacci(n - 2, worker, e); + } + + // + // Report progress as a percentage of the total task. + int percentComplete = + (int)((float)n / (float)numberToCompute * 100); + if (percentComplete > highestPercentageReached) + { + highestPercentageReached = percentComplete; + worker.ReportProgress(percentComplete); + } + // + } + // + + return result; + } + // + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); + this.startAsyncButton = new System.Windows.Forms.Button(); + this.cancelAsyncButton = new System.Windows.Forms.Button(); + this.resultLabel = new System.Windows.Forms.Label(); + this.progressBar1 = new System.Windows.Forms.ProgressBar(); + this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); + this.SuspendLayout(); + // + // numericUpDown1 + // + this.numericUpDown1.Location = new System.Drawing.Point(16, 16); + this.numericUpDown1.Maximum = new System.Decimal(new int[] { + 91, + 0, + 0, + 0}); + this.numericUpDown1.Minimum = new System.Decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numericUpDown1.Name = "numericUpDown1"; + this.numericUpDown1.Size = new System.Drawing.Size(80, 20); + this.numericUpDown1.TabIndex = 0; + this.numericUpDown1.Value = new System.Decimal(new int[] { + 1, + 0, + 0, + 0}); + // + // startAsyncButton + // + this.startAsyncButton.Location = new System.Drawing.Point(16, 72); + this.startAsyncButton.Name = "startAsyncButton"; + this.startAsyncButton.Size = new System.Drawing.Size(120, 23); + this.startAsyncButton.TabIndex = 1; + this.startAsyncButton.Text = "Start Async"; + this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click); + // + // cancelAsyncButton + // + this.cancelAsyncButton.Enabled = false; + this.cancelAsyncButton.Location = new System.Drawing.Point(153, 72); + this.cancelAsyncButton.Name = "cancelAsyncButton"; + this.cancelAsyncButton.Size = new System.Drawing.Size(119, 23); + this.cancelAsyncButton.TabIndex = 2; + this.cancelAsyncButton.Text = "Cancel Async"; + this.cancelAsyncButton.Click += new System.EventHandler(this.cancelAsyncButton_Click); + // + // resultLabel + // + this.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; + this.resultLabel.Location = new System.Drawing.Point(112, 16); + this.resultLabel.Name = "resultLabel"; + this.resultLabel.Size = new System.Drawing.Size(160, 23); + this.resultLabel.TabIndex = 3; + this.resultLabel.Text = "(no result)"; + this.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; + // + // progressBar1 + // + this.progressBar1.Location = new System.Drawing.Point(18, 48); + this.progressBar1.Name = "progressBar1"; + this.progressBar1.Size = new System.Drawing.Size(256, 8); + this.progressBar1.Step = 2; + this.progressBar1.TabIndex = 4; + // + // backgroundWorker1 + // + this.backgroundWorker1.WorkerReportsProgress = true; + this.backgroundWorker1.WorkerSupportsCancellation = true; + // + // FibonacciForm + // + this.ClientSize = new System.Drawing.Size(292, 118); + this.Controls.Add(this.progressBar1); + this.Controls.Add(this.resultLabel); + this.Controls.Add(this.cancelAsyncButton); + this.Controls.Add(this.startAsyncButton); + this.Controls.Add(this.numericUpDown1); + this.Name = "FibonacciForm"; + this.Text = "Fibonacci Calculator"; + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); + this.ResumeLayout(false); + } + #endregion + + [STAThread] + static void Main() + { + Application.Run(new FibonacciForm()); + } + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/CS/form1.cs new file mode 100644 index 0000000000..75e6e1778b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/CS/form1.cs @@ -0,0 +1,134 @@ +// +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +// + +// This sample demonstrates the use of the +// DesignerSerializationVisibility attribute +// to serialize a collection of strings +// at design time. +namespace SerializationDemo +{ + class Form1 : Form + { + private SerializationDemoControl serializationDemoControl1; + + public Form1() + { + InitializeComponent(); + } + + // The Windows Forms Designer emits code to this method. + // If an instance of SerializationDemoControl is added + // to the form, the Strings will be serialized here. + private void InitializeComponent() + { + this.serializationDemoControl1 = new SerializationDemo.SerializationDemoControl(); + this.SuspendLayout(); + // + // serializationDemoControl1 + // + this.serializationDemoControl1.Location = new System.Drawing.Point(0, 0); + this.serializationDemoControl1.Name = "serializationDemoControl1"; + this.serializationDemoControl1.Padding = new System.Windows.Forms.Padding(5); + this.serializationDemoControl1.TabIndex = 0; + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.serializationDemoControl1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } + + // + public class SerializationDemoControl : UserControl + { + // This is the TextBox contained by + // the SerializationDemoControl. + private System.Windows.Forms.TextBox textBox1; + + // + // This field backs the Strings property. + private String[] stringsValue = new String[1]; + // + + public SerializationDemoControl() + { + InitializeComponent(); + } + + // + // When the DesignerSerializationVisibility attribute has + // a value of "Content" or "Visible" the designer will + // serialize the property. This property can also be edited + // at design time with a CollectionEditor. + [DesignerSerializationVisibility( + DesignerSerializationVisibility.Content )] + public String[] Strings + { + get + { + return this.stringsValue; + } + set + { + this.stringsValue = value; + + // Populate the contained TextBox with the values + // in the stringsValue array. + StringBuilder sb = + new StringBuilder(this.stringsValue.Length); + + for (int i = 0; i < this.stringsValue.Length; i++) + { + sb.Append(this.stringsValue[i]); + sb.Append("\r\n"); + } + + this.textBox1.Text = sb.ToString(); + } + } + // + + private void InitializeComponent() + { + this.textBox1 = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + + // Settings for the contained TextBox control. + this.textBox1.AutoSize = false; + this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBox1.Location = new System.Drawing.Point(5, 5); + this.textBox1.Margin = new System.Windows.Forms.Padding(0); + this.textBox1.Multiline = true; + this.textBox1.Name = "textBox1"; + this.textBox1.ReadOnly = true; + this.textBox1.ScrollBars = ScrollBars.Vertical; + this.textBox1.Size = new System.Drawing.Size(140, 140); + this.textBox1.TabIndex = 0; + + // Settings for SerializationDemoControl. + this.Controls.Add(this.textBox1); + this.Name = "SerializationDemoControl"; + this.Padding = new System.Windows.Forms.Padding(5); + this.ResumeLayout(false); + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/BusinessObjectBase.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/BusinessObjectBase.cs new file mode 100644 index 0000000000..1d59e60d33 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/BusinessObjectBase.cs @@ -0,0 +1,32 @@ +// +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; +using System.Diagnostics; + +namespace IListSourceCS +{ + public class BusinessObjectBase : INotifyPropertyChanged + { + #region INotifyPropertyChanged Members + + public event PropertyChangedEventHandler PropertyChanged; + + protected virtual void OnPropertyChanged(string propertyName) + { + OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); + } + + private void OnPropertyChanged(PropertyChangedEventArgs e) + { + if (null != PropertyChanged) + { + PropertyChanged(this, e); + } + } + + #endregion + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Employee.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Employee.cs new file mode 100644 index 0000000000..b087fc185b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Employee.cs @@ -0,0 +1,65 @@ +// +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; + +namespace IListSourceCS +{ + public class Employee : BusinessObjectBase + { + private string _id; + private string _name; + private Decimal parkingId; + + public Employee() : this(string.Empty, 0) {} + public Employee(string name) : this(name, 0) {} + + public Employee(string name, Decimal parkingId) : base() + { + this._id = System.Guid.NewGuid().ToString(); + + // Set values + this.Name = name; + this.ParkingID = parkingId; + } + + public string ID + { + get { return _id; } + } + + const string NAME = "Name"; + public string Name + { + get { return _name; } + set + { + if (_name != value) + { + _name = value; + + // Raise the PropertyChanged event. + OnPropertyChanged(NAME); + } + } + } + + const string PARKING_ID = "Salary"; + public Decimal ParkingID + { + get { return parkingId; } + set + { + if (parkingId != value) + { + parkingId = value; + + // Raise the PropertyChanged event. + OnPropertyChanged(PARKING_ID); + } + } + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/EmployeeListSource.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/EmployeeListSource.cs new file mode 100644 index 0000000000..c69875cb3b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/EmployeeListSource.cs @@ -0,0 +1,51 @@ +// +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; + +namespace IListSourceCS +{ + public class EmployeeListSource : Component, IListSource + { + public EmployeeListSource() {} + + public EmployeeListSource(IContainer container) + { + container.Add(this); + } + + // + #region IListSource Members + + // + bool IListSource.ContainsListCollection + { + get { return false; } + } + // + + // + System.Collections.IList IListSource.GetList() + { + BindingList ble = new BindingList(); + + if (!this.DesignMode) + { + ble.Add(new Employee("Aaberg, Jesper", 26000000)); + ble.Add(new Employee("Cajhen, Janko", 19600000)); + ble.Add(new Employee("Furse, Kari", 19000000)); + ble.Add(new Employee("Langhorn, Carl", 16000000)); + ble.Add(new Employee("Todorov, Teodor", 15700000)); + ble.Add(new Employee("Verebélyi, Ágnes", 15700000)); + } + + return ble; + } + // + + #endregion + // + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Form1.cs new file mode 100644 index 0000000000..794e60e334 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/Form1.cs @@ -0,0 +1,152 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace IListSourceCS +{ + public class Form1 : Form + { + private System.ComponentModel.IContainer components = null; + private FlowLayoutPanel flowLayoutPanel1; + private Label label2; + private DataGridView dataGridView1; + private DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn; + private DataGridViewTextBoxColumn salaryDataGridViewTextBoxColumn; + private DataGridViewTextBoxColumn iDDataGridViewTextBoxColumn; + private EmployeeListSource employeeListSource1; + + public Form1() + { + InitializeComponent(); + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); + this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.label2 = new System.Windows.Forms.Label(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.nameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.salaryDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.iDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.employeeListSource1 = new EmployeeListSource(this.components); + this.flowLayoutPanel1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.SuspendLayout(); + // + // flowLayoutPanel1 + // + this.flowLayoutPanel1.AutoSize = true; + this.flowLayoutPanel1.Controls.Add(this.label2); + this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; + this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); + this.flowLayoutPanel1.Name = "flowLayoutPanel1"; + this.flowLayoutPanel1.Size = new System.Drawing.Size(416, 51); + this.flowLayoutPanel1.TabIndex = 11; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(3, 6); + this.label2.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(408, 39); + this.label2.TabIndex = 0; + this.label2.Text = "This sample demonstrates how to implement the IListSource interface. In this sam" + + "ple, a DataGridView is bound at design time to a Component (employeeListSource1)" + + " that implements IListSource."; + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); + this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; + this.dataGridView1.AutoGenerateColumns = false; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.nameDataGridViewTextBoxColumn, + this.salaryDataGridViewTextBoxColumn, + this.iDDataGridViewTextBoxColumn}); + this.dataGridView1.DataSource = this.employeeListSource1; + this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView1.Location = new System.Drawing.Point(0, 51); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowHeadersVisible = false; + this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + this.dataGridView1.Size = new System.Drawing.Size(416, 215); + this.dataGridView1.TabIndex = 12; + // + // nameDataGridViewTextBoxColumn + // + this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name"; + this.nameDataGridViewTextBoxColumn.FillWeight = 131.7987F; + this.nameDataGridViewTextBoxColumn.HeaderText = "Name"; + this.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn"; + // + // salaryDataGridViewTextBoxColumn + // + this.salaryDataGridViewTextBoxColumn.DataPropertyName = "ParkingID"; + this.salaryDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2; + this.salaryDataGridViewTextBoxColumn.FillWeight = 121.8274F; + this.salaryDataGridViewTextBoxColumn.HeaderText = "Parking ID"; + this.salaryDataGridViewTextBoxColumn.Name = "salaryDataGridViewTextBoxColumn"; + // + // iDDataGridViewTextBoxColumn + // + this.iDDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; + this.iDDataGridViewTextBoxColumn.DataPropertyName = "ID"; + this.iDDataGridViewTextBoxColumn.FillWeight = 46.37391F; + this.iDDataGridViewTextBoxColumn.HeaderText = "ID"; + this.iDDataGridViewTextBoxColumn.Name = "iDDataGridViewTextBoxColumn"; + this.iDDataGridViewTextBoxColumn.ReadOnly = true; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(416, 266); + this.Controls.Add(this.dataGridView1); + this.Controls.Add(this.flowLayoutPanel1); + this.Name = "Form1"; + this.Text = "IListSource Sample"; + this.flowLayoutPanel1.ResumeLayout(false); + this.flowLayoutPanel1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + } + + static class Program + { + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/makefile new file mode 100644 index 0000000000..65140588fe --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IListSource/CS/makefile @@ -0,0 +1,5 @@ +IListSource.exe: BusinessObjectBase.cs Employee.cs EmployeeListSource.cs Form1.cs + csc /t:exe /out:IListSource.exe BusinessObjectBase.cs Employee.cs EmployeeListSource.cs Form1.cs + +clean: + del *.dll *.bin *.exe \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/CS/Form1.cs new file mode 100644 index 0000000000..1ba4ddbc9d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/CS/Form1.cs @@ -0,0 +1,159 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Runtime.CompilerServices; +using System.Windows.Forms; + +// Change the namespace to the project name. +namespace TestNotifyPropertyChangedCS +{ + // This form demonstrates using a BindingSource to bind + // a list to a DataGridView control. The list does not + // raise change notifications. However the DemoCustomer type + // in the list does. + public partial class Form1 : Form + { + // This button causes the value of a list element to be changed. + private Button changeItemBtn = new Button(); + + // This DataGridView control displays the contents of the list. + private DataGridView customersDataGridView = new DataGridView(); + + // This BindingSource binds the list to the DataGridView control. + private BindingSource customersBindingSource = new BindingSource(); + + public Form1() + { + InitializeComponent(); + + // Set up the "Change Item" button. + this.changeItemBtn.Text = "Change Item"; + this.changeItemBtn.Dock = DockStyle.Bottom; + this.changeItemBtn.Click += + new EventHandler(changeItemBtn_Click); + this.Controls.Add(this.changeItemBtn); + + // Set up the DataGridView. + customersDataGridView.Dock = DockStyle.Top; + this.Controls.Add(customersDataGridView); + + this.Size = new Size(400, 200); + } + + private void Form1_Load(object sender, EventArgs e) + { + // Create and populate the list of DemoCustomer objects + // which will supply data to the DataGridView. + BindingList customerList = new BindingList(); + customerList.Add(DemoCustomer.CreateNewCustomer()); + customerList.Add(DemoCustomer.CreateNewCustomer()); + customerList.Add(DemoCustomer.CreateNewCustomer()); + + // Bind the list to the BindingSource. + this.customersBindingSource.DataSource = customerList; + + // Attach the BindingSource to the DataGridView. + this.customersDataGridView.DataSource = + this.customersBindingSource; + } + + // Change the value of the CompanyName property for the first + // item in the list when the "Change Item" button is clicked. + void changeItemBtn_Click(object sender, EventArgs e) + { + // Get a reference to the list from the BindingSource. + BindingList customerList = + this.customersBindingSource.DataSource as BindingList; + + // Change the value of the CompanyName property for the + // first item in the list. + customerList[0].CustomerName = "Tailspin Toys"; + customerList[0].PhoneNumber = "(708)555-0150"; + } + } + + // + // This is a simple customer class that + // implements the IPropertyChange interface. + public class DemoCustomer : INotifyPropertyChanged + { + // These fields hold the values for the public properties. + private Guid idValue = Guid.NewGuid(); + private string customerNameValue = String.Empty; + private string phoneNumberValue = String.Empty; + + public event PropertyChangedEventHandler PropertyChanged; + + // This method is called by the Set accessor of each property. + // The CallerMemberName attribute that is applied to the optional propertyName + // parameter causes the property name of the caller to be substituted as an argument. + private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") + { + if (PropertyChanged != null) + { + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + // The constructor is private to enforce the factory pattern. + private DemoCustomer() + { + customerNameValue = "Customer"; + phoneNumberValue = "(312)555-0100"; + } + + // This is the public factory method. + public static DemoCustomer CreateNewCustomer() + { + return new DemoCustomer(); + } + + // This property represents an ID, suitable + // for use as a primary key in a database. + public Guid ID + { + get + { + return this.idValue; + } + } + + public string CustomerName + { + get + { + return this.customerNameValue; + } + + set + { + if (value != this.customerNameValue) + { + this.customerNameValue = value; + NotifyPropertyChanged(); + } + } + } + + public string PhoneNumber + { + get + { + return this.phoneNumberValue; + } + + set + { + if (value != this.phoneNumberValue) + { + this.phoneNumberValue = value; + NotifyPropertyChanged(); + } + } + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Customer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Customer.cs new file mode 100644 index 0000000000..5c15e8ef1f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Customer.cs @@ -0,0 +1,148 @@ +// +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; + +namespace ITypedListCS +{ + class Customer : INotifyPropertyChanged + { + public Customer() {} + + public Customer(int id, string name, string company, string address, string city, string state, string zip) + { + this._id = id; + this._name = name; + this._company = company; + this._address = address; + this._city = city; + this._state = state; + this._zip = zip; + } + + #region Public Properties + + private int _id; + + public int ID + { + get { return _id; } + set + { + if (_id != value) + { + _id = value; + OnPropertyChanged(new PropertyChangedEventArgs("ID")); + } + } + } + + private string _name; + + public string Name + { + get { return _name; } + set + { + if (_name != value) + { + _name = value; + OnPropertyChanged(new PropertyChangedEventArgs("Name")); + } + } + } + + private string _company; + + public string Company + { + get { return _company; } + set + { + if (_company != value) + { + _company = value; + OnPropertyChanged(new PropertyChangedEventArgs("Company")); + } + } + } + + private string _address; + + public string Address + { + get { return _address; } + set + { + if (_address != value) + { + _address = value; + OnPropertyChanged(new PropertyChangedEventArgs("Address")); + } + } + } + + private string _city; + + public string City + { + get { return _city; } + set + { + if (_city != value) + { + _city = value; + OnPropertyChanged(new PropertyChangedEventArgs("City")); + } + } + } + + private string _state; + + public string State + { + get { return _state; } + set + { + if (_state != value) + { + _state = value; + OnPropertyChanged(new PropertyChangedEventArgs("State")); + } + } + } + + private string _zip; + + public string ZipCode + { + get { return _zip; } + set + { + if (_zip != value) + { + _zip = value; + OnPropertyChanged(new PropertyChangedEventArgs("ZipCode")); + } + } + } + + #endregion + + #region INotifyPropertyChanged Members + + public event PropertyChangedEventHandler PropertyChanged; + + protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) + { + if (null != PropertyChanged) + { + PropertyChanged(this, e); + } + } + + #endregion + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Form1.cs new file mode 100644 index 0000000000..d44aa80b4f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/Form1.cs @@ -0,0 +1,166 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace ITypedListCS +{ + public partial class Form1 : Form + { + private SortableBindingList sortableBindingListOfCustomers; + private BindingList bindingListOfCustomers; + + private System.ComponentModel.IContainer components = null; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; + private System.Windows.Forms.Label label2; + private DataGridView dataGridView1; + private Button button1; + private Button button2; + + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + this.sortableBindingListOfCustomers = new SortableBindingList(); + this.bindingListOfCustomers = new BindingList(); + + this.dataGridView1.DataSource = this.bindingListOfCustomers; + } + + private void button1_Click(object sender, EventArgs e) + { + this.dataGridView1.DataSource = null; + this.dataGridView1.DataSource = this.sortableBindingListOfCustomers; + } + + private void button2_Click(object sender, EventArgs e) + { + this.dataGridView1.DataSource = null; + this.dataGridView1.DataSource = this.bindingListOfCustomers; + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); + this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.label2 = new System.Windows.Forms.Label(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.flowLayoutPanel1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.SuspendLayout(); + // + // flowLayoutPanel1 + // + this.flowLayoutPanel1.AutoSize = true; + this.flowLayoutPanel1.Controls.Add(this.label2); + this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; + this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); + this.flowLayoutPanel1.Name = "flowLayoutPanel1"; + this.flowLayoutPanel1.Size = new System.Drawing.Size(566, 51); + this.flowLayoutPanel1.TabIndex = 13; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(3, 6); + this.label2.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(558, 39); + this.label2.TabIndex = 0; + this.label2.Text = "This sample demonstrates how to implement the ITypedList interface. Clicking on the 'Sort Columns' button will bind the DataGridView to a sub-classed BindingList that implements ITypedList to provide a sorted list of columns. Clicking on the 'Reset' button will bind the DataGridView to a normal BindingList."; + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Location = new System.Drawing.Point(6, 57); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.ReadOnly = true; + this.dataGridView1.RowHeadersVisible = false; + this.dataGridView1.Size = new System.Drawing.Size(465, 51); + this.dataGridView1.TabIndex = 14; + // + // button1 + // + this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.button1.Location = new System.Drawing.Point(477, 57); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(82, 23); + this.button1.TabIndex = 15; + this.button1.Text = "Sort Columns"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // button2 + // + this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.button2.Location = new System.Drawing.Point(477, 86); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(82, 23); + this.button2.TabIndex = 16; + this.button2.Text = "Reset"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(566, 120); + this.Controls.Add(this.button2); + this.Controls.Add(this.button1); + this.Controls.Add(this.dataGridView1); + this.Controls.Add(this.flowLayoutPanel1); + this.Name = "Form1"; + this.Text = "ITypedList Sample"; + this.Load += new System.EventHandler(this.Form1_Load); + this.flowLayoutPanel1.ResumeLayout(false); + this.flowLayoutPanel1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/SortableBindingList.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/SortableBindingList.cs new file mode 100644 index 0000000000..22ff90da03 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/SortableBindingList.cs @@ -0,0 +1,66 @@ +// +using System; +using System.Collections.Generic; +using System.Text; +using System.ComponentModel; +using System.Windows.Forms; +using System.Collections; +using System.Reflection; + +namespace ITypedListCS +{ + [Serializable()] + public class SortableBindingList : BindingList, ITypedList + { + [NonSerialized()] + private PropertyDescriptorCollection properties; + + public SortableBindingList() : base() + { + // Get the 'shape' of the list. + // Only get the public properties marked with Browsable = true. + PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties( + typeof(T), + new Attribute[] { new BrowsableAttribute(true) }); + + // Sort the properties. + properties = pdc.Sort(); + } + + // + #region ITypedList Implementation + + // + public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) + { + PropertyDescriptorCollection pdc; + + if (listAccessors!=null && listAccessors.Length>0) + { + // Return child list shape. + pdc = ListBindingHelper.GetListItemProperties(listAccessors[0].PropertyType); + } + else + { + // Return properties in sort order. + pdc = properties; + } + + return pdc; + } + // + + // + // This method is only used in the design-time framework + // and by the obsolete DataGrid control. + public string GetListName(PropertyDescriptor[] listAccessors) + { + return typeof(T).Name; + } + // + + #endregion + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/makefile new file mode 100644 index 0000000000..da380f1064 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.ComponentModel.ITypedList/CS/makefile @@ -0,0 +1,5 @@ +ITypedList.exe: SortableBindingList.cs Customer.cs Form1.cs + csc /t:exe /out:ITypedList.exe SortableBindingList.cs Customer.cs Form1.cs + +clean: + del *.dll *.bin *.exe \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs new file mode 100644 index 0000000000..a480b21f06 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/CS/Form1.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace AlignText +{ + public class Form1 : Form + { + public Form1() + { + this.Paint +=new PaintEventHandler(Form1_Paint); + } + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void AlignTextWithTextRenderer(PaintEventArgs e) + { + // + string text2 = "Use TextFormatFlags and Rectangle objects to" + + " center text in a rectangle."; + + using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) + { + Rectangle rect2 = new Rectangle(150, 10, 130, 140); + + // Create a TextFormatFlags with word wrapping, horizontal center and + // vertical center specified. + TextFormatFlags flags = TextFormatFlags.HorizontalCenter | + TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak; + + // Draw the text and the surrounding rectangle. + TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags); + e.Graphics.DrawRectangle(Pens.Black, rect2); + } + // + } + + private void AlignTextWithDrawString(PaintEventArgs e) + { + // + string text1 = "Use StringFormat and Rectangle objects to" + + " center text in a rectangle."; + using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) + { + Rectangle rect1 = new Rectangle(10, 10, 130, 140); + + // Create a StringFormat object with the each line of text, and the block + // of text centered on the page. + StringFormat stringFormat = new StringFormat(); + stringFormat.Alignment = StringAlignment.Center; + stringFormat.LineAlignment = StringAlignment.Center; + + // Draw the text and the surrounding rectangle. + e.Graphics.DrawString(text1, font1, Brushes.Blue, rect1, stringFormat); + e.Graphics.DrawRectangle(Pens.Black, rect1); + } + // + } + private void DrawTextAtLocation1(PaintEventArgs e) + { + // + using (Font font1 = new Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel)){ + PointF pointF1 = new PointF(30, 10); + e.Graphics.DrawString("Hello", font1, Brushes.Blue, pointF1); + } + // + } + + private void DrawTextAtLocation2(PaintEventArgs e) + { + // + using (Font font = new Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel)) + { + Point point1 = new Point(30, 10); + TextRenderer.DrawText(e.Graphics, "Hello", font, point1, Color.Blue); + } + // + } + + private void DrawTextInARectangle1(PaintEventArgs e) + { + // + string text1 = "Draw text in a rectangle by passing a RectF to the DrawString method."; + using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) + { + RectangleF rectF1 = new RectangleF(30, 10, 100, 122); + e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1); + e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1)); + } + // + } + + private void DrawTextInARectangle2(PaintEventArgs e) + { + // + string text2 = "Draw text in a rectangle by passing a RectF to the DrawString method."; + using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) + { + Rectangle rect2 = new Rectangle(30, 10, 100, 122); + + // Specify the text is wrapped. + TextFormatFlags flags = TextFormatFlags.WordBreak; + TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags); + e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2)); + } + // + } + + private void Form1_Paint(object sender, PaintEventArgs e) + { + //AlignTextWithDrawString(e); + //AlignTextWithTextRenderer(e); + //DrawTextAtLocation1(e); + //DrawTextAtLocation2(e); + DrawTextInARectangle1(e); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs new file mode 100644 index 0000000000..378eedb8e6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.AlphaBlending/CS/Class1.cs @@ -0,0 +1,164 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; + +public class SystemDrawingAlphaBlending +{ + + // 8f2508af-f495-4223-b5cc-646cbbb520eb + // How to: Draw Opaque and Semitransparent Lines + + public void Method11(PaintEventArgs e) + { + // + Bitmap bitmap = new Bitmap("Texture1.jpg"); + e.Graphics.DrawImage(bitmap, 10, 5, bitmap.Width, bitmap.Height); + + Pen opaquePen = new Pen(Color.FromArgb(255, 0, 0, 255), 15); + Pen semiTransPen = new Pen(Color.FromArgb(128, 0, 0, 255), 15); + + e.Graphics.DrawLine(opaquePen, 0, 20, 100, 20); + e.Graphics.DrawLine(semiTransPen, 0, 40, 100, 40); + + e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected; + e.Graphics.DrawLine(semiTransPen, 0, 60, 100, 60); + // + } + // a27121e6-f7e9-4c09-84e2-f05aa9d2a1bb + // How to: Use a Color Matrix to Set Alpha Values in Images + + public void Method21(PaintEventArgs e) + { + // + // Create the Bitmap object and load it with the texture image. + Bitmap bitmap = new Bitmap("Texture.jpg"); + + // Initialize the color matrix. + // Note the value 0.8 in row 4, column 4. + float[][] matrixItems ={ + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0, 0, 1, 0, 0}, + new float[] {0, 0, 0, 0.8f, 0}, + new float[] {0, 0, 0, 0, 1}}; + ColorMatrix colorMatrix = new ColorMatrix(matrixItems); + + // Create an ImageAttributes object and set its color matrix. + ImageAttributes imageAtt = new ImageAttributes(); + imageAtt.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + // First draw a wide black line. + e.Graphics.DrawLine( + new Pen(Color.Black, 25), + new Point(10, 35), + new Point(200, 35)); + + // Now draw the semitransparent bitmap image. + int iWidth = bitmap.Width; + int iHeight = bitmap.Height; + e.Graphics.DrawImage( + bitmap, + new Rectangle(30, 0, iWidth, iHeight), // destination rectangle + 0.0f, // source rectangle x + 0.0f, // source rectangle y + iWidth, // source rectangle width + iHeight, // source rectangle height + GraphicsUnit.Pixel, + imageAtt); + // + } + // a4f6f6b8-3bc8-440a-84af-d62ef0f8ff40 + // How to: Draw with Opaque and Semitransparent Brushes + + public void Method31(PaintEventArgs e) + { + // + Bitmap bitmap = new Bitmap("Texture1.jpg"); + e.Graphics.DrawImage(bitmap, 50, 50, bitmap.Width, bitmap.Height); + + SolidBrush opaqueBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255)); + SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255)); + + e.Graphics.FillEllipse(opaqueBrush, 35, 45, 45, 30); + e.Graphics.FillEllipse(semiTransBrush, 86, 45, 45, 30); + + e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected; + e.Graphics.FillEllipse(semiTransBrush, 40, 90, 86, 30); + // + } + // f331df2d-b395-4b0a-95be-24fec8c9bbb5 + // How to: Use Compositing Mode to Control Alpha Blending + + public void Method41() + { + Bitmap myBitmap = new Bitmap(180, 100); + + // Create a Graphics object that we can use to draw on the bitmap. + Graphics bitmapGraphics = Graphics.FromImage(myBitmap); + + // + bitmapGraphics.CompositingMode = CompositingMode.SourceCopy; + // + } + public void Method42() + { + Bitmap myBitmap = new Bitmap(180, 100); + + // Create a Graphics object that we can use to draw on the bitmap. + Graphics bitmapGraphics = Graphics.FromImage(myBitmap); + + // + bitmapGraphics.CompositingMode = CompositingMode.SourceOver; + // + } + public void Method43(PaintEventArgs e) + { + // + // Create a blank bitmap. + Bitmap myBitmap = new Bitmap(180, 100); + + // Create a Graphics object that we can use to draw on the bitmap. + Graphics bitmapGraphics = Graphics.FromImage(myBitmap); + + // Create a red brush and a green brush, each with an alpha value of 160. + SolidBrush redBrush = new SolidBrush(Color.FromArgb(160, 255, 0, 0)); + SolidBrush greenBrush = new SolidBrush(Color.FromArgb(160, 0, 255, 0)); + + // Set the compositing mode so that when we draw overlapping ellipses, + // the colors of the ellipses are not blended. + bitmapGraphics.CompositingMode = CompositingMode.SourceCopy; + + // Fill an ellipse using a red brush that has an alpha value of 160. + bitmapGraphics.FillEllipse(redBrush, 0, 0, 150, 70); + + // Fill a second ellipse using a green brush that has an alpha value of 160. + // The green ellipse overlaps the red ellipse, but the green is not + // blended with the red. + bitmapGraphics.FillEllipse(greenBrush, 30, 30, 150, 70); + + // Set the compositing quality of the form's Graphics object. + e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected; + + // Draw a multicolored background. + SolidBrush colorBrush = new SolidBrush(Color.Aqua); + e.Graphics.FillRectangle(colorBrush, 200, 0, 60, 100); + colorBrush.Color = Color.Yellow; + e.Graphics.FillRectangle(colorBrush, 260, 0, 60, 100); + colorBrush.Color = Color.Fuchsia; + e.Graphics.FillRectangle(colorBrush, 320, 0, 60, 100); + + // Display the bitmap on a white background. + e.Graphics.DrawImage(myBitmap, 0, 0); + + // Display the bitmap on a multicolored background. + e.Graphics.DrawImage(myBitmap, 200, 0); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs new file mode 100644 index 0000000000..8961cacbb1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/CS/form1.cs @@ -0,0 +1,149 @@ +using System; +using System.Windows.Forms; +using System.Drawing; + +public class Form1: + System.Windows.Forms.Form + +{ + private void DoSomething1() + { + // Snippet for: \vbtskcodeexampledrawingfilledellipseonform.xml + // + System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); + System.Drawing.Graphics formGraphics; + formGraphics = this.CreateGraphics(); + formGraphics.FillEllipse(myBrush, new Rectangle(0, 0, 200, 300)); + myBrush.Dispose(); + formGraphics.Dispose(); + // + } + + private void DoSomething2() + { + // Snippet for: \vbtskcodeexampledrawingfilledrectangleonform.xml + // + System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); + System.Drawing.Graphics formGraphics; + formGraphics = this.CreateGraphics(); + formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300)); + myBrush.Dispose(); + formGraphics.Dispose(); + // + } + + private void DoSomething3() + { + // Snippet for: \vbtskcodeexamplecreatingpen.xml + // + System.Drawing.Pen myPen; + myPen = new System.Drawing.Pen(System.Drawing.Color.Tomato); + // + } + + private void DoSomething4() + { + // Snippet for: \vbtskcodeexamplecreatingsolidbrush.xml + // + System.Drawing.SolidBrush myBrush; + myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.PeachPuff); + // + } + + private void DoSomething5() + { + // Snippet for: \vbtskcodeexampledrawinglineonform.xml + // + System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red); + System.Drawing.Graphics formGraphics; + formGraphics = this.CreateGraphics(); + formGraphics.DrawLine(myPen, 0, 0, 200, 200); + myPen.Dispose(); + formGraphics.Dispose(); + // + } + + // Snippet for: \vbtskcodeexampledrawingoutlinedshapes.xml + // + private void DrawEllipse() + { + System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red); + System.Drawing.Graphics formGraphics; + formGraphics = this.CreateGraphics(); + formGraphics.DrawEllipse(myPen, new Rectangle(0, 0, 200, 300)); + myPen.Dispose(); + formGraphics.Dispose(); + } + + private void DrawRectangle() + { + System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red); + System.Drawing.Graphics formGraphics; + formGraphics = this.CreateGraphics(); + formGraphics.DrawRectangle(myPen, new Rectangle(0, 0, 200, 300)); + myPen.Dispose(); + formGraphics.Dispose(); + } + + // + // Snippet for: \vbtskcodeexampledrawingtextonform2.xml + // + public void DrawString() + { + System.Drawing.Graphics formGraphics = this.CreateGraphics(); + string drawString = "Sample Text"; + System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16); + System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); + float x = 150.0F; + float y = 50.0F; + System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(); + formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat); + drawFont.Dispose(); + drawBrush.Dispose(); + formGraphics.Dispose(); + } + + // + // Snippet for: \vbtskcodeexampledrawingtextonform.xml + // + public void DrawVerticalString() + { + System.Drawing.Graphics formGraphics = this.CreateGraphics(); + string drawString = "Sample Text"; + System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16); + System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); + float x = 150.0F; + float y = 50.0F; + System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(); + drawFormat.FormatFlags = StringFormatFlags.DirectionVertical; + formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat); + drawFont.Dispose(); + drawBrush.Dispose(); + formGraphics.Dispose(); + } + + // + private void DoSomething9() + { + Pen myPen = new Pen(Color.Red); + // Snippet for: \vbtskcodeexamplesetcolorofpen.xml + // + myPen.Color = System.Drawing.Color.PeachPuff; + // + } + // Snippet for: \vbtskcreateashapedwindowsform.xml + // + protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) + { + System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath(); + shape.AddEllipse(0, 0, this.Width, this.Height); + this.Region = new System.Drawing.Region(shape); + } + // + + [STAThread] + public static void Main() + { + Application.Run(new Form1()); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs new file mode 100644 index 0000000000..a0b0cffb61 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/CS/Class1.cs @@ -0,0 +1,97 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Drawing2D; + +public class SystemDrawingConstructingDrawingCurves +{ + + // 37a0bedb-20c2-4cf0-91fa-a5509e826b30 + // How to: Draw a Sequence of Bézier Splines + + private void Method11(PaintEventArgs e) + { + // + Point[] p = { + new Point(10, 100), // start point of first spline + new Point(75, 10), // first control point of first spline + new Point(80, 50), // second control point of first spline + + new Point(100, 150), // endpoint of first spline and + // start point of second spline + + new Point(125, 80), // first control point of second spline + new Point(175, 200), // second control point of second spline + new Point(200, 80)}; // endpoint of second spline + + Pen pen = new Pen(Color.Blue); + e.Graphics.DrawBeziers(pen, p); + + // + } + // a4a41e80-4461-4b47-b6bd-2c5e68881994 + // How to: Draw Cardinal Splines + + private void Method21(PaintEventArgs e) + { + // + Point[] points = { + new Point(0, 100), + new Point(50, 80), + new Point(100, 20), + new Point(150, 80), + new Point(200, 100)}; + + Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255)); + e.Graphics.DrawCurve(pen, points); + // + } + private void Method22(PaintEventArgs e) + { + // + Point[] points = { + new Point(60, 60), + new Point(150, 80), + new Point(200, 40), + new Point(180, 120), + new Point(120, 100), + new Point(80, 160)}; + + Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255)); + e.Graphics.DrawClosedCurve(pen, points); + // + } + private void Method23(PaintEventArgs e) + { + // + Point[] points = { + new Point(20, 50), + new Point(100, 10), + new Point(200, 100), + new Point(300, 50), + new Point(400, 80)}; + + Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255)); + e.Graphics.DrawCurve(pen, points, 0.0f); + e.Graphics.DrawCurve(pen, points, 0.6f); + e.Graphics.DrawCurve(pen, points, 1.0f); + // + } + // f4f3fe30-f0a6-4743-ac91-11310cebea9f + // How to: Draw a Single Bézier Spline + + private void Method31(PaintEventArgs e) + { + // + Point p1 = new Point(10, 100); // Start point + Point c1 = new Point(100, 10); // First control point + Point c2 = new Point(150, 150); // Second control point + Point p2 = new Point(200, 100); // Endpoint + + Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255)); + e.Graphics.DrawBezier(pen, p1, c1, c2, p2); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/CS/Class1.cs new file mode 100644 index 0000000000..f24ea09702 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/CS/Class1.cs @@ -0,0 +1,69 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Drawing2D; + +public class SystemDrawingConstructingDrawingPaths +{ + + // 5a36b0e4-f1f4-46c0-a85a-22ae98491950 + // How to: Fill Open Figures + + private void Method11(PaintEventArgs e) + { + // + GraphicsPath path = new GraphicsPath(); + + // Add an open figure. + path.AddArc(0, 0, 150, 120, 30, 120); + + // Add an intrinsically closed figure. + path.AddEllipse(50, 50, 50, 100); + + Pen pen = new Pen(Color.FromArgb(128, 0, 0, 255), 5); + SolidBrush brush = new SolidBrush(Color.Red); + + // The fill mode is FillMode.Alternate by default. + e.Graphics.FillPath(brush, path); + e.Graphics.DrawPath(pen, path); + // + } + // 82fd56c7-b443-4765-9b7c-62ce030656ec + // How to: Create Figures from Lines, Curves, and Shapes + + private void Method21(PaintEventArgs e) + { + // + GraphicsPath path = new GraphicsPath(); + path.AddArc(175, 50, 50, 50, 0, -180); + e.Graphics.DrawPath(new Pen(Color.FromArgb(128, 255, 0, 0), 4), path); + // + } + private void Method22(PaintEventArgs e) + { + // + // Create an array of points for the curve in the second figure. + Point[] points = { + new Point(40, 60), + new Point(50, 70), + new Point(30, 90)}; + + GraphicsPath path = new GraphicsPath(); + + path.StartFigure(); // Start the first figure. + path.AddArc(175, 50, 50, 50, 0, -180); + path.AddLine(100, 0, 250, 20); + // First figure is not closed. + + path.StartFigure(); // Start the second figure. + path.AddLine(50, 20, 5, 90); + path.AddCurve(points, 3); + path.AddLine(50, 150, 150, 180); + path.CloseFigure(); // Second figure is closed. + + e.Graphics.DrawPath(new Pen(Color.FromArgb(255, 255, 0, 0), 2), path); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs new file mode 100644 index 0000000000..73e41ac56a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/CS/Class1.cs @@ -0,0 +1,128 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +public class Form1 : Form +{ + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + Pen myPen = Pens.Red; + + // 0659fe00-9e0c-41c4-9118-016f2404c905 + // Matrix Representation of Transformations + + public void Method11() + { + Graphics myGraphics = this.CreateGraphics(); + // + Matrix myMatrix = new Matrix(); + myMatrix.Rotate(30); + myMatrix.Scale(1, 2, MatrixOrder.Append); + myMatrix.Translate(5, 0, MatrixOrder.Append); + // + } + // b601d66d-d572-4f11-9d2e-92f0dc8893f3 + // Global and Local Transformations + + public void Method21() + { + Graphics myGraphics = this.CreateGraphics(); + // + myGraphics.DrawEllipse(myPen, 0, 0, 100, 50); + myGraphics.ScaleTransform(1, 0.5f); + myGraphics.TranslateTransform(50, 0, MatrixOrder.Append); + myGraphics.RotateTransform(30, MatrixOrder.Append); + myGraphics.DrawEllipse(myPen, 0, 0, 100, 50); + // + } + public void Method22() + { + Graphics myGraphics = this.CreateGraphics(); + GraphicsPath myGraphicsPath = new GraphicsPath(); + // + Matrix myMatrix = new Matrix(); + myMatrix.Rotate(45); + myGraphicsPath.Transform(myMatrix); + myGraphics.DrawRectangle(myPen, 10, 10, 100, 50); + myGraphics.DrawPath(myPen, myGraphicsPath); + // + } + public void Method23() + { + Graphics myGraphics = this.CreateGraphics(); + // + Matrix myMatrix = new Matrix(1, 0, 0, -1, 0, 0); + myGraphics.Transform = myMatrix; + myGraphics.TranslateTransform(200, 150, MatrixOrder.Append); + // + } + public void Method24() + { + Graphics myGraphics = this.CreateGraphics(); + SolidBrush mySolidBrush1 = new SolidBrush(Color.Red); + SolidBrush mySolidBrush2 = new SolidBrush(Color.Black); + // + // Create the path. + GraphicsPath myGraphicsPath = new GraphicsPath(); + Rectangle myRectangle = new Rectangle(0, 0, 60, 60); + myGraphicsPath.AddRectangle(myRectangle); + + // Fill the path on the new coordinate system. + // No local transformation + myGraphics.FillPath(mySolidBrush1, myGraphicsPath); + + // Set the local transformation of the GraphicsPath object. + Matrix myPathMatrix = new Matrix(); + myPathMatrix.Scale(2, 1); + myPathMatrix.Rotate(30, MatrixOrder.Append); + myGraphicsPath.Transform(myPathMatrix); + + // Fill the transformed path on the new coordinate system. + myGraphics.FillPath(mySolidBrush2, myGraphicsPath); + // + } + // c61ff50a-eb1d-4e6c-83cd-f7e9764cfa9f + // Types of Coordinate Systems + + public void Method31() + { + Graphics myGraphics = this.CreateGraphics(); + // + myGraphics.TranslateTransform(100, 50); + myGraphics.DrawLine(myPen, 0, 0, 160, 80); + // + } + public void Method32() + { + Graphics myGraphics = this.CreateGraphics(); + // + myGraphics.PageUnit = GraphicsUnit.Inch; + myGraphics.DrawLine(myPen, 0, 0, 2, 1); + // + } + public void Method33() + { + Graphics myGraphics = this.CreateGraphics(); + // + Pen myPen = new Pen(Color.Black, 1 / myGraphics.DpiX); + // + } + public void Method34() + { + Graphics myGraphics = this.CreateGraphics(); + // + myGraphics.TranslateTransform(2, 0.5f); + myGraphics.PageUnit = GraphicsUnit.Inch; + myGraphics.DrawLine(myPen, 0, 0, 2, 1); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/CS/Form1.cs new file mode 100644 index 0000000000..1f2f2260e2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/CS/Form1.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace BitmapAtRuntime +{ + public class Form1 : Form + { + public Form1() + { + this.Paint += new PaintEventHandler(Form1_Paint); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + + void Form1_Paint(object sender, PaintEventArgs e) + { + CreateBitmapAtRuntime(); + } + + // + PictureBox pictureBox1 = new PictureBox(); + public void CreateBitmapAtRuntime() + { + pictureBox1.Size = new Size(210, 110); + this.Controls.Add(pictureBox1); + + Bitmap flag = new Bitmap(200, 100); + Graphics flagGraphics = Graphics.FromImage(flag); + int red = 0; + int white = 11; + while (white <= 100) { + flagGraphics.FillRectangle(Brushes.Red, 0, red, 200,10); + flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10); + red += 20; + white += 20; + } + pictureBox1.Image = flag; + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs new file mode 100644 index 0000000000..1e0bae9110 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.FontsAndText/CS/Class1.cs @@ -0,0 +1,381 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Text; + +public class SystemDrawingFontsAndText +{ + + // 26d74ef5-0f39-4eeb-8d20-00e66e014abe + // How to: Enumerate Installed Fonts + + public void Method11(PaintEventArgs e) + { + // + FontFamily fontFamily = new FontFamily("Arial"); + Font font = new Font( + fontFamily, + 8, + FontStyle.Regular, + GraphicsUnit.Point); + RectangleF rectF = new RectangleF(10, 10, 500, 500); + SolidBrush solidBrush = new SolidBrush(Color.Black); + + string familyName; + string familyList = ""; + FontFamily[] fontFamilies; + + InstalledFontCollection installedFontCollection = new InstalledFontCollection(); + + // Get the array of FontFamily objects. + fontFamilies = installedFontCollection.Families; + + // The loop below creates a large string that is a comma-separated + // list of all font family names. + + int count = fontFamilies.Length; + for (int j = 0; j < count; ++j) + { + familyName = fontFamilies[j].Name; + familyList = familyList + familyName; + familyList = familyList + ", "; + } + + // Draw the large string (list of all families) in a rectangle. + e.Graphics.DrawString(familyList, font, solidBrush, rectF); + // + } + // 48fc34f3-f236-4b01-a0cb-f0752e6d22ae + // How to: Use Antialiasing with Text + + public void Method21(PaintEventArgs e) + { + // + FontFamily fontFamily = new FontFamily("Times New Roman"); + Font font = new Font( + fontFamily, + 32, + FontStyle.Regular, + GraphicsUnit.Pixel); + SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255)); + string string1 = "SingleBitPerPixel"; + string string2 = "AntiAlias"; + + e.Graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; + e.Graphics.DrawString(string1, font, solidBrush, new PointF(10, 10)); + + e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias; + e.Graphics.DrawString(string2, font, solidBrush, new PointF(10, 60)); + // + } + // 50c69046-4188-47d9-b949-cc2610ffd337 + // How to: Create Vertical Text + + public void Method31(PaintEventArgs e) + { + // + string myText = "Vertical text"; + + FontFamily fontFamily = new FontFamily("Lucida Console"); + Font font = new Font( + fontFamily, + 14, + FontStyle.Regular, + GraphicsUnit.Point); + PointF pointF = new PointF(40, 10); + StringFormat stringFormat = new StringFormat(); + SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255)); + + stringFormat.FormatFlags = StringFormatFlags.DirectionVertical; + + e.Graphics.DrawString(myText, font, solidBrush, pointF, stringFormat); + + // + } + // 64878f98-39ba-4303-b63f-0859ab682eeb + // How to: Set Tab Stops in Drawn Text + + public void Method41(PaintEventArgs e) + { + // + string text = "Name\tTest 1\tTest 2\tTest 3\n"; + text = text + "Joe\t95\t88\t91\n"; + text = text + "Mary\t98\t84\t90\n"; + text = text + "Sam\t42\t76\t98\n"; + text = text + "Jane\t65\t73\t92\n"; + + FontFamily fontFamily = new FontFamily("Courier New"); + Font font = new Font( + fontFamily, + 12, + FontStyle.Regular, + GraphicsUnit.Point); + Rectangle rect = new Rectangle(10, 10, 450, 100); + StringFormat stringFormat = new StringFormat(); + SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255)); + float[] tabs = { 150, 100, 100, 100 }; + + stringFormat.SetTabStops(0, tabs); + + e.Graphics.DrawString(text, font, solidBrush, rect, stringFormat); + + Pen pen = Pens.Black; + e.Graphics.DrawRectangle(pen, rect); + // + } + // 6533d5e5-a8dc-4b76-9fc4-3bf75c8b9212 + // How to: Create a Private Font Collection + + public void Method51(PaintEventArgs e) + { + // + PointF pointF = new PointF(10, 0); + SolidBrush solidBrush = new SolidBrush(Color.Black); + + int count = 0; + string familyName = ""; + string familyNameAndStyle; + FontFamily[] fontFamilies; + PrivateFontCollection privateFontCollection = new PrivateFontCollection(); + + // Add three font files to the private collection. + privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\Arial.ttf"); + privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\CourBI.ttf"); + privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\TimesBD.ttf"); + + // Get the array of FontFamily objects. + fontFamilies = privateFontCollection.Families; + + // How many objects in the fontFamilies array? + count = fontFamilies.Length; + + // Display the name of each font family in the private collection + // along with the available styles for that font family. + for (int j = 0; j < count; ++j) + { + // Get the font family name. + familyName = fontFamilies[j].Name; + + // Is the regular style available? + if (fontFamilies[j].IsStyleAvailable(FontStyle.Regular)) + { + familyNameAndStyle = ""; + familyNameAndStyle = familyNameAndStyle + familyName; + familyNameAndStyle = familyNameAndStyle + " Regular"; + + Font regFont = new Font( + familyName, + 16, + FontStyle.Regular, + GraphicsUnit.Pixel); + + e.Graphics.DrawString( + familyNameAndStyle, + regFont, + solidBrush, + pointF); + + pointF.Y += regFont.Height; + } + + // Is the bold style available? + if (fontFamilies[j].IsStyleAvailable(FontStyle.Bold)) + { + familyNameAndStyle = ""; + familyNameAndStyle = familyNameAndStyle + familyName; + familyNameAndStyle = familyNameAndStyle + " Bold"; + + Font boldFont = new Font( + familyName, + 16, + FontStyle.Bold, + GraphicsUnit.Pixel); + + e.Graphics.DrawString(familyNameAndStyle, boldFont, solidBrush, pointF); + + pointF.Y += boldFont.Height; + } + // Is the italic style available? + if (fontFamilies[j].IsStyleAvailable(FontStyle.Italic)) + { + familyNameAndStyle = ""; + familyNameAndStyle = familyNameAndStyle + familyName; + familyNameAndStyle = familyNameAndStyle + " Italic"; + + Font italicFont = new Font( + familyName, + 16, + FontStyle.Italic, + GraphicsUnit.Pixel); + + e.Graphics.DrawString( + familyNameAndStyle, + italicFont, + solidBrush, + pointF); + + pointF.Y += italicFont.Height; + } + + // Is the bold italic style available? + if (fontFamilies[j].IsStyleAvailable(FontStyle.Italic) && + fontFamilies[j].IsStyleAvailable(FontStyle.Bold)) + { + familyNameAndStyle = ""; + familyNameAndStyle = familyNameAndStyle + familyName; + familyNameAndStyle = familyNameAndStyle + "BoldItalic"; + + Font italicFont = new Font( + familyName, + 16, + FontStyle.Italic | FontStyle.Bold, + GraphicsUnit.Pixel); + + e.Graphics.DrawString( + familyNameAndStyle, + italicFont, + solidBrush, + pointF); + + pointF.Y += italicFont.Height; + } + // Is the underline style available? + if (fontFamilies[j].IsStyleAvailable(FontStyle.Underline)) + { + familyNameAndStyle = ""; + familyNameAndStyle = familyNameAndStyle + familyName; + familyNameAndStyle = familyNameAndStyle + " Underline"; + + Font underlineFont = new Font( + familyName, + 16, + FontStyle.Underline, + GraphicsUnit.Pixel); + + e.Graphics.DrawString( + familyNameAndStyle, + underlineFont, + solidBrush, + pointF); + + pointF.Y += underlineFont.Height; + } + + // Is the strikeout style available? + if (fontFamilies[j].IsStyleAvailable(FontStyle.Strikeout)) + { + familyNameAndStyle = ""; + familyNameAndStyle = familyNameAndStyle + familyName; + familyNameAndStyle = familyNameAndStyle + " Strikeout"; + + Font strikeFont = new Font( + familyName, + 16, + FontStyle.Strikeout, + GraphicsUnit.Pixel); + + e.Graphics.DrawString( + familyNameAndStyle, + strikeFont, + solidBrush, + pointF); + + pointF.Y += strikeFont.Height; + } + + // Separate the families with white space. + pointF.Y += 10; + } // for + // + } + // d3a4a223-9492-4b54-9afd-db1c31c3cefd + // How to: Construct Font Families and Fonts + + public void Method61(PaintEventArgs e) + { + // + FontFamily fontFamily = new FontFamily("Arial"); + Font font = new Font( + fontFamily, + 16, + FontStyle.Regular, + GraphicsUnit.Pixel); + // + } + // ff7c0616-67f7-4fa2-84ee-b8d642f2b09b + // How to: Obtain Font Metrics + + public void Method71(PaintEventArgs e) + { + // + string infoString = ""; // enough space for one line of output + int ascent; // font family ascent in design units + float ascentPixel; // ascent converted to pixels + int descent; // font family descent in design units + float descentPixel; // descent converted to pixels + int lineSpacing; // font family line spacing in design units + float lineSpacingPixel; // line spacing converted to pixels + + FontFamily fontFamily = new FontFamily("Arial"); + Font font = new Font( + fontFamily, + 16, FontStyle.Regular, + GraphicsUnit.Pixel); + PointF pointF = new PointF(10, 10); + SolidBrush solidBrush = new SolidBrush(Color.Black); + + // Display the font size in pixels. + infoString = "font.Size returns " + font.Size + "."; + e.Graphics.DrawString(infoString, font, solidBrush, pointF); + + // Move down one line. + pointF.Y += font.Height; + + // Display the font family em height in design units. + infoString = "fontFamily.GetEmHeight() returns " + + fontFamily.GetEmHeight(FontStyle.Regular) + "."; + e.Graphics.DrawString(infoString, font, solidBrush, pointF); + + // Move down two lines. + pointF.Y += 2 * font.Height; + + // Display the ascent in design units and pixels. + ascent = fontFamily.GetCellAscent(FontStyle.Regular); + + // 14.484375 = 16.0 * 1854 / 2048 + ascentPixel = + font.Size * ascent / fontFamily.GetEmHeight(FontStyle.Regular); + infoString = "The ascent is " + ascent + " design units, " + ascentPixel + + " pixels."; + e.Graphics.DrawString(infoString, font, solidBrush, pointF); + + // Move down one line. + pointF.Y += font.Height; + + // Display the descent in design units and pixels. + descent = fontFamily.GetCellDescent(FontStyle.Regular); + + // 3.390625 = 16.0 * 434 / 2048 + descentPixel = + font.Size * descent / fontFamily.GetEmHeight(FontStyle.Regular); + infoString = "The descent is " + descent + " design units, " + + descentPixel + " pixels."; + e.Graphics.DrawString(infoString, font, solidBrush, pointF); + + // Move down one line. + pointF.Y += font.Height; + + // Display the line spacing in design units and pixels. + lineSpacing = fontFamily.GetLineSpacing(FontStyle.Regular); + + // 18.398438 = 16.0 * 2355 / 2048 + lineSpacingPixel = + font.Size * lineSpacing / fontFamily.GetEmHeight(FontStyle.Regular); + infoString = "The line spacing is " + lineSpacing + " design units, " + + lineSpacingPixel + " pixels."; + e.Graphics.DrawString(infoString, font, solidBrush, pointF); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/CS/Form1.cs new file mode 100644 index 0000000000..20a1589d31 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/CS/Form1.cs @@ -0,0 +1,50 @@ +// + +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Printing; + +public class Form1 : + Form +{ + private Button printButton = new Button(); + private PrintDocument printDocument1 = new PrintDocument(); + + public Form1() + { + printButton.Text = "Print Form"; + printButton.Click += new EventHandler(printButton_Click); + printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage); + this.Controls.Add(printButton); + } + + void printButton_Click(object sender, EventArgs e) + { + CaptureScreen(); + printDocument1.Print(); + } + + Bitmap memoryImage; + + private void CaptureScreen() + { + Graphics myGraphics = this.CreateGraphics(); + Size s = this.Size; + memoryImage = new Bitmap(s.Width, s.Height, myGraphics); + Graphics memoryGraphics = Graphics.FromImage(memoryImage); + memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s); + } + + private void printDocument1_PrintPage(System.Object sender, + System.Drawing.Printing.PrintPageEventArgs e) + { + e.Graphics.DrawImage(memoryImage, 0, 0); + } + + public static void Main() + { + Application.Run(new Form1()); + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/CS/Form1.cs new file mode 100644 index 0000000000..8f05270e51 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/CS/Form1.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.IO; + +namespace ExtractAssociatedIcon +{ + public class Form1 : Form + { + public Form1() + { + ExtractAssociatedIconEx(); + } + + // + ListView listView1; + ImageList imageList1; + + public void ExtractAssociatedIconEx() + { + // Initialize the ListView, ImageList and Form. + listView1 = new ListView(); + imageList1 = new ImageList(); + listView1.Location = new Point(37, 12); + listView1.Size = new Size(151, 262); + listView1.SmallImageList = imageList1; + listView1.View = View.SmallIcon; + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.listView1); + this.Text = "Form1"; + + // Get the c:\ directory. + System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"c:\"); + + ListViewItem item; + listView1.BeginUpdate(); + + // For each file in the c:\ directory, create a ListViewItem + // and set the icon to the icon extracted from the file. + foreach (System.IO.FileInfo file in dir.GetFiles()) + { + // Set a default icon for the file. + Icon iconForFile = SystemIcons.WinLogo; + + item = new ListViewItem(file.Name, 1); + + // Check to see if the image collection contains an image + // for this extension, using the extension as a key. + if (!imageList1.Images.ContainsKey(file.Extension)) + { + // If not, add the image to the image list. + iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName); + imageList1.Images.Add(file.Extension, iconForFile); + } + item.ImageKey = file.Extension; + listView1.Items.Add(item); + } + listView1.EndUpdate(); + } + // + + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs new file mode 100644 index 0000000000..987341f224 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/CS/Class1.cs @@ -0,0 +1,118 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Imaging; + +public class Form1 : Form +{ + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + // 09f0c07a-19c0-43b4-90a2-862a10545ce8 + // Drawing, Positioning, and Cloning Images in GDI+ + + public void Method11() + { + Graphics myGraphics = this.CreateGraphics(); + // + Bitmap myBitmap = new Bitmap("Climber.jpg"); + myGraphics.DrawImage(myBitmap, 10, 10); + // + } + public void Method12() + { + Graphics myGraphics = this.CreateGraphics(); + // + Bitmap myBMP = new Bitmap("SpaceCadet.bmp"); + Bitmap myGIF = new Bitmap("Soda.gif"); + Bitmap myJPEG = new Bitmap("Mango.jpg"); + Bitmap myPNG = new Bitmap("Flowers.png"); + Bitmap myTIFF = new Bitmap("MS.tif"); + + myGraphics.DrawImage(myBMP, 10, 10); + myGraphics.DrawImage(myGIF, 220, 10); + myGraphics.DrawImage(myJPEG, 280, 10); + myGraphics.DrawImage(myPNG, 150, 200); + myGraphics.DrawImage(myTIFF, 300, 200); + // + } + public void Method13() + { + Graphics myGraphics = this.CreateGraphics(); + // + Bitmap originalBitmap = new Bitmap("Spiral.png"); + Rectangle sourceRectangle = new Rectangle(0, 0, originalBitmap.Width, + originalBitmap.Height / 2); + + Bitmap secondBitmap = originalBitmap.Clone(sourceRectangle, + PixelFormat.DontCare); + + myGraphics.DrawImage(originalBitmap, 10, 10); + myGraphics.DrawImage(secondBitmap, 150, 10); + // + } + // 51da872c-c783-440f-8bf6-1e580a966c31 + // Metafiles in GDI+ + + // + public void Example_DisplayMetafile(PaintEventArgs e) + { + Graphics myGraphics = e.Graphics; + Metafile myMetafile = new Metafile("SampleMetafile.emf"); + myGraphics.DrawImage(myMetafile, 100, 100); + } + // + // ad5daf26-005f-45bc-a2af-e0e97777a21a + // Cropping and Scaling Images in GDI+ + + public void Method31() + { + Graphics myGraphics = this.CreateGraphics(); + // + Bitmap myBitmap = new Bitmap("Spiral.png"); + + Rectangle expansionRectangle = new Rectangle(135, 10, + myBitmap.Width, myBitmap.Height); + + Rectangle compressionRectangle = new Rectangle(300, 10, + myBitmap.Width / 2, myBitmap.Height / 2); + + myGraphics.DrawImage(myBitmap, 10, 10); + myGraphics.DrawImage(myBitmap, expansionRectangle); + myGraphics.DrawImage(myBitmap, compressionRectangle); + // + } + public void Method32() + { + Graphics myGraphics = this.CreateGraphics(); + // + Bitmap myBitmap = new Bitmap("Runner.jpg"); + + // One hand of the runner + Rectangle sourceRectangle = new Rectangle(80, 70, 80, 45); + + // Compressed hand + Rectangle destRectangle1 = new Rectangle(200, 10, 20, 16); + + // Expanded hand + Rectangle destRectangle2 = new Rectangle(200, 40, 200, 160); + + // Draw the original image at (0, 0). + myGraphics.DrawImage(myBitmap, 0, 0); + + // Draw the compressed hand. + myGraphics.DrawImage( + myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel); + + // Draw the expanded hand. + myGraphics.DrawImage( + myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Misc3/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Misc3/CS/Form1.cs new file mode 100644 index 0000000000..26f421632a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Misc3/CS/Form1.cs @@ -0,0 +1,306 @@ +using System.Windows.Forms; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.ComponentModel; +using System.Drawing.Text; +using System; + +public class Form1 : + System.Windows.Forms.Form +{ + #region " Windows Form Designer generated code " + + public Form1() : base() + { + + //This call is required by the Windows Form Designer. + InitializeComponent(); + ExtractAssociatedIconEx(); + } + + //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. + + [System.Diagnostics.DebuggerStepThrough] + private void InitializeComponent() + { + +// Form1 +// + this.ClientSize = new System.Drawing.Size(292, 266); + + this.Name = "Form1"; + this.Text = "Form1"; + this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); + this.ResumeLayout(false); + } + + #endregion + + [System.STAThread] + public static void Main() + { + Application.Run(new Form1()); + } + + // + + protected void DrawCaps(PaintEventArgs e) + { + GraphicsPath hPath = new GraphicsPath(); + + // Create the outline for our custom end cap. + hPath.AddLine(new Point(0, 0), new Point(0, 5)); + hPath.AddLine(new Point(0, 5), new Point(5, 1)); + hPath.AddLine(new Point(5, 1), new Point(3, 1)); + + // Construct the hook-shaped end cap. + CustomLineCap HookCap = new CustomLineCap(null, hPath); + + // Set the start cap and end cap of the HookCap to be rounded. + HookCap.SetStrokeCaps(LineCap.Round, LineCap.Round); + + // Create a pen and set end custom start and end + // caps to the hook cap. + Pen customCapPen = new Pen(Color.Black, 5); + customCapPen.CustomStartCap = HookCap; + customCapPen.CustomEndCap = HookCap; + + // Create a second pen using the start and end caps from + // the hook cap. + Pen capPen = new Pen(Color.Red, 10); + LineCap startCap; + LineCap endCap; + HookCap.GetStrokeCaps(out startCap, out endCap); + capPen.StartCap = startCap; + capPen.EndCap = endCap; + + // Create a line to draw. + Point[] points = { new Point(100, 100), new Point(200, 50), + new Point(250, 300) }; + + // Draw the lines. + e.Graphics.DrawLines(capPen, points); + e.Graphics.DrawLines(customCapPen, points); + } + // + + // + private void ExtractAssociatedIconEx() + { + Icon ico = + Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe"); + this.Icon = ico; + } + // + + // + private void ConstructAnIconFromAType(PaintEventArgs e) + { + + Icon icon1 = new Icon(typeof(Control), "Error.ico"); + e.Graphics.DrawIcon(icon1, new Rectangle(10, 10, 50, 50)); + } + // + // + private void ShowOutputChannels(PaintEventArgs e) + { + //Create a bitmap from a file. + Bitmap bmp1 = new Bitmap("c:\\fakePhoto.jpg"); + + // Create a new bitmap from the original, resizing it for this example. + Bitmap bmp2 = new Bitmap(bmp1, new Size(80, 80)); + + bmp1.Dispose(); + + // Create an ImageAttributes object. + ImageAttributes imgAttributes = new ImageAttributes(); + + // Draw the image unaltered. + e.Graphics.DrawImage(bmp2, 10, 10); + + // Draw the image, showing the intensity of the cyan channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelC, + System.Drawing.Imaging.ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(bmp2, new Rectangle(100, 10, bmp2.Width, bmp2.Height), + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes); + + // Draw the image, showing the intensity of the magenta channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelM, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(bmp2, new Rectangle(10, 100, bmp2.Width, bmp2.Height), + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes); + + // Draw the image, showing the intensity of the yellow channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelY, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(bmp2, new Rectangle(100, 100, bmp2.Width, bmp2.Height), 0, 0, + bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes); + + // Draw the image, showing the intensity of the black channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelK, + + System.Drawing.Imaging.ColorAdjustType.Bitmap); + e.Graphics.DrawImage(bmp2, new Rectangle(10, 190, bmp2.Width, bmp2.Height), + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes); + + //Dispose of the bitmap. + bmp2.Dispose(); + } + // +// + private void OpAdditionExample(PaintEventArgs e) + { + PointF point1 = new PointF(120.5F, 120F); + SizeF size1 = new SizeF(120.5F, 30.5F); + RectangleF rect1 = new RectangleF(point1, size1); + if (new PointF(rect1.Right, rect1.Bottom) == point1 + size1) + e.Graphics.DrawString("They are equal", this.Font, Brushes.Black, rect1); + else + e.Graphics.DrawString("They are not equal", this.Font, Brushes.Red, rect1); + } + // + + // + private void AddExample(PaintEventArgs e) + { + PointF point1 = new PointF(120.5F, 120F); + SizeF size1 = new SizeF(20.5F, 20.5F); + RectangleF rect1 = new RectangleF(point1, size1); + PointF point2 = new PointF(rect1.Right, rect1.Bottom); + if (point2 != PointF.Add(point1, size1)) + e.Graphics.DrawString("They are not equal", this.Font, Brushes.Red, rect1); + else + e.Graphics.DrawString("They are equal", this.Font, Brushes.Black, rect1); + } + // + + // + private void SubtractExample(PaintEventArgs e) + { + PointF point1 = new PointF(120.5F, 120F); + SizeF size1 = new SizeF(120.5F, 30.5F); + PointF point2 = PointF.Subtract(point1, size1); + e.Graphics.DrawLine(Pens.Blue, point1, point2); + } + // + + // + private void OpSubtractionExample(PaintEventArgs e) + { + PointF point1 = new PointF(120.5F, 120F); + SizeF size1 = new SizeF(20.5F, 20.5F); + PointF point2 = point1 - size1; + e.Graphics.DrawLine(Pens.Blue, point1, point2); + } + // + + private void ShearColors(PaintEventArgs e) + { + // + Image image = new Bitmap("ColorBars.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + + float[][] colorMatrixElements = { + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0.5f, 0, 1, 0, 0}, + new float[] {0, 0, 0, 1, 0}, + new float[] {0, 0, 0, 0, 1}}; + + ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); + + imageAttributes.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10, width, height); + + e.Graphics.DrawImage( + image, + new Rectangle(150, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + // + } + // + InstalledFontCollection ifc = new InstalledFontCollection(); + private void EnumerateInstalledFonts(PaintEventArgs e) + { + FontFamily[] families = ifc.Families; + float x = 0.0F; + float y = 0.0F; + for (int i = 0; i < ifc.Families.Length; i++) + { + if (ifc.Families[i].IsStyleAvailable(FontStyle.Regular)) + { + e.Graphics.DrawString(ifc.Families[i].Name, new Font(ifc.Families[i], 12), + Brushes.Black, x, y); + y += 20; + if (y % 700 == 0) + { + x += 140; + y = 0; + } + } + } + } + // + + // + private void ConstructFontWithString(PaintEventArgs e) + { + Font font1 = new Font("Arial", 20); + e.Graphics.DrawString("Arial Font", font1, Brushes.Red, new PointF(10, 10)); + } + // + public static Bitmap ResizeImage(System.Drawing.Image image) + { + // + Bitmap bitmap = new Bitmap(100, 100); + bitmap.SetResolution(96.0F, 96.0F); + // + + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + graphics.DrawImage(image, + new Rectangle(0, 0, 100, 100), + new Rectangle(0, 0, image.Width, image.Height), + GraphicsUnit.Pixel); + } + + return bitmap; + } + // + public bool ThumbnailCallback() + { + return false; + } + public void Example_GetThumb(PaintEventArgs e) + { + Image.GetThumbnailImageAbort myCallback = + new Image.GetThumbnailImageAbort(ThumbnailCallback); + Bitmap myBitmap = new Bitmap("Climber.jpg"); + Image myThumbnail = myBitmap.GetThumbnailImage( + 40, 40, myCallback, IntPtr.Zero); + e.Graphics.DrawImage(myThumbnail, 150, 75); + } + // + private void Form1_Paint(object sender, PaintEventArgs e) + { + DrawCaps(e); + //ConstructAnIconFromAType(e); + ShowOutputChannels(e); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs new file mode 100644 index 0000000000..1f6b118331 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/CS/Class1.cs @@ -0,0 +1,263 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +public class SystemDrawingMiscLegacyTopics +{ + + // 1e717711-1361-448e-aa49-0f3ec43110c9 + // Using the World Transformation + + private void Method11(PaintEventArgs e) + { + // + Rectangle rect = new Rectangle(0, 0, 50, 50); + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + e.Graphics.DrawRectangle(pen, rect); + // + } + private void Method12(PaintEventArgs e) + { + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + Rectangle rect = new Rectangle(0, 0, 50, 50); + // + e.Graphics.ScaleTransform(1.75f, 0.5f); + e.Graphics.DrawRectangle(pen, rect); + // + } + private void Method13(PaintEventArgs e) + { + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + Rectangle rect = new Rectangle(0, 0, 50, 50); + // + e.Graphics.ResetTransform(); + e.Graphics.RotateTransform(28); // 28 degrees + e.Graphics.DrawRectangle(pen, rect); + // + } + private void Method14(PaintEventArgs e) + { + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + Rectangle rect = new Rectangle(0, 0, 50, 50); + // + e.Graphics.ResetTransform(); + e.Graphics.TranslateTransform(150, 150); + e.Graphics.DrawRectangle(pen, rect); + // + } + // 37d5f9dc-a5cf-4475-aa5d-34d714e808a9 + // Why Transformation Order Is Significant + + private void Method21(PaintEventArgs e) + { + // + Rectangle rect = new Rectangle(0, 0, 50, 50); + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + e.Graphics.ResetTransform(); + e.Graphics.ScaleTransform(1.75f, 0.5f); + e.Graphics.RotateTransform(28, MatrixOrder.Append); + e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append); + e.Graphics.DrawRectangle(pen, rect); + // + } + private void Method22(PaintEventArgs e) + { + // + Rectangle rect = new Rectangle(0, 0, 50, 50); + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + e.Graphics.ResetTransform(); + e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append); + e.Graphics.RotateTransform(28, MatrixOrder.Append); + e.Graphics.ScaleTransform(1.75f, 0.5f); + e.Graphics.DrawRectangle(pen, rect); + // + } + private void Method23(PaintEventArgs e) + { + // + Rectangle rect = new Rectangle(0, 0, 50, 50); + Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2); + e.Graphics.ResetTransform(); + e.Graphics.TranslateTransform(150, 150, MatrixOrder.Prepend); + e.Graphics.RotateTransform(28, MatrixOrder.Prepend); + e.Graphics.ScaleTransform(1.75f, 0.5f); + e.Graphics.DrawRectangle(pen, rect); + // + } + // 3a4c07cb-a40a-4d14-ad35-008f531910a8 + // How to: Use Hit Testing with a Region + + private void Method31(PaintEventArgs e) + { + // + Point point = new Point(60, 10); + + // Assume that the variable "point" contains the location of the + // most recent mouse click. + // To simulate a hit, assign (60, 10) to point. + // To simulate a miss, assign (0, 0) to point. + + SolidBrush solidBrush = new SolidBrush(Color.Black); + Region region1 = new Region(new Rectangle(50, 0, 50, 150)); + Region region2 = new Region(new Rectangle(0, 50, 150, 50)); + + // Create a plus-shaped region by forming the union of region1 and + // region2. + // The union replaces region1. + region1.Union(region2); + + if (region1.IsVisible(point, e.Graphics)) + { + // The point is in the region. Use an opaque brush. + solidBrush.Color = Color.FromArgb(255, 255, 0, 0); + } + else + { + // The point is not in the region. Use a semitransparent brush. + solidBrush.Color = Color.FromArgb(64, 255, 0, 0); + } + + e.Graphics.FillRegion(solidBrush, region1); + // + } + // 43d121b4-e14c-4901-b25c-2d6c25ba4e29 + // How to: Use Clipping with a Region + + private void Method41(PaintEventArgs e) + { + // + // Create a path that consists of a single polygon. + Point[] polyPoints = { + new Point(10, 10), + new Point(150, 10), + new Point(100, 75), + new Point(100, 150)}; + GraphicsPath path = new GraphicsPath(); + path.AddPolygon(polyPoints); + + // Construct a region based on the path. + Region region = new Region(path); + + // Draw the outline of the region. + Pen pen = Pens.Black; + e.Graphics.DrawPath(pen, path); + + // Set the clipping region of the Graphics object. + e.Graphics.SetClip(region, CombineMode.Replace); + + // Draw some clipped strings. + FontFamily fontFamily = new FontFamily("Arial"); + Font font = new Font( + fontFamily, + 36, FontStyle.Bold, + GraphicsUnit.Pixel); + SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0)); + + e.Graphics.DrawString( + "A Clipping Region", + font, solidBrush, + new PointF(15, 25)); + + e.Graphics.DrawString( + "A Clipping Region", + font, + solidBrush, + new PointF(15, 68)); + // + } + + // a0d9f178-43a4-4323-bb5a-d3e3f77ae6c1 + // Using Nested Graphics Containers + + private void Method61(PaintEventArgs e) + { + // + Graphics graphics = e.Graphics; + Pen pen = new Pen(Color.Red); + GraphicsContainer graphicsContainer; + graphics.FillRectangle(Brushes.Black, 100, 80, 3, 3); + + graphics.TranslateTransform(100, 80); + + graphicsContainer = graphics.BeginContainer(); + graphics.RotateTransform(30); + graphics.DrawRectangle(pen, -60, -30, 120, 60); + graphics.EndContainer(graphicsContainer); + + graphics.DrawRectangle(pen, -60, -30, 120, 60); + // + } + private void Method62(PaintEventArgs e) + { + // + Graphics graphics = e.Graphics; + GraphicsContainer graphicsContainer; + Pen redPen = new Pen(Color.Red, 2); + Pen bluePen = new Pen(Color.Blue, 2); + SolidBrush aquaBrush = new SolidBrush(Color.FromArgb(255, 180, 255, 255)); + SolidBrush greenBrush = new SolidBrush(Color.FromArgb(255, 150, 250, 130)); + + graphics.SetClip(new Rectangle(50, 65, 150, 120)); + graphics.FillRectangle(aquaBrush, 50, 65, 150, 120); + + graphicsContainer = graphics.BeginContainer(); + // Create a path that consists of a single ellipse. + GraphicsPath path = new GraphicsPath(); + path.AddEllipse(75, 50, 100, 150); + + // Construct a region based on the path. + Region region = new Region(path); + graphics.FillRegion(greenBrush, region); + + graphics.SetClip(region, CombineMode.Replace); + graphics.DrawLine(redPen, 50, 0, 350, 300); + graphics.EndContainer(graphicsContainer); + + graphics.DrawLine(bluePen, 70, 0, 370, 300); + // + } + private void Method63(PaintEventArgs e) + { + // + Graphics graphics = e.Graphics; + GraphicsContainer innerContainer; + GraphicsContainer outerContainer; + SolidBrush brush = new SolidBrush(Color.Blue); + FontFamily fontFamily = new FontFamily("Times New Roman"); + Font font = new Font(fontFamily, 36, FontStyle.Regular, GraphicsUnit.Pixel); + + graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; + + outerContainer = graphics.BeginContainer(); + + graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel; + + innerContainer = graphics.BeginContainer(); + graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; + graphics.DrawString( + "Inner Container", + font, + brush, + new PointF(20, 10)); + graphics.EndContainer(innerContainer); + + graphics.DrawString( + "Outer Container", + font, + brush, + new PointF(20, 50)); + + graphics.EndContainer(outerContainer); + + graphics.DrawString( + "Graphics Object", + font, + brush, + new PointF(20, 90)); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs new file mode 100644 index 0000000000..15e23792a7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/CS/Form1.cs @@ -0,0 +1,87 @@ +// +using System; +using System.Drawing; +using System.IO; +using System.Drawing.Printing; +using System.Windows.Forms; + +namespace PrintApp +{ + public class Form1 : Form + { + private Button printButton; + // + private PrintDocument printDocument1 = new PrintDocument(); + private string stringToPrint; + // + public Form1() + { + this.printButton = new System.Windows.Forms.Button(); + this.printButton.Location = new System.Drawing.Point(12, 51); + this.printButton.Size = new System.Drawing.Size(75, 23); + this.printButton.Text = "Print"; + this.printButton.Click += new System.EventHandler(this.printButton_Click); + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.printButton); + + // Associate the PrintPage event handler with the PrintPage event. + printDocument1.PrintPage += + new PrintPageEventHandler(printDocument1_PrintPage); + } + + private void ReadFile() + { + // + string docName = "testPage.txt"; + string docPath = @"c:\"; + printDocument1.DocumentName = docName; + using (FileStream stream = new FileStream(docPath + docName, FileMode.Open)) + using (StreamReader reader = new StreamReader(stream)) + { + stringToPrint = reader.ReadToEnd(); + } + // + } + + // + private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) + { + int charactersOnPage = 0; + int linesPerPage = 0; + + // Sets the value of charactersOnPage to the number of characters + // of stringToPrint that will fit within the bounds of the page. + e.Graphics.MeasureString(stringToPrint, this.Font, + e.MarginBounds.Size, StringFormat.GenericTypographic, + out charactersOnPage, out linesPerPage); + + // Draws the string within the bounds of the page + e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, + e.MarginBounds, StringFormat.GenericTypographic); + + // Remove the portion of the string that has been printed. + stringToPrint = stringToPrint.Substring(charactersOnPage); + + // Check to see if more pages are to be printed. + e.HasMorePages = (stringToPrint.Length > 0); + } + // + + private void printButton_Click(object sender, EventArgs e) + { + ReadFile(); + // + printDocument1.Print(); + // + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs new file mode 100644 index 0000000000..b6a741db3a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/CS/Form1.cs @@ -0,0 +1,100 @@ +// +using System; +using System.Drawing; +using System.IO; +using System.Drawing.Printing; +using System.Windows.Forms; + +namespace PrintPreviewApp +{ + public partial class Form1 : Form + { + private Button printPreviewButton; + + // + private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog(); + private PrintDocument printDocument1 = new PrintDocument(); + + // Declare a string to hold the entire document contents. + private string documentContents; + + // Declare a variable to hold the portion of the document that + // is not printed. + private string stringToPrint; + // + + public Form1() + { + this.printPreviewButton = new System.Windows.Forms.Button(); + this.printPreviewButton.Location = new System.Drawing.Point(12, 12); + this.printPreviewButton.Size = new System.Drawing.Size(125, 23); + this.printPreviewButton.Text = "Print Preview"; + this.printPreviewButton.Click += new System.EventHandler(this.printPreviewButton_Click); + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.printPreviewButton); + printDocument1.PrintPage += + new PrintPageEventHandler(printDocument1_PrintPage); + } + // + private void ReadDocument() + { + string docName = "testPage.txt"; + string docPath = @"c:\"; + printDocument1.DocumentName = docName; + using (FileStream stream = new FileStream(docPath + docName, FileMode.Open)) + using (StreamReader reader = new StreamReader(stream)) + { + documentContents = reader.ReadToEnd(); + } + stringToPrint = documentContents; + } + // + + // + void printDocument1_PrintPage(object sender, PrintPageEventArgs e) + { + int charactersOnPage = 0; + int linesPerPage = 0; + + // Sets the value of charactersOnPage to the number of characters + // of stringToPrint that will fit within the bounds of the page. + e.Graphics.MeasureString(stringToPrint, this.Font, + e.MarginBounds.Size, StringFormat.GenericTypographic, + out charactersOnPage, out linesPerPage); + + // Draws the string within the bounds of the page. + e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, + e.MarginBounds, StringFormat.GenericTypographic); + + // Remove the portion of the string that has been printed. + stringToPrint = stringToPrint.Substring(charactersOnPage); + + // Check to see if more pages are to be printed. + e.HasMorePages = (stringToPrint.Length > 0); + + // If there are no more pages, reset the string to be printed. + if (!e.HasMorePages) + stringToPrint = documentContents; + } + // + // + private void printPreviewButton_Click(object sender, EventArgs e) + { + ReadDocument(); + // + printPreviewDialog1.Document = printDocument1; + // + printPreviewDialog1.ShowDialog(); + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs new file mode 100644 index 0000000000..2ff97286b5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RecoloringImages/CS/Class1.cs @@ -0,0 +1,187 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Imaging; + +public class SystemDrawingRecoloringImages +{ + + // 2106fb9a-4d60-4dcf-9220-9f189a6c4d19 + // How to: Translate Image Colors + + private void Method11(PaintEventArgs e) + { + // + Image image = new Bitmap("ColorBars.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + + float[][] colorMatrixElements = { + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0, 0, 1, 0, 0}, + new float[] {0, 0, 0, 1, 0}, + new float[] {.75f, 0, 0, 0, 1}}; + + ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); + + imageAttributes.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10, width, height); + + e.Graphics.DrawImage( + image, + new Rectangle(150, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + // + } + // 44df4556-a433-49c0-ac0f-9a12063a5860 + // How to: Use a Color Matrix to Transform a Single Color + + private void Method21(PaintEventArgs e) + { + // + Image image = new Bitmap("InputColor.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + + float[][] colorMatrixElements = { + new float[] {2, 0, 0, 0, 0}, // red scaling factor of 2 + new float[] {0, 1, 0, 0, 0}, // green scaling factor of 1 + new float[] {0, 0, 1, 0, 0}, // blue scaling factor of 1 + new float[] {0, 0, 0, 1, 0}, // alpha scaling factor of 1 + new float[] {.2f, .2f, .2f, 0, 1}}; // three translations of 0.2 + + ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); + + imageAttributes.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10); + + e.Graphics.DrawImage( + image, + new Rectangle(120, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + // + } + // 977df1ce-8665-42d4-9fb1-ef7f0ff63419 + // How to: Use a Color Remap Table + + private void Method31(PaintEventArgs e) + { + // + Image image = new Bitmap("RemapInput.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + ColorMap colorMap = new ColorMap(); + + colorMap.OldColor = Color.FromArgb(255, 255, 0, 0); // opaque red + colorMap.NewColor = Color.FromArgb(255, 0, 0, 255); // opaque blue + + ColorMap[] remapTable = { colorMap }; + + imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10, width, height); + + e.Graphics.DrawImage( + image, + new Rectangle(150, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + // + } + // df23c887-7fd6-4b15-ad94-e30b5bd4b849 + // Using Transformations to Scale Colors + + private void Method41(PaintEventArgs e) + { + // + Image image = new Bitmap("ColorBars2.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + + float[][] colorMatrixElements = { + new float[] {1, 0, 0, 0, 0}, + new float[] {0, 1, 0, 0, 0}, + new float[] {0, 0, 2, 0, 0}, + new float[] {0, 0, 0, 1, 0}, + new float[] {0, 0, 0, 0, 1}}; + + ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); + + imageAttributes.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10, width, height); + + e.Graphics.DrawImage( + image, + new Rectangle(150, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + // + } + private void Method42(PaintEventArgs e) + { + // + Image image = new Bitmap("ColorBars.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + + float[][] colorMatrixElements = { + new float[] {.75F, 0, 0, 0, 0}, + new float[] {0, .65F, 0, 0, 0}, + new float[] {0, 0, .5F, 0, 0}, + new float[] {0, 0, 0, 1F, 0}, + new float[] {0, 0, 0, 0, 1F}}; + + ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); + + imageAttributes.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10, width, height); + + e.Graphics.DrawImage( + image, + new Rectangle(150, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RotateColors/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RotateColors/CS/Form1.cs new file mode 100644 index 0000000000..bf3cee0d3a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.RotateColors/CS/Form1.cs @@ -0,0 +1,70 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; +using System.Drawing.Imaging; + +#endregion + +namespace RotateColors +{ + public class Form1 : Form + { + public Form1() + { + this.Paint +=new PaintEventHandler(Form1_Paint); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + void Form1_Paint(object sender, PaintEventArgs e) + { + RotateColors(e); + } +// + private void RotateColors(PaintEventArgs e) + { + Bitmap image = new Bitmap("RotationInput.bmp"); + ImageAttributes imageAttributes = new ImageAttributes(); + int width = image.Width; + int height = image.Height; + float degrees = 60f; + double r = degrees * System.Math.PI / 180; // degrees to radians + + float[][] colorMatrixElements = { + new float[] {(float)System.Math.Cos(r), (float)System.Math.Sin(r), 0, 0, 0}, + new float[] {(float)-System.Math.Sin(r), (float)-System.Math.Cos(r), 0, 0, 0}, + new float[] {0, 0, 2, 0, 0}, + new float[] {0, 0, 0, 1, 0}, + new float[] {0, 0, 0, 0, 1}}; + + ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); + + imageAttributes.SetColorMatrix( + colorMatrix, + ColorMatrixFlag.Default, + ColorAdjustType.Bitmap); + + e.Graphics.DrawImage(image, 10, 10, width, height); + + e.Graphics.DrawImage( + image, + new Rectangle(150, 10, width, height), // destination rectangle + 0, 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + imageAttributes); + } +// + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs new file mode 100644 index 0000000000..7326ebb8c0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingABrush/CS/Class1.cs @@ -0,0 +1,100 @@ +using System; +using System.Diagnostics; +using System.Windows.Forms; +using System.Xml; +using System.Data; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; + +public class class1 +{ + // 06088b31-bac9-4ef3-9ebe-06c2c764d6df + // How to: Fill a Shape with a Solid Color + + public void Method11(PaintEventArgs e) + { + // + SolidBrush solidBrush = new SolidBrush( + Color.FromArgb(255, 255, 0, 0)); + e.Graphics.FillEllipse(solidBrush, 0, 0, 100, 60); + // + } + // 508da5a6-2433-4d2b-9680-eaeae4e96e3b + // How to: Fill a Shape with an Image Texture + + public void Method21(PaintEventArgs e) + { + // + Image image = new Bitmap("ImageFile.jpg"); + TextureBrush tBrush = new TextureBrush(image); + tBrush.Transform = new Matrix( + 75.0f / 640.0f, + 0.0f, + 0.0f, + 75.0f / 480.0f, + 0.0f, + 0.0f); + e.Graphics.FillEllipse(tBrush, new Rectangle(0, 150, 150, 250)); + // + } + // 6d407891-6e5c-4495-a546-3da5604e9fb8 + // How to: Tile a Shape with an Image + + public void Method31(PaintEventArgs e) + { + // + Image image = new Bitmap("HouseAndTree.gif"); + TextureBrush tBrush = new TextureBrush(image); + Pen blackPen = new Pen(Color.Black); + e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200)); + e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200)); + // + } + public void Method32(PaintEventArgs e) + { + // + Image image = new Bitmap("HouseAndTree.gif"); + TextureBrush tBrush = new TextureBrush(image); + Pen blackPen = new Pen(Color.Black); + tBrush.WrapMode = WrapMode.TileFlipX; + e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200)); + e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200)); + // + } + public void Method33(PaintEventArgs e) + { + // + Image image = new Bitmap("HouseAndTree.gif"); + TextureBrush tBrush = new TextureBrush(image); + Pen blackPen = new Pen(Color.Black); + tBrush.WrapMode = WrapMode.TileFlipY; + e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200)); + e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200)); + // + } + public void Method34(PaintEventArgs e) + { + // + Image image = new Bitmap("HouseAndTree.gif"); + TextureBrush tBrush = new TextureBrush(image); + Pen blackPen = new Pen(Color.Black); + tBrush.WrapMode = WrapMode.TileFlipXY; + e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200)); + e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200)); + // + } + // 9c8300ff-187b-404f-af1f-ebd499f5b16f + // How to: Fill a Shape with a Hatch Pattern + + public void Method41(PaintEventArgs e) + { + // + HatchBrush hBrush = new HatchBrush( + HatchStyle.Horizontal, + Color.Red, + Color.FromArgb(255, 128, 255, 255)); + e.Graphics.FillEllipse(hBrush, 0, 0, 100, 60); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs new file mode 100644 index 0000000000..49290a5b83 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingAPen/CS/Class1.cs @@ -0,0 +1,133 @@ +using System; +using System.Diagnostics; +using System.Windows.Forms; +using System.Xml; +using System.Data; +using System.Collections; +using System.Drawing; +using System.Drawing.Drawing2D; + +public class Form1 : Form +{ + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + // 0828c331-a438-4bdd-a4d6-3ef1e59e8795 + // How to: Use a Pen to Draw Lines + + public void Method11(PaintEventArgs e) + { + // + Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0)); + e.Graphics.DrawLine(pen, 20, 10, 300, 100); + // + } + // 54a7fa14-3ad8-4d64-b424-2a12005b250c + // How to: Use a Pen to Draw Rectangles + + public void Method21(PaintEventArgs e) + { + // + Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 5); + e.Graphics.DrawRectangle(blackPen, 10, 10, 100, 50); + // + } + // 9fc480c2-3c75-4fd1-8ab5-296a99e820e2 + // How to: Join Lines + + public void Method31(PaintEventArgs e) + { + // + GraphicsPath path = new GraphicsPath(); + Pen penJoin = new Pen(Color.FromArgb(255, 0, 0, 255), 8); + + path.StartFigure(); + path.AddLine(new Point(50, 200), new Point(100, 200)); + path.AddLine(new Point(100, 200), new Point(100, 250)); + + penJoin.LineJoin = LineJoin.Bevel; + e.Graphics.DrawPath(penJoin, path); + + // + } + // a202af36-4d31-4401-a126-b232f51db581 + // How to: Set Pen Width and Alignment + + public void Method41(PaintEventArgs e) + { + // + Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1); + Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10); + greenPen.Alignment = PenAlignment.Center; + + // Draw the line with the wide green pen. + e.Graphics.DrawLine(greenPen, 10, 100, 100, 50); + + // Draw the line with the thin black pen. + e.Graphics.DrawLine(blackPen, 10, 100, 100, 50); + // + } + public void Method42(PaintEventArgs e) + { + // + Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1); + Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10); + greenPen.Alignment = PenAlignment.Center; + + // Draw the rectangle with the wide green pen. + e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50); + + // Draw the rectangle with the thin black pen. + e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50); + // + } + public void Method43(PaintEventArgs e) + { + Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10); + // + greenPen.Alignment = PenAlignment.Inset; + // + } + // cd0ed96a-cce4-47b9-b58a-3bae2e3d1bee + // How to: Draw a Custom Dashed Line + + public void Method51(PaintEventArgs e) + { + // + float[] dashValues = { 5, 2, 15, 4 }; + Pen blackPen = new Pen(Color.Black, 5); + blackPen.DashPattern = dashValues; + e.Graphics.DrawLine(blackPen, new Point(5, 5), new Point(405, 5)); + // + } + // dc9118cc-f3c2-42e5-8173-f46d41d18fd5 + // How to: Draw a Line Filled with a Texture + + public void Method61(PaintEventArgs e) + { + // + Bitmap bitmap = new Bitmap("Texture1.jpg"); + TextureBrush tBrush = new TextureBrush(bitmap); + Pen texturedPen = new Pen(tBrush, 30); + + e.Graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height); + e.Graphics.DrawEllipse(texturedPen, 100, 20, 200, 100); + // + } + // eb68c3e1-c400-4886-8a04-76978a429cb6 + // How to: Draw a Line with Line Caps + + public void Method71(PaintEventArgs e) + { + // + Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255), 8); + pen.StartCap = LineCap.ArrowAnchor; + pen.EndCap = LineCap.RoundAnchor; + e.Graphics.DrawLine(pen, 20, 175, 300, 175); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs new file mode 100644 index 0000000000..d9b7fb61a8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/CS/Class1.cs @@ -0,0 +1,308 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Drawing2D; + +public class class1 +{ + + // 1948e834-e104-481c-b71d-d8aa9e4d106e + // How to: Create a Path Gradient + + // + public void FillEllipseWithPathGradient(PaintEventArgs e) + { + // Create a path that consists of a single ellipse. + GraphicsPath path = new GraphicsPath(); + path.AddEllipse(0, 0, 140, 70); + + // Use the path to construct a brush. + PathGradientBrush pthGrBrush = new PathGradientBrush(path); + + // Set the color at the center of the path to blue. + pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255); + + // Set the color along the entire boundary + // of the path to aqua. + Color[] colors = { Color.FromArgb(255, 0, 255, 255) }; + pthGrBrush.SurroundColors = colors; + + e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70); + } + // + + // + public void ConstructBrushFromStarShapedPath(PaintEventArgs e) + { + // Put the points of a polygon in an array. + Point[] points = { + new Point(75, 0), + new Point(100, 50), + new Point(150, 50), + new Point(112, 75), + new Point(150, 150), + new Point(75, 100), + new Point(0, 150), + new Point(37, 75), + new Point(0, 50), + new Point(50, 50)}; + + // Use the array of points to construct a path. + GraphicsPath path = new GraphicsPath(); + path.AddLines(points); + + // Use the path to construct a path gradient brush. + PathGradientBrush pthGrBrush = new PathGradientBrush(path); + + // Set the color at the center of the path to red. + pthGrBrush.CenterColor = Color.FromArgb(255, 255, 0, 0); + + // Set the colors of the points in the array. + Color[] colors = { + Color.FromArgb(255, 0, 0, 0), + Color.FromArgb(255, 0, 255, 0), + Color.FromArgb(255, 0, 0, 255), + Color.FromArgb(255, 255, 255, 255), + Color.FromArgb(255, 0, 0, 0), + Color.FromArgb(255, 0, 255, 0), + Color.FromArgb(255, 0, 0, 255), + Color.FromArgb(255, 255, 255, 255), + Color.FromArgb(255, 0, 0, 0), + Color.FromArgb(255, 0, 255, 0)}; + + pthGrBrush.SurroundColors = colors; + + // Fill the path with the path gradient brush. + e.Graphics.FillPath(pthGrBrush, path); + } + // + + // + public void DrawPathGradentWthoutGraphicsPath(PaintEventArgs e) + { + // Construct a path gradient brush based on an array of points. + PointF[] ptsF = { + new PointF(0, 0), + new PointF(160, 0), + new PointF(160, 200), + new PointF(80, 150), + new PointF(0, 200)}; + + PathGradientBrush pBrush = new PathGradientBrush(ptsF); + + // An array of five points was used to construct the path gradient + // brush. Set the color of each point in that array. + Color[] colors = { + Color.FromArgb(255, 255, 0, 0), // (0, 0) red + Color.FromArgb(255, 0, 255, 0), // (160, 0) green + Color.FromArgb(255, 0, 255, 0), // (160, 200) green + Color.FromArgb(255, 0, 0, 255), // (80, 150) blue + Color.FromArgb(255, 255, 0, 0)}; // (0, 200) red + + pBrush.SurroundColors = colors; + + // Set the center color to white. + pBrush.CenterColor = Color.White; + + // Use the path gradient brush to fill a rectangle. + e.Graphics.FillRectangle(pBrush, new Rectangle(0, 0, 160, 200)); + } + // + + // + public void CustomizePathGradientBrush(PaintEventArgs e) + { + // Create a path that consists of a single ellipse. + GraphicsPath path = new GraphicsPath(); + path.AddEllipse(0, 0, 200, 100); + + // Create a path gradient brush based on the elliptical path. + PathGradientBrush pthGrBrush = new PathGradientBrush(path); + + // Set the color along the entire boundary to blue. + Color[] color = { Color.Blue }; + pthGrBrush.SurroundColors = color; + + // Set the center color to aqua. + pthGrBrush.CenterColor = Color.Aqua; + + // Use the path gradient brush to fill the ellipse. + e.Graphics.FillPath(pthGrBrush, path); + + // Set the focus scales for the path gradient brush. + pthGrBrush.FocusScales = new PointF(0.3f, 0.8f); + + // Use the path gradient brush to fill the ellipse again. + // Show this filled ellipse to the right of the first filled ellipse. + e.Graphics.TranslateTransform(220.0f, 0.0f); + e.Graphics.FillPath(pthGrBrush, path); + } + // + + // + public void CustomizeWithInterpolation(PaintEventArgs e) + { + // Vertices of the outer triangle + Point[] points = { + new Point(100, 0), + new Point(200, 200), + new Point(0, 200)}; + + // No GraphicsPath object is created. The PathGradientBrush + // object is constructed directly from the array of points. + PathGradientBrush pthGrBrush = new PathGradientBrush(points); + + Color[] colors = { + Color.FromArgb(255, 0, 128, 0), // dark green + Color.FromArgb(255, 0, 255, 255), // aqua + Color.FromArgb(255, 0, 0, 255)}; // blue + + float[] relativePositions = { + 0f, // Dark green is at the boundary of the triangle. + 0.4f, // Aqua is 40 percent of the way from the boundary + // to the center point. + 1.0f}; // Blue is at the center point. + + ColorBlend colorBlend = new ColorBlend(); + colorBlend.Colors = colors; + colorBlend.Positions = relativePositions; + pthGrBrush.InterpolationColors = colorBlend; + + // Fill a rectangle that is larger than the triangle + // specified in the Point array. The portion of the + // rectangle outside the triangle will not be painted. + e.Graphics.FillRectangle(pthGrBrush, 0, 0, 200, 200); + } + // + + // + public void SetCenterPoint(PaintEventArgs e) + { + // Create a path that consists of a single ellipse. + GraphicsPath path = new GraphicsPath(); + path.AddEllipse(0, 0, 140, 70); + + // Use the path to construct a brush. + PathGradientBrush pthGrBrush = new PathGradientBrush(path); + + // Set the center point to a location that is not + // the centroid of the path. + pthGrBrush.CenterPoint = new PointF(120, 40); + + // Set the color at the center of the path to blue. + pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255); + + // Set the color along the entire boundary + // of the path to aqua. + Color[] colors = { Color.FromArgb(255, 0, 255, 255) }; + pthGrBrush.SurroundColors = colors; + + e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70); + } + // + + // + public void SetCenterPointOutsidePath(PaintEventArgs e) + { + // Create a path that consists of a single ellipse. + GraphicsPath path = new GraphicsPath(); + path.AddEllipse(0, 0, 140, 70); + + // Use the path to construct a brush. + PathGradientBrush pthGrBrush = new PathGradientBrush(path); + + // Set the center point to a location that is not + // the centroid of the path. + pthGrBrush.CenterPoint = new PointF(145, 35); + + // Set the color at the center of the path to blue. + pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255); + + // Set the color along the entire boundary + // of the path to aqua. + Color[] colors = { Color.FromArgb(255, 0, 255, 255) }; + pthGrBrush.SurroundColors = colors; + + e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70); + } + // + + // 6c88e1cc-1217-4399-ac12-cb37592b9f01 + // How to: Create a Linear Gradient + + // + public void UseHorizontalLinearGradients(PaintEventArgs e) + { + LinearGradientBrush linGrBrush = new LinearGradientBrush( + new Point(0, 10), + new Point(200, 10), + Color.FromArgb(255, 255, 0, 0), // Opaque red + Color.FromArgb(255, 0, 0, 255)); // Opaque blue + + Pen pen = new Pen(linGrBrush); + + e.Graphics.DrawLine(pen, 0, 10, 200, 10); + e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100); + e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30); + } + // + + // + public void CustomizeLinearGradients(PaintEventArgs e) + { + LinearGradientBrush linGrBrush = new LinearGradientBrush( + new Point(0, 10), + new Point(200, 10), + Color.FromArgb(255, 0, 0, 0), // Opaque black + Color.FromArgb(255, 255, 0, 0)); // Opaque red + + float[] relativeIntensities = { 0.0f, 0.5f, 1.0f }; + float[] relativePositions = { 0.0f, 0.2f, 1.0f }; + + //Create a Blend object and assign it to linGrBrush. + Blend blend = new Blend(); + blend.Factors = relativeIntensities; + blend.Positions = relativePositions; + linGrBrush.Blend = blend; + + e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100); + e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30); + } + // + + // + public void CreateDiagonalLinearGradients(PaintEventArgs e) + { + LinearGradientBrush linGrBrush = new LinearGradientBrush( + new Point(0, 0), + new Point(200, 100), + Color.FromArgb(255, 0, 0, 255), // opaque blue + Color.FromArgb(255, 0, 255, 0)); // opaque green + + Pen pen = new Pen(linGrBrush, 10); + + e.Graphics.DrawLine(pen, 0, 0, 600, 300); + e.Graphics.FillEllipse(linGrBrush, 10, 100, 200, 100); + } + // + + // da4690e7-5fac-4fd2-b3f0-5cb35c165b92 + // How to: Apply Gamma Correction to a Gradient + + // + public void FillTwoRectangles(PaintEventArgs e) + { + LinearGradientBrush linGrBrush = new LinearGradientBrush( + new Point(0, 10), + new Point(200, 10), + Color.Red, + Color.Blue); + + e.Graphics.FillRectangle(linGrBrush, 0, 0, 200, 50); + linGrBrush.GammaCorrection = true; + e.Graphics.FillRectangle(linGrBrush, 0, 60, 200, 50); + } + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs new file mode 100644 index 0000000000..2acd89631f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/CS/Class1.cs @@ -0,0 +1,267 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; + +public class SystemDrawingWorkingWithImages : Form +{ + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new SystemDrawingWorkingWithImages()); + } + + // 053e3360-bca0-4b25-9afa-0e77a6f17b03 + // How to: Crop and Scale Images + + private void Method11(PaintEventArgs e) + { + // + Image image = new Bitmap("Apple.gif"); + + // Draw the image unaltered with its upper-left corner at (0, 0). + e.Graphics.DrawImage(image, 0, 0); + + // Make the destination rectangle 30 percent wider and + // 30 percent taller than the original image. + // Put the upper-left corner of the destination + // rectangle at (150, 20). + int width = image.Width; + int height = image.Height; + RectangleF destinationRect = new RectangleF( + 150, + 20, + 1.3f * width, + 1.3f * height); + + // Draw a portion of the image. Scale that portion of the image + // so that it fills the destination rectangle. + RectangleF sourceRect = new RectangleF(0, 0, .75f * width, .75f * height); + e.Graphics.DrawImage( + image, + destinationRect, + sourceRect, + GraphicsUnit.Pixel); + // + } + // 5bc558d7-b326-4050-a834-b8600da0de95 + // How to: Load and Display Bitmaps + + private void Method21(PaintEventArgs e) + { + // + Bitmap bitmap = new Bitmap("Grapes.jpg"); + e.Graphics.DrawImage(bitmap, 60, 10); + // + } + // 5fe2c95d-8653-4d55-bf0d-e5afa28f223b + // How to: Improve Performance by Avoiding Automatic Scaling + + private void Method31(PaintEventArgs e) + { + Image image = new Bitmap("Texture.jpg"); + // + e.Graphics.DrawImage(image, 50, 30); // upper-left corner at (50, 30) + // + } + private void Method32(PaintEventArgs e) + { + // + Image image = new Bitmap("Texture.jpg"); + + e.Graphics.DrawImage(image, 10, 10); + e.Graphics.DrawImage(image, 120, 10, image.Width, image.Height); + // + } + // 60af1714-f148-4d85-a739-0557965ffa73 + // How to: Load and Display Metafiles + + private void Method41(PaintEventArgs e) + { + // + Metafile metafile = new Metafile("SampleMetafile.emf"); + e.Graphics.DrawImage(metafile, 60, 10); + // + } + // 72ec0b31-0be7-444a-9575-1dbcb864e0be + // How to: Read Image Metadata + + private void Method51(PaintEventArgs e) + { + // + // Create an Image object. + Image image = new Bitmap(@"c:\FakePhoto.jpg"); + + // Get the PropertyItems property from image. + PropertyItem[] propItems = image.PropertyItems; + + // Set up the display. + Font font = new Font("Arial", 12); + SolidBrush blackBrush = new SolidBrush(Color.Black); + int X = 0; + int Y = 0; + + // For each PropertyItem in the array, display the ID, type, and + // length. + int count = 0; + foreach (PropertyItem propItem in propItems) + { + e.Graphics.DrawString( + "Property Item " + count.ToString(), + font, + blackBrush, + X, Y); + + Y += font.Height; + + e.Graphics.DrawString( + " id: 0x" + propItem.Id.ToString("x"), + font, + blackBrush, + X, Y); + + Y += font.Height; + + e.Graphics.DrawString( + " type: " + propItem.Type.ToString(), + font, + blackBrush, + X, Y); + + Y += font.Height; + + e.Graphics.DrawString( + " length: " + propItem.Len.ToString() + " bytes", + font, + blackBrush, + X, Y); + + Y += font.Height; + + count++; + } + // Convert the value of the second property to a string, and display + // it. + System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); + string manufacturer = encoding.GetString(propItems[1].Value); + + e.Graphics.DrawString( + "The equipment make is " + manufacturer + ".", + font, + blackBrush, + X, Y); + // + } + // a3bf97eb-63ed-425a-ba07-dcc65efb567c + // How to: Rotate, Reflect, and Skew Images + + private void Method61(PaintEventArgs e) + { + // + Point[] destinationPoints = { + new Point(200, 20), // destination for upper-left point of + // original + new Point(110, 100), // destination for upper-right point of + // original + new Point(250, 30)}; // destination for lower-left point of + // original + + Image image = new Bitmap("Stripes.bmp"); + + // Draw the image unaltered with its upper-left corner at (0, 0). + e.Graphics.DrawImage(image, 0, 0); + + // Draw the image mapped to the parallelogram. + e.Graphics.DrawImage(image, destinationPoints); + // + } + // e956242a-1e5b-4217-a3cf-5f3fb45d00ba + // How to: Create Thumbnail Images + + // + public bool ThumbnailCallback() + { + return true; + } + + private void GetThumbnail(PaintEventArgs e) + { + Image.GetThumbnailImageAbort callback = + new Image.GetThumbnailImageAbort(ThumbnailCallback); + Image image = new Bitmap(@"c:\FakePhoto.jpg"); + Image pThumbnail = image.GetThumbnailImage(100, 100, callback, new + IntPtr()); + e.Graphics.DrawImage( + pThumbnail, + 10, + 10, + pThumbnail.Width, + pThumbnail.Height); + } + // + + // fde9bccf-8aa5-4b0d-ba4b-788740627b02 + // How to: Use Interpolation Mode to Control Image Quality During Scaling + + private void Method81(PaintEventArgs e) + { + // + Image image = new Bitmap("GrapeBunch.bmp"); + int width = image.Width; + int height = image.Height; + + // Draw the image with no shrinking or stretching. + e.Graphics.DrawImage( + image, + new Rectangle(10, 10, width, height), // destination rectangle + 0, + 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel, + null); + + // Shrink the image using low-quality interpolation. + e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor; + e.Graphics.DrawImage( + image, + new Rectangle(10, 250, (int)(0.6 * width), (int)(0.6 * height)), + // destination rectangle + 0, + 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel); + + // Shrink the image using medium-quality interpolation. + e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear; + e.Graphics.DrawImage( + image, + new Rectangle(150, 250, (int)(0.6 * width), (int)(0.6 * height)), + // destination rectangle + 0, + 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel); + + // Shrink the image using high-quality interpolation. + e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + e.Graphics.DrawImage( + image, + new Rectangle(290, 250, (int)(0.6 * width), (int)(0.6 * height)), + // destination rectangle + 0, + 0, // upper-left corner of source rectangle + width, // width of source rectangle + height, // height of source rectangle + GraphicsUnit.Pixel); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/CS/Form1.cs new file mode 100644 index 0000000000..4979623c86 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/CS/Form1.cs @@ -0,0 +1,125 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Media; +using System.Windows.Forms; + +namespace SoundPlayerLoadAsyncExample +{ + public class Form1 : Form + { + private SoundPlayer Player = new SoundPlayer(); + + public Form1() + { + InitializeComponent(); + + this.Player.LoadCompleted += new AsyncCompletedEventHandler(Player_LoadCompleted); + } + + private void playSoundButton_Click(object sender, EventArgs e) + { + this.LoadAsyncSound(); + } + + public void LoadAsyncSound() + { + try + { + // Replace this file name with a valid file name. + this.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav"; + this.Player.LoadAsync(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Error loading sound"); + } + } + + // This is the event handler for the LoadCompleted event. + void Player_LoadCompleted(object sender, AsyncCompletedEventArgs e) + { + if (Player.IsLoadCompleted) + { + try + { + this.Player.Play(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Error playing sound"); + } + } + } + + private Button playSoundButton; + + /// + /// 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.playSoundButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // playSoundButton + // + this.playSoundButton.Location = new System.Drawing.Point(106, 112); + this.playSoundButton.Name = "playSoundButton"; + this.playSoundButton.Size = new System.Drawing.Size(75, 23); + this.playSoundButton.TabIndex = 0; + this.playSoundButton.Text = "Play Sound"; + this.playSoundButton.Click += new System.EventHandler(this.playSoundButton_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.playSoundButton); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + #endregion + + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/CS/Form1.cs new file mode 100644 index 0000000000..baf0c9f4e7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/CS/Form1.cs @@ -0,0 +1,121 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Media; +using System.Windows.Forms; + +namespace SoundPlayerPlayLoopingExample +{ + public class Form1 : Form + { + private SoundPlayer Player = new SoundPlayer(); + + public Form1() + { + InitializeComponent(); + } + + private void playLoopingButton_Click(object sender, EventArgs e) + { + try + { + // Note: You may need to change the location specified based on + // the sounds loaded on your computer. + this.Player.SoundLocation = @"C:\Windows\Media\chimes.wav"; + this.Player.PlayLooping(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Error playing sound"); + } + } + + private void stopPlayingButton_Click(object sender, EventArgs e) + { + this.Player.Stop(); + } + + /// + /// 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.playLoopingButton = new System.Windows.Forms.Button(); + this.stopPlayingButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // playLoopingButton + // + this.playLoopingButton.Location = new System.Drawing.Point(12, 12); + this.playLoopingButton.Name = "playLoopingButton"; + this.playLoopingButton.Size = new System.Drawing.Size(87, 23); + this.playLoopingButton.TabIndex = 0; + this.playLoopingButton.Text = "Play Looping"; + this.playLoopingButton.UseVisualStyleBackColor = true; + this.playLoopingButton.Click += new System.EventHandler(this.playLoopingButton_Click); + // + // stopPlayingButton + // + this.stopPlayingButton.Location = new System.Drawing.Point(105, 12); + this.stopPlayingButton.Name = "stopPlayingButton"; + this.stopPlayingButton.Size = new System.Drawing.Size(75, 23); + this.stopPlayingButton.TabIndex = 1; + this.stopPlayingButton.Text = "Stop"; + this.stopPlayingButton.UseVisualStyleBackColor = true; + this.stopPlayingButton.Click += new System.EventHandler(this.stopPlayingButton_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(195, 51); + this.Controls.Add(this.stopPlayingButton); + this.Controls.Add(this.playLoopingButton); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.Button playLoopingButton; + private System.Windows.Forms.Button stopPlayingButton; + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs new file mode 100644 index 0000000000..0bb2043258 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/CS/Form1.cs @@ -0,0 +1,27 @@ +// +// +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +// +// + public class Form1 : Form +// + { + // + public Form1() {} + // + + // + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + // + } + + // \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/CS/form1.cs new file mode 100644 index 0000000000..188ebe7f1d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/CS/form1.cs @@ -0,0 +1,101 @@ +// + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Data.SqlClient; +using System.Windows.Forms; + +namespace DBNullCS +{ + public class Form1 : Form + { + public Form1() + { + this.Load += new EventHandler(Form1_Load); + } + + // The controls and components we need for the form. + private Button button1; + private PictureBox pictureBox1; + private BindingSource bindingSource1; + private TextBox textBox1; + private TextBox textBox2; + + // Data table to hold the database data. + DataTable employeeTable = new DataTable(); + + void Form1_Load(object sender, EventArgs e) + { + // Basic form setup. + this.pictureBox1 = new PictureBox(); + this.bindingSource1 = new BindingSource(); + this.textBox1 = new TextBox(); + this.textBox2 = new TextBox(); + this.button1 = new Button(); + this.pictureBox1.Location = new System.Drawing.Point(20, 20); + this.pictureBox1.Size = new System.Drawing.Size(174, 179); + this.textBox1.Location = new System.Drawing.Point(25, 215); + this.textBox1.ReadOnly = true; + this.textBox2.Location = new System.Drawing.Point(25, 241); + this.textBox2.ReadOnly = true; + this.button1.Location = new System.Drawing.Point(200, 103); + this.button1.Text = "Move Next"; + this.button1.Click += new System.EventHandler(this.button1_Click); + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.button1); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.pictureBox1); + this.ResumeLayout(false); + this.PerformLayout(); + + // Create the connection string and populate the data table + // with data. + string connectionString = "Integrated Security=SSPI;" + + "Persist Security Info = False;Initial Catalog=Northwind;" + + "Data Source = localhost"; + SqlConnection connection = new SqlConnection(); + connection.ConnectionString = connectionString; + SqlDataAdapter employeeAdapter = + new SqlDataAdapter(new SqlCommand("Select * from Employees", connection)); + connection.Open(); + employeeAdapter.Fill(employeeTable); + + // Set the DataSource property of the BindingSource to the employee table. + bindingSource1.DataSource = employeeTable; + + // Set up the binding to the ReportsTo column. + Binding reportsToBinding = textBox2.DataBindings.Add("Text", bindingSource1, + "ReportsTo", true); + + // Set the NullValue property for this binding. + reportsToBinding.NullValue = "No Manager"; + + // Set up the binding for the PictureBox using the Add method, setting + // the null value in method call. + pictureBox1.DataBindings.Add("Image", bindingSource1, "Photo", true, + DataSourceUpdateMode.Never, new Bitmap(typeof(Button), "Button.bmp")); + + // Set up the remaining binding. + textBox1.DataBindings.Add("Text", bindingSource1, "LastName", true); + } + + // Move through the data when the button is clicked. + private void button1_Click(object sender, EventArgs e) + { + bindingSource1.MoveNext(); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/CS/Form1.cs new file mode 100644 index 0000000000..2358dc01f5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/CS/Form1.cs @@ -0,0 +1,228 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; +using System.Xml; +using System.IO; +using System.Text; + +namespace System.Windows.Forms.BindingSourceCurrent +{ + class Form1 : Form + { + private IContainer components; + private BindingNavigator bindingNavigator1; + private ToolStripButton bindingNavigatorAddNewItem; + private ToolStripLabel bindingNavigatorCountItem; + private ToolStripButton bindingNavigatorDeleteItem; + private ToolStripButton bindingNavigatorMoveFirstItem; + private ToolStripButton bindingNavigatorMovePreviousItem; + private ToolStripSeparator bindingNavigatorSeparator; + private ToolStripTextBox bindingNavigatorPositionItem; + private ToolStripSeparator bindingNavigatorSeparator1; + private ToolStripButton bindingNavigatorMoveNextItem; + private ToolStripButton bindingNavigatorMoveLastItem; + private TextBox textBox1; + private TextBox textBox2; + private BindingSource bindingSource1; + private ToolStripSeparator bindingNavigatorSeparator2; + + public Form1() + { + InitializeComponent(); + LoadData(); + + // + bindingNavigator1.BindingSource = bindingSource1; + // + } + // + private void LoadData() + { + // The xml to bind to. + string xml = @"" + + @"WashingtonOlympia" + + @"OregonSalem" + + @"CaliforniaSacramento" + + @"NevadaCarson City" + + @""; + + // Convert the xml string to bytes and load into a memory stream. + byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); + MemoryStream stream = new MemoryStream(xmlBytes, false); + + // Create a DataSet and load the xml into it. + DataSet set = new DataSet(); + set.ReadXml(stream); + + // Set the DataSource to the DataSet, and the DataMember + // to state. + bindingSource1.DataSource = set; + bindingSource1.DataMember = "state"; + + textBox1.DataBindings.Add("Text", bindingSource1, "name"); + textBox2.DataBindings.Add("Text", bindingSource1, "capital"); + } + // + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = + new System.ComponentModel.ComponentResourceManager(typeof(Form1)); + this.bindingNavigator1 = new System.Windows.Forms.BindingNavigator(this.components); + this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton(); + this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); + this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton(); + this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); + this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); + this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); + this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); + this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); + this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); + this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); + this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components); + ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator1)).BeginInit(); + this.bindingNavigator1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit(); + this.SuspendLayout(); + // + // bindingNavigator1 + // + this.bindingNavigator1.AddNewItem = this.bindingNavigatorAddNewItem; + this.bindingNavigator1.CountItem = this.bindingNavigatorCountItem; + this.bindingNavigator1.CountItemFormat = "of {0}"; + this.bindingNavigator1.DeleteItem = this.bindingNavigatorDeleteItem; + this.bindingNavigator1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.bindingNavigatorMoveFirstItem, + this.bindingNavigatorMovePreviousItem, + this.bindingNavigatorSeparator, + this.bindingNavigatorPositionItem, + this.bindingNavigatorCountItem, + this.bindingNavigatorSeparator1, + this.bindingNavigatorMoveNextItem, + this.bindingNavigatorMoveLastItem, + this.bindingNavigatorSeparator2, + this.bindingNavigatorAddNewItem, + this.bindingNavigatorDeleteItem}); + this.bindingNavigator1.Location = new System.Drawing.Point(0, 0); + this.bindingNavigator1.MoveFirstItem = this.bindingNavigatorMoveFirstItem; + this.bindingNavigator1.MoveLastItem = this.bindingNavigatorMoveLastItem; + this.bindingNavigator1.MoveNextItem = this.bindingNavigatorMoveNextItem; + this.bindingNavigator1.MovePreviousItem = this.bindingNavigatorMovePreviousItem; + this.bindingNavigator1.Name = "bindingNavigator1"; + this.bindingNavigator1.PositionItem = this.bindingNavigatorPositionItem; + this.bindingNavigator1.TabIndex = 2; + this.bindingNavigator1.Text = "bindingNavigator1"; + // + // bindingNavigatorAddNewItem + // + this.bindingNavigatorAddNewItem.Image = + ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image"))); + this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem"; + this.bindingNavigatorAddNewItem.Text = "Add new"; + // + // bindingNavigatorCountItem + // + this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; + this.bindingNavigatorCountItem.Text = "of {0}"; + this.bindingNavigatorCountItem.ToolTipText = "Total number of items"; + // + // bindingNavigatorDeleteItem + // + this.bindingNavigatorDeleteItem.Image = + ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image"))); + this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem"; + this.bindingNavigatorDeleteItem.Text = "Delete"; + // + // bindingNavigatorMoveFirstItem + // + this.bindingNavigatorMoveFirstItem.Image = + ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); + this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; + this.bindingNavigatorMoveFirstItem.Text = "Move first"; + // + // bindingNavigatorMovePreviousItem + // + this.bindingNavigatorMovePreviousItem.Image = + ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); + this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; + this.bindingNavigatorMovePreviousItem.Text = "Move previous"; + // + // bindingNavigatorSeparator + // + this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; + // + // bindingNavigatorPositionItem + // + this.bindingNavigatorPositionItem.DisplayStyle = + System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; + this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; + this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 25); + this.bindingNavigatorPositionItem.Text = "0"; + this.bindingNavigatorPositionItem.ToolTipText = "Current position"; + // + // bindingNavigatorSeparator1 + // + this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; + + // bindingNavigatorMoveNextItem + // + this.bindingNavigatorMoveNextItem.Image = + ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); + this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; + this.bindingNavigatorMoveNextItem.Text = "Move next"; + // + // bindingNavigatorMoveLastItem + // + this.bindingNavigatorMoveLastItem.Image = + ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); + this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; + this.bindingNavigatorMoveLastItem.Text = "Move last"; + // + // bindingNavigatorSeparator2 + // + this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(46, 64); + this.textBox1.Name = "textBox1"; + this.textBox1.TabIndex = 3; + // + // textBox2 + // + this.textBox2.Location = new System.Drawing.Point(46, 104); + this.textBox2.Name = "textBox2"; + this.textBox2.TabIndex = 4; + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.bindingNavigator1); + this.Name = "Form1"; + ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator1)).EndInit(); + this.bindingNavigator1.ResumeLayout(false); + this.bindingNavigator1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/CS/Form1.cs new file mode 100644 index 0000000000..68ccaedee9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/CS/Form1.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.IO; + +namespace MultipleControls +{ + public class Form1 : Form + { + + public Form1() + { + this.Load += new EventHandler(Form1_Load); + } + + private void Form1_Load(object sender, EventArgs e) + { + //InitializeControlsAndDataSource(); + InitializeControlsAndData(); + } + + // + // + + // Declare the controls to be used. + private BindingSource bindingSource1; + private TextBox textBox1; + private TextBox textBox2; + private DataGridView dataGridView1; + + private void InitializeControlsAndDataSource() + { + // Initialize the controls and set location, size and + // other basic properties. + this.dataGridView1 = new DataGridView(); + this.bindingSource1 = new BindingSource(); + this.textBox1 = new TextBox(); + this.textBox2 = new TextBox(); + this.dataGridView1.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Dock = DockStyle.Top; + this.dataGridView1.Location = new Point(0, 0); + this.dataGridView1.Size = new Size(292, 150); + this.textBox1.Location = new Point(132, 156); + this.textBox1.Size = new Size(100, 20); + this.textBox2.Location = new Point(12, 156); + this.textBox2.Size = new Size(100, 20); + this.ClientSize = new Size(292, 266); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.dataGridView1); + + // Declare the DataSet and add a table and column. + DataSet set1 = new DataSet(); + set1.Tables.Add("Menu"); + set1.Tables[0].Columns.Add("Beverages"); + + // Add some rows to the table. + set1.Tables[0].Rows.Add("coffee"); + set1.Tables[0].Rows.Add("tea"); + set1.Tables[0].Rows.Add("hot chocolate"); + set1.Tables[0].Rows.Add("milk"); + set1.Tables[0].Rows.Add("orange juice"); + + // Set the data source to the DataSet. + bindingSource1.DataSource = set1; + + //Set the DataMember to the Menu table. + bindingSource1.DataMember = "Menu"; + + // Add the control data bindings. + dataGridView1.DataSource = bindingSource1; + textBox1.DataBindings.Add("Text", bindingSource1, + "Beverages", true, DataSourceUpdateMode.OnPropertyChanged); + textBox2.DataBindings.Add("Text", bindingSource1, + "Beverages", true, DataSourceUpdateMode.OnPropertyChanged); + bindingSource1.BindingComplete += + new BindingCompleteEventHandler(bindingSource1_BindingComplete); + } + // + + // + private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e) + { + // Check if the data source has been updated, and that no error has occurred. + if (e.BindingCompleteContext == + BindingCompleteContext.DataSourceUpdate && e.Exception == null) + + // If not, end the current edit. + e.Binding.BindingManagerBase.EndCurrentEdit(); + } + // + + // + + // + private void InitializeControlsAndData() + { + // Initialize the controls and set location, size and + // other basic properties. + this.dataGridView1 = new DataGridView(); + + this.textBox1 = new TextBox(); + this.textBox2 = new TextBox(); + this.dataGridView1.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Dock = DockStyle.Top; + this.dataGridView1.Location = new Point(0, 0); + this.dataGridView1.Size = new Size(292, 150); + this.textBox1.Location = new Point(132, 156); + this.textBox1.Size = new Size(100, 20); + this.textBox2.Location = new Point(12, 156); + this.textBox2.Size = new Size(100, 20); + this.ClientSize = new Size(292, 266); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.dataGridView1); + + // Declare the DataSet and add a table and column. + DataSet set1 = new DataSet(); + set1.Tables.Add("Menu"); + set1.Tables[0].Columns.Add("Beverages"); + + // Add some rows to the table. + set1.Tables[0].Rows.Add("coffee"); + set1.Tables[0].Rows.Add("tea"); + set1.Tables[0].Rows.Add("hot chocolate"); + set1.Tables[0].Rows.Add("milk"); + set1.Tables[0].Rows.Add("orange juice"); + + // Add the control data bindings. + dataGridView1.DataSource = set1; + dataGridView1.DataMember = "Menu"; + textBox1.DataBindings.Add("Text", set1, + "Menu.Beverages", true, DataSourceUpdateMode.OnPropertyChanged); + textBox2.DataBindings.Add("Text", set1, + "Menu.Beverages", true, DataSourceUpdateMode.OnPropertyChanged); + + BindingManagerBase bmb = this.BindingContext[set1, "Menu"]; + bmb.BindingComplete += new BindingCompleteEventHandler(bmb_BindingComplete); + } + + private void bmb_BindingComplete(object sender, BindingCompleteEventArgs e) + { + // Check if the data source has been updated, and that no error has occurred. + if (e.BindingCompleteContext == + BindingCompleteContext.DataSourceUpdate && e.Exception == null) + + // If not, end the current edit. + e.Binding.BindingManagerBase.EndCurrentEdit(); ; + } + // + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/CS/Form1.cs new file mode 100644 index 0000000000..9c3bf01ec8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/CS/Form1.cs @@ -0,0 +1,143 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Data; + +namespace BindingSourceMultipleForms +{ + public class MainForm : Form + { + public MainForm() + { + this.Load += new EventHandler(MainForm_Load); + } + + private BindingSource bindingSource1; + private Button button1; + + private void MainForm_Load(object sender, EventArgs e) + { + InitializeData(); + } + + private void InitializeData() + { + bindingSource1 = new System.Windows.Forms.BindingSource(); + + // Handle the BindingComplete event to ensure the two forms + // remain synchronized. + bindingSource1.BindingComplete += + new BindingCompleteEventHandler(bindingSource1_BindingComplete); + ClientSize = new System.Drawing.Size(292, 266); + DataSet dataset1 = new DataSet(); + + // Some xml data to populate the DataSet with. + string musicXml = + "" + + "" + + "Dave Matthews" + + "Under the Table and Dreaming" + + "19943.5" + + "ColdplayX&Y" + + "20054" + + "Dave Matthews" + + "Live at Red Rocks" + + "19974" + + "U2" + + "Joshua Tree1987" + + "5" + + "U2" + + "How to Dismantle an Atomic Bomb" + + "20044.5" + + "Natalie Merchant" + + "Tigerlily1995" + + "3.5" + + ""; + + // Read the xml. + System.IO.StringReader reader = new System.IO.StringReader(musicXml); + dataset1.ReadXml(reader); + + // Get a DataView of the table contained in the dataset. + DataTableCollection tables = dataset1.Tables; + DataView view1 = new DataView(tables[0]); + + // Create a DataGridView control and add it to the form. + DataGridView datagridview1 = new DataGridView(); + datagridview1.ReadOnly = true; + datagridview1.AutoGenerateColumns = true; + datagridview1.Width = 300; + this.Controls.Add(datagridview1); + bindingSource1.DataSource = view1; + datagridview1.DataSource = bindingSource1; + datagridview1.Columns.Remove("artist"); + datagridview1.Columns.Remove("releaseDate"); + + // Create and add a button to the form. + button1 = new Button(); + button1.AutoSize = true; + button1.Text = "Show/Edit Details"; + this.Controls.Add(button1); + button1.Location = new Point(50, 200); + button1.Click += new EventHandler(button1_Click); + } + + // Handle the BindingComplete event to ensure the two forms + // remain synchronized. + private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e) + { + if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate + && e.Exception == null) + e.Binding.BindingManagerBase.EndCurrentEdit(); + } + + // The detailed form will be shown when the button is clicked. + private void button1_Click(object sender, EventArgs e) + { + DetailForm detailForm = new DetailForm(bindingSource1); + detailForm.Show(); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new MainForm()); + } + } + + // The detail form class. + public class DetailForm : Form + { + private BindingSource formDataSource; + + // The constructor takes a BindingSource object. + public DetailForm(BindingSource dataSource) + { + formDataSource = dataSource; + this.ClientSize = new Size(240, 200); + TextBox textBox1 = new TextBox(); + this.Text = "Selection Details"; + textBox1.Width = 220; + TextBox textBox2 = new TextBox(); + TextBox textBox3 = new TextBox(); + TextBox textBox4 = new TextBox(); + textBox4.Width = 30; + textBox3.Width = 50; + + // Associate each text box with a column from the data source. + textBox1.DataBindings.Add("Text", formDataSource, "cd", true, DataSourceUpdateMode.OnPropertyChanged); + + textBox2.DataBindings.Add("Text", formDataSource, "artist", true); + textBox3.DataBindings.Add("Text", formDataSource, "releaseDate", true); + textBox4.DataBindings.Add("Text", formDataSource, "rating", true); + textBox1.Location = new Point(10, 10); + textBox2.Location = new Point(10, 40); + textBox3.Location = new Point(10, 80); + textBox4.Location = new Point(10, 120); + this.Controls.AddRange(new Control[] { textBox1, textBox2, textBox3, textBox4 }); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/CS/Form1.cs new file mode 100644 index 0000000000..ae8c952206 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/CS/Form1.cs @@ -0,0 +1,62 @@ +// +using System; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace MouseRollBackSingleClick +{ + public class Form1 : Form + { + private DoubleClickButton button1; + private FormBorderStyle initialStyle; + + public Form1() + { + initialStyle = this.FormBorderStyle; + this.ClientSize = new System.Drawing.Size(292, 266); + button1 = new DoubleClickButton(); + button1.Location = new Point (40,40); + button1.Click += new EventHandler(button1_Click); + button1.AutoSize = true; + this.AllowDrop = true; + button1.Text = "Click or Double Click"; + button1.DoubleClick += new EventHandler(button1_DoubleClick); + this.Controls.Add(button1); + } + + // Handle the double click event. + void button1_DoubleClick(object sender, EventArgs e) + { + // Change the border style back to the initial style. + this.FormBorderStyle = initialStyle; + MessageBox.Show("Rolled back single click change."); + } + + // Handle the click event. + void button1_Click(object sender, EventArgs e) + { + this.FormBorderStyle = FormBorderStyle.FixedToolWindow; + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +// + public class DoubleClickButton : Button + { + public DoubleClickButton() : base() + { + // Set the style so a double click event occurs. + SetStyle(ControlStyles.StandardClick | + ControlStyles.StandardDoubleClick, true); + } + } +// +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/CS/Form1.cs new file mode 100644 index 0000000000..12f113460a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/CS/Form1.cs @@ -0,0 +1,227 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Windows.Forms; + +namespace UpdateBindings +{ + // + // This form demonstrates using a BindingSource to bind + // a list to a simple user control. The list does not + // raise change notifications, however the DemoCustomer type + // in the list does. In addition, an event is raised when the DataSource + // property of the user control changes. + public class Form1 : System.Windows.Forms.Form + { + // This button causes the value of a list element to be changed. + private Button changeItemBtn = new Button(); + + // This is the DataGridView control that displays the contents + // of the list. + private CustomerControl customerControl1 = new CustomerControl(); + + // This is the BindingSource used to bind the list to the control. + private BindingSource customersBindingSource = new BindingSource(); + + public Form1() + { + // Set up the "Change Item" button. + this.changeItemBtn.Text = "Change Item"; + this.changeItemBtn.Dock = DockStyle.Bottom; + this.changeItemBtn.Click += + new EventHandler(changeItemBtn_Click); + this.Controls.Add(this.changeItemBtn); + + // Set up the DataGridView. + customerControl1.Dock = DockStyle.Top; + this.Controls.Add(customerControl1); + this.Size = new Size(800, 200); + this.Load += new EventHandler(Form1_Load); + this.customerControl1.DataSourceChanged += + new EventHandler(customerControl1_DataSourceChanged); + } + private void customerControl1_DataSourceChanged(Object sender, EventArgs e) + { + MessageBox.Show("Data Source has changed"); + } + + private void Form1_Load(System.Object sender, System.EventArgs e) + { + // Create and populate the list of DemoCustomer objects + // which will supply data to the control. + List customerList = new List(); + customerList.Add(DemoCustomer.CreateNewCustomer()); + customerList.Add(DemoCustomer.CreateNewCustomer()); + customerList.Add(DemoCustomer.CreateNewCustomer()); + + // Bind the list to the BindingSource. + this.customersBindingSource.DataSource = customerList; + customerControl1.DataSource = customersBindingSource; + } + + // This event handler changes the value of the CompanyName + // property for the first item in the list. + private void changeItemBtn_Click(object sender, EventArgs e) + { + // Get a reference to the list from the BindingSource. + List customerList = + this.customersBindingSource.DataSource as List; + + // Change the value of the CompanyName property for the + // first item in the list. + customerList[0].CompanyName = "Tailspin Toys"; + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } + + // + // + // This class implements a simple user control + // that demonstrates how to apply the propertyNameChanged pattern. + [ComplexBindingProperties("DataSource", "DataMember")] + public class CustomerControl : UserControl + { + private DataGridView dataGridView1; + private Label label1; + private DateTime lastUpdate = DateTime.Now; + + public EventHandler DataSourceChanged; + + public object DataSource + { + get + { + return this.dataGridView1.DataSource; + } + set + { + if (DataSource != value) + { + this.dataGridView1.DataSource = value; + OnDataSourceChanged(); + } + } + } + + public string DataMember + { + get { return this.dataGridView1.DataMember; } + + set { this.dataGridView1.DataMember = value; } + } + + private void OnDataSourceChanged() + { + if (DataSourceChanged != null) + { + DataSourceChanged(this, new EventArgs()); + } + } + + public CustomerControl() + { + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.label1 = new System.Windows.Forms.Label(); + this.dataGridView1.ColumnHeadersHeightSizeMode = + System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.ImeMode = System.Windows.Forms.ImeMode.Disable; + this.dataGridView1.Location = new System.Drawing.Point(19, 55); + this.dataGridView1.Size = new System.Drawing.Size(350, 150); + this.dataGridView1.TabIndex = 1; + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(19, 23); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(76, 13); + this.label1.TabIndex = 2; + this.label1.Text = "Customer List:"; + this.Controls.Add(this.label1); + this.Controls.Add(this.dataGridView1); + this.Size = new System.Drawing.Size(350, 216); + } + } + // + + // + // This class implements a simple customer type + // that implements the IPropertyChange interface. + public class DemoCustomer : INotifyPropertyChanged + { + // These fields hold the values for the public properties. + private Guid idValue = Guid.NewGuid(); + private string customerName = String.Empty; + private string companyNameValue = String.Empty; + private string phoneNumberValue = String.Empty; + + public event PropertyChangedEventHandler PropertyChanged; + + private void NotifyPropertyChanged(String info) + { + if (PropertyChanged != null) + { + PropertyChanged(this, new PropertyChangedEventArgs(info)); + } + } + + // The constructor is private to enforce the factory pattern. + private DemoCustomer() + { + customerName = "no data"; + companyNameValue = "no data"; + phoneNumberValue = "no data"; + } + + // This is the public factory method. + public static DemoCustomer CreateNewCustomer() + { + return new DemoCustomer(); + } + + // This property represents an ID, suitable + // for use as a primary key in a database. + public Guid ID + { + get + { + return this.idValue; + } + } + + public string CompanyName + { + get {return this.companyNameValue;} + + set + { + if (value != this.companyNameValue) + { + this.companyNameValue = value; + NotifyPropertyChanged("CompanyName"); + } + } + } + public string PhoneNumber + { + get { return this.phoneNumberValue; } + + set + { + if (value != this.phoneNumberValue) + { + this.phoneNumberValue = value; + NotifyPropertyChanged("PhoneNumber"); + } + } + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs new file mode 100644 index 0000000000..3690bf36f5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/CS/form1.cs @@ -0,0 +1,161 @@ +using System; +using System.Windows.Forms; + +public class Form1 : Form +{ + // + [Serializable] + public class Customer + { + private string nameValue = string.Empty; + public Customer(String name) + { + nameValue = name; + } + public string Name + { + get { return nameValue; } + set { nameValue = value; } + } + } + // + + public Form1() + { + // + Clipboard.Clear(); + // + } + + // + // Demonstrates SetData, ContainsData, and GetData + // using a custom format name and a business object. + public Customer TestCustomFormat + { + get + { + Clipboard.SetData("CustomerFormat", new Customer("Customer Name")); + if (Clipboard.ContainsData("CustomerFormat")) + { + return Clipboard.GetData("CustomerFormat") as Customer; + } + return null; + } + } + // + + // + // Demonstrates how to use a DataObject to add + // data to the Clipboard in multiple formats. + public void TestClipboardMultipleFormats() + { + DataObject data = new DataObject(); + + // Add a Customer object using the type as the format. + data.SetData(new Customer("Customer as Customer object")); + + // Add a ListViewItem object using a custom format name. + data.SetData("CustomFormat", + new ListViewItem("Customer as ListViewItem")); + + Clipboard.SetDataObject(data); + DataObject retrievedData = (DataObject)Clipboard.GetDataObject(); + + if (retrievedData.GetDataPresent("CustomFormat")) + { + ListViewItem item = + retrievedData.GetData("CustomFormat") as ListViewItem; + if (item != null) + { + MessageBox.Show(item.Text); + } + } + + if (retrievedData.GetDataPresent(typeof(Customer))) + { + Customer customer = + retrievedData.GetData(typeof(Customer)) as Customer; + if (customer != null) + { + MessageBox.Show(customer.Name); + } + } + } + // + + // + // Demonstrates SetData, ContainsData, and GetData. + public Object SwapClipboardFormattedData(String format, Object data) + { + Object returnObject = null; + if (Clipboard.ContainsData(format)) + { + returnObject = Clipboard.GetData(format); + Clipboard.SetData(format, data); + } + return returnObject; + } + // + + // + // + // Demonstrates SetAudio, ContainsAudio, and GetAudioStream. + public System.IO.Stream SwapClipboardAudio( + System.IO.Stream replacementAudioStream) + { + System.IO.Stream returnAudioStream = null; + if (Clipboard.ContainsAudio()) + { + returnAudioStream = Clipboard.GetAudioStream(); + Clipboard.SetAudio(replacementAudioStream); + } + return returnAudioStream; + } + // + + // + // Demonstrates SetFileDropList, ContainsFileDroList, and GetFileDropList + public System.Collections.Specialized.StringCollection + SwapClipboardFileDropList( + System.Collections.Specialized.StringCollection replacementList) + { + System.Collections.Specialized.StringCollection returnList = null; + if (Clipboard.ContainsFileDropList()) + { + returnList = Clipboard.GetFileDropList(); + Clipboard.SetFileDropList(replacementList); + } + return returnList; + } + // + + // + // Demonstrates SetImage, ContainsImage, and GetImage. + public System.Drawing.Image SwapClipboardImage( + System.Drawing.Image replacementImage) + { + System.Drawing.Image returnImage = null; + if (Clipboard.ContainsImage()) + { + returnImage = Clipboard.GetImage(); + Clipboard.SetImage(replacementImage); + } + return returnImage; + } + // + + // + // Demonstrates SetText, ContainsText, and GetText. + public String SwapClipboardHtmlText(String replacementHtmlText) + { + String returnHtmlText = null; + if (Clipboard.ContainsText(TextDataFormat.Html)) + { + returnHtmlText = Clipboard.GetText(TextDataFormat.Html); + Clipboard.SetText(replacementHtmlText, TextDataFormat.Html); + } + return returnHtmlText; + } + // + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/CS/form1.cs new file mode 100644 index 0000000000..7324d00640 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/CS/form1.cs @@ -0,0 +1,151 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace WindowsApplication10 +{ + public class Form1 : Form + { + private ToolStripButton toolStripButton1; + private ToolStripButton toolStripButton2; + private ToolStripButton toolStripButton3; + private ContextMenuStrip contextMenuStrip1; + private IContainer components; + private ToolStripMenuItem toolStripMenuItem1; + private ToolStripMenuItem toolStripMenuItem2; + private ContextMenuStrip contextMenuStrip2; + private ToolStripMenuItem rearrangeButtonsToolStripMenuItem; + private ToolStripMenuItem selectIconsToolStripMenuItem; + private ToolStrip toolStrip1; + + public Form1() + { + InitializeComponent(); + } + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); + this.toolStrip1 = new System.Windows.Forms.ToolStrip(); + this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); + this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); + this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); + this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); + this.contextMenuStrip2 = new System.Windows.Forms.ContextMenuStrip(this.components); + this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); + this.rearrangeButtonsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.selectIconsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStrip1.SuspendLayout(); + this.contextMenuStrip1.SuspendLayout(); + this.contextMenuStrip2.SuspendLayout(); + this.SuspendLayout(); + // + // + // Associate contextMenuStrip2 with toolStrip1. + // toolStrip1 property settings follow. + // + this.toolStrip1.ContextMenuStrip = this.contextMenuStrip2; + this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripButton1, + this.toolStripButton2, + this.toolStripButton3}); + this.toolStrip1.Location = new System.Drawing.Point(0, 0); + this.toolStrip1.Name = "toolStrip1"; + this.toolStrip1.Size = new System.Drawing.Size(292, 25); + this.toolStrip1.TabIndex = 0; + this.toolStrip1.Text = "toolStrip1"; + // + // + // toolStripButton1 + // + this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); + this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButton1.Name = "toolStripButton1"; + this.toolStripButton1.Text = "toolStripButton1"; + // + // toolStripButton2 + // + this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image"))); + this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButton2.Name = "toolStripButton2"; + this.toolStripButton2.Text = "toolStripButton2"; + // + // toolStripButton3 + // + this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; + this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image"))); + this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; + this.toolStripButton3.Name = "toolStripButton3"; + this.toolStripButton3.Text = "toolStripButton3"; + // + // contextMenuStrip1 + // + this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem1, + this.toolStripMenuItem2}); + this.contextMenuStrip1.Name = "contextMenuStrip1"; + this.contextMenuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.No; + this.contextMenuStrip1.Size = new System.Drawing.Size(131, 48); + // + // contextMenuStrip2 + // + this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.rearrangeButtonsToolStripMenuItem, + this.selectIconsToolStripMenuItem}); + this.contextMenuStrip2.Name = "contextMenuStrip2"; + this.contextMenuStrip2.RightToLeft = System.Windows.Forms.RightToLeft.No; + this.contextMenuStrip2.Size = new System.Drawing.Size(162, 48); + // + // toolStripMenuItem1 + // + this.toolStripMenuItem1.Name = "toolStripMenuItem1"; + this.toolStripMenuItem1.Text = "&Resize"; + // + // toolStripMenuItem2 + // + this.toolStripMenuItem2.Name = "toolStripMenuItem2"; + this.toolStripMenuItem2.Text = "&Keep on Top"; + // + // rearrangeButtonsToolStripMenuItem + // + this.rearrangeButtonsToolStripMenuItem.Name = "rearrangeButtonsToolStripMenuItem"; + this.rearrangeButtonsToolStripMenuItem.Text = "R&earrange Buttons"; + // + // selectIconsToolStripMenuItem + // + this.selectIconsToolStripMenuItem.Name = "selectIconsToolStripMenuItem"; + this.selectIconsToolStripMenuItem.Text = "&Select Icons"; + // + // + // Associate contextMenuStrip1 with Form1. + // Form1 property settings follow. + // + this.ClientSize = new System.Drawing.Size(292, 266); + this.ContextMenuStrip = this.contextMenuStrip1; + this.Controls.Add(this.toolStrip1); + this.Name = "Form1"; + this.toolStrip1.ResumeLayout(false); + this.contextMenuStrip1.ResumeLayout(false); + this.contextMenuStrip2.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + // + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs new file mode 100644 index 0000000000..a15c592f81 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/CS/Form1.cs @@ -0,0 +1,208 @@ +// +using System; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace BT2 +{ + public class Form1 : Form + { + public Form1() + { + InitializeControlsAndDataSource(); + } + + // Declare the controls to be used. + private BindingSource bindingSource1; + private DataGridView dataGridView1; + private Button button1; + private DataGridView dataGridView2; + private CheckBox cachePositionCheckBox; + public DataSet set1; + + private void InitializeControlsAndDataSource() + { + // Initialize the controls and set location, size and + // other basic properties. + this.dataGridView1 = new DataGridView(); + this.bindingSource1 = new BindingSource(); + this.button1 = new Button(); + this.dataGridView2 = new DataGridView(); + this.cachePositionCheckBox = new System.Windows.Forms.CheckBox(); + this.dataGridView1.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Dock = DockStyle.Top; + this.dataGridView1.Location = new Point(0, 20); + this.dataGridView1.Size = new Size(292, 170); + this.button1.Location = new System.Drawing.Point(18, 175); + this.button1.Size = new System.Drawing.Size(125, 23); + + button1.Text = "Clear Parent Field"; + this.button1.Click += new System.EventHandler(this.button1_Click); + this.dataGridView2.ColumnHeadersHeightSizeMode = + System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView2.Location = new System.Drawing.Point(0, 225); + this.dataGridView2.Size = new System.Drawing.Size(309, 130); + this.cachePositionCheckBox.AutoSize = true; + this.cachePositionCheckBox.Checked = true; + this.cachePositionCheckBox.Location = new System.Drawing.Point(150, 175); + this.cachePositionCheckBox.Name = "radioButton1"; + this.cachePositionCheckBox.Size = new System.Drawing.Size(151, 17); + this.cachePositionCheckBox.Text = "Cache and restore position"; + this.ClientSize = new System.Drawing.Size(325, 420); + this.Controls.Add(this.dataGridView1); + this.Controls.Add(this.cachePositionCheckBox); + this.Controls.Add(this.dataGridView2); + this.Controls.Add(this.button1); + + // Initialize the data. + set1 = InitializeDataSet(); + + // Set the data source to the DataSet. + bindingSource1.DataSource = set1; + + //Set the DataMember to the Menu table. + bindingSource1.DataMember = "Customers"; + + // Add the control data bindings. + dataGridView1.DataSource = bindingSource1; + + // Set the data source and member for the second DataGridView. + dataGridView2.DataSource = bindingSource1; + dataGridView2.DataMember = "custOrders"; + + // Get the currency manager for the customer orders binding. + CurrencyManager relatedCM = + bindingSource1.GetRelatedCurrencyManager("custOrders"); + + // Set the position in the child table for demonstration purposes. + relatedCM.Position = 3; + + // Handle the current changed event. This event occurs when + // the current item is changed, but not when a field of the current + // item is changed. + bindingSource1.CurrentChanged += + new EventHandler(bindingSource1_CurrentChanged); + + // Handle the two events for caching and resetting the position. + relatedCM.ListChanged += new ListChangedEventHandler(relatedCM_ListChanged); + relatedCM.PositionChanged + += new EventHandler(relatedCM_PositionChanged); + + // Set cacheing to true in case current changed event + // occurred on set up. + cacheChildPosition = true; + } + + // Establish the data set with two tables and a relationship + // between them. + private DataSet InitializeDataSet() + { + set1 = new DataSet(); + // Declare the DataSet and add a table and column. + set1.Tables.Add("Customers"); + set1.Tables[0].Columns.Add("CustomerID"); + set1.Tables[0].Columns.Add("Customer Name"); + set1.Tables[0].Columns.Add("Contact Name"); + + // Add some rows to the table. + set1.Tables["Customers"].Rows.Add("c1", "Fabrikam, Inc.", "Ellen Adams"); + set1.Tables[0].Rows.Add("c2", "Lucerne Publishing", "Don Hall"); + set1.Tables[0].Rows.Add("c3", "Northwind Traders", "Lori Penor"); + set1.Tables[0].Rows.Add("c4", "Tailspin Toys", "Michael Patten"); + set1.Tables[0].Rows.Add("c5", "Woodgrove Bank", "Jyothi Pai"); + + // Declare the DataSet and add a table and column. + set1.Tables.Add("Orders"); + set1.Tables[1].Columns.Add("CustomerID"); + set1.Tables[1].Columns.Add("OrderNo"); + set1.Tables[1].Columns.Add("OrderDate"); + + // Add some rows to the table. + set1.Tables[1].Rows.Add("c1", "119", "10/04/2006"); + set1.Tables[1].Rows.Add("c1", "149", "10/10/2006"); + set1.Tables[1].Rows.Add("c1", "159", "10/12/2006"); + set1.Tables[1].Rows.Add("c2", "169", "10/10/2006"); + set1.Tables[1].Rows.Add("c2", "179", "10/10/2006"); + set1.Tables[1].Rows.Add("c2", "189", "10/12/2006"); + set1.Tables[1].Rows.Add("c3", "122", "10/04/2006"); + set1.Tables[1].Rows.Add("c4", "130", "10/10/2006"); + set1.Tables[1].Rows.Add("c5", "1.29", "10/14/2006"); + + DataRelation dr = new DataRelation("custOrders", + set1.Tables["Customers"].Columns["CustomerID"], + set1.Tables["Orders"].Columns["CustomerID"]); + set1.Relations.Add(dr); + return set1; + } + // + private int cachedPosition = -1; + private bool cacheChildPosition = true; + // + + // + void relatedCM_ListChanged(object sender, ListChangedEventArgs e) + { + // Check to see if this is a caching situation. + if (cacheChildPosition && cachePositionCheckBox.Checked) + { + // If so, check to see if it is a reset situation, and the current + // position is greater than zero. + CurrencyManager relatedCM = sender as CurrencyManager; + if (e.ListChangedType == ListChangedType.Reset && relatedCM.Position > 0) + + // If so, cache the position of the child table. + cachedPosition = relatedCM.Position; + } + } + // + // + void bindingSource1_CurrentChanged(object sender, EventArgs e) + { + // If the CurrentChanged event occurs, this is not a caching + // situation. + cacheChildPosition = false; + } + // + // + void relatedCM_PositionChanged(object sender, EventArgs e) + { + // Check to see if this is a caching situation. + if (cacheChildPosition && cachePositionCheckBox.Checked) + { + CurrencyManager relatedCM = sender as CurrencyManager; + + // If so, check to see if the current position is + // not equal to the cached position and the cached + // position is not out of bounds. + if (relatedCM.Position != cachedPosition && cachedPosition + > 0 && cachedPosition < relatedCM.Count) + { + relatedCM.Position = cachedPosition; + cachedPosition = -1; + } + } + } + // + int count = 0; + private void button1_Click(object sender, EventArgs e) + { + // For demo purposes--modifies a value in the first row of the + // parent table. + DataRow row1 = set1.Tables[0].Rows[0]; + row1[1] = DBNull.Value; + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CS/form1.cs new file mode 100644 index 0000000000..5a1d242938 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/CS/form1.cs @@ -0,0 +1,156 @@ +// +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Data.SqlClient; +using System.Windows.Forms; +// + +// +// This form demonstrates using a BindingSource to provide +// data from a collection of custom types to a DataGridView control. +public class Form1 : System.Windows.Forms.Form +{ + // + // This is the BindingSource that will provide data for + // the DataGridView control. + private BindingSource customersBindingSource = new BindingSource(); + + // This is the DataGridView control that will display our data. + private DataGridView customersDataGridView = new DataGridView(); + + // Set up the StatusBar for displaying ListChanged events. + private StatusBar status = new StatusBar(); + + // + + // + public Form1() + { + // Set up the form. + this.Size = new Size(800, 800); + this.Load += new EventHandler(Form1_Load); + this.Controls.Add(status); + + // Set up the DataGridView control. + this.customersDataGridView.Dock = DockStyle.Fill; + this.Controls.Add(customersDataGridView); + + // Attach an event handler for the AddingNew event. + this.customersBindingSource.AddingNew += + new AddingNewEventHandler(customersBindingSource_AddingNew); + + // Attach an event handler for the ListChanged event. + this.customersBindingSource.ListChanged += + new ListChangedEventHandler(customersBindingSource_ListChanged); + } + // + + // + private void Form1_Load(System.Object sender, System.EventArgs e) + { + // Add a DemoCustomer to cause a row to be displayed. + this.customersBindingSource.AddNew(); + + // Bind the BindingSource to the DataGridView + // control's DataSource. + this.customersDataGridView.DataSource = + this.customersBindingSource; + } + // + + // + // This event handler provides custom item-creation behavior. + void customersBindingSource_AddingNew( + object sender, + AddingNewEventArgs e) + { + e.NewObject = DemoCustomer.CreateNewCustomer(); + } + // + + // + // This event handler detects changes in the BindingSource + // list or changes to items within the list. + void customersBindingSource_ListChanged( + object sender, + ListChangedEventArgs e) + { + status.Text = e.ListChangedType.ToString(); + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// + +// +// This class implements a simple customer type. +public class DemoCustomer +{ + // These fields hold the values for the public properties. + private Guid idValue = Guid.NewGuid(); + private string customerName = String.Empty; + private string companyNameValue = String.Empty; + private string phoneNumberValue = String.Empty; + + // The constructor is private to enforce the factory pattern. + private DemoCustomer() + { + customerName = "no data"; + companyNameValue = "no data"; + phoneNumberValue = "no data"; + } + + // This is the public factory method. + public static DemoCustomer CreateNewCustomer() + { + return new DemoCustomer(); + } + + // This property represents an ID, suitable + // for use as a primary key in a database. + public Guid ID + { + get + { + return this.idValue; + } + } + + public string CompanyName + { + get + { + return this.companyNameValue; + } + + set + { + this.companyNameValue = value; + } + } + + public string PhoneNumber + { + get + { + return this.phoneNumberValue; + } + + set + { + this.phoneNumberValue = value; + } + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CS/form1.cs new file mode 100644 index 0000000000..cbd440adb6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/CS/form1.cs @@ -0,0 +1,128 @@ +// +// +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Common; +using System.Diagnostics; +using System.Drawing; +using System.Data.SqlClient; +using System.Windows.Forms; +// + +// +// This form demonstrates using a BindingSource to bind to a factory +// object. +public class Form1 : System.Windows.Forms.Form +{ + // + // This is the TextBox for entering CustomerID values. + private TextBox customerIdTextBox = new TextBox(); + + // This is the DataGridView that displays orders for the + // specified customer. + private DataGridView customersDataGridView = new DataGridView(); + + // This is the BindingSource for binding the database query + // result set to the DataGridView. + private BindingSource ordersBindingSource = new BindingSource(); + // + + // + public Form1() + { + // Set up the CustomerID TextBox. + this.customerIdTextBox.Location = new Point(100, 200); + this.customerIdTextBox.Size = new Size(500, 30); + this.customerIdTextBox.Text = + "Enter a valid Northwind CustomerID, for example: ALFKI," + + " then RETURN or click outside the TextBox"; + this.customerIdTextBox.Leave += + new EventHandler(customerIdTextBox_Leave); + this.customerIdTextBox.KeyDown += + new KeyEventHandler(customerIdTextBox_KeyDown); + this.Controls.Add(this.customerIdTextBox); + + // Set up the DataGridView. + customersDataGridView.Dock = DockStyle.Top; + this.Controls.Add(customersDataGridView); + + // Set up the form. + this.Size = new Size(800, 500); + this.Load += new EventHandler(Form1_Load); + } + // + + // + // This event handler binds the BindingSource to the DataGridView + // control's DataSource property. + private void Form1_Load( + System.Object sender, + System.EventArgs e) + { + // Attach the BindingSource to the DataGridView. + this.customersDataGridView.DataSource = + this.ordersBindingSource; + } + // + + // + // This is a static factory method. It queries the Northwind + // database for the orders belonging to the specified + // customer and returns an IEnumerable. + public static IEnumerable GetOrdersByCustomerId(string id) + { + // Open a connection to the database. + string connectString = "Integrated Security=SSPI;" + + "Persist Security Info=False;Initial Catalog=Northwind;" + + "Data Source= localhost"; + SqlConnection connection = new SqlConnection(); + + connection.ConnectionString = connectString; + connection.Open(); + + // Execute the query. + string queryString = + String.Format("Select * From Orders where CustomerID = '{0}'", + id); + SqlCommand command = new SqlCommand(queryString, connection); + SqlDataReader reader = + command.ExecuteReader(CommandBehavior.CloseConnection); + return reader; + } + // + + // + // These event handlers are called when the user tabs or clicks + // out of the customerIdTextBox or hits the return key. + // The database is then queried with the CustomerID + // in the customerIdTextBox.Text property. + void customerIdTextBox_Leave(object sender, EventArgs e) + { + // Attach the data source to the BindingSource control. + this.ordersBindingSource.DataSource = + GetOrdersByCustomerId(this.customerIdTextBox.Text); + } + + void customerIdTextBox_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Return) + { + // Attach the data source to the BindingSource control. + this.ordersBindingSource.DataSource = + GetOrdersByCustomerId(this.customerIdTextBox.Text); + } + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/CS/form1.cs new file mode 100644 index 0000000000..a7df47acc5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/CS/form1.cs @@ -0,0 +1,96 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +class Form1 : Form +{ + BindingSource bSource = new BindingSource(); + private Button button1; + DataGridView dgv = new DataGridView(); + + public Form1() + { + this.button1 = new System.Windows.Forms.Button(); + this.button1.Location = new System.Drawing.Point(140, 326); + this.button1.Name = "button1"; + this.button1.AutoSize = true; + this.button1.Text = "Add Customer"; + this.button1.Click += new System.EventHandler(this.button1_Click); + this.ClientSize = new System.Drawing.Size(362, 370); + this.Controls.Add(this.button1); + + // Bind the BindingSource to the DemoCustomer type. + bSource.DataSource = typeof(DemoCustomer); + + // Set up the DataGridView control. + dgv.Dock = DockStyle.Top; + this.Controls.Add(dgv); + + // Bind the DataGridView control to the BindingSource. + dgv.DataSource = bSource; + } + public static void Main() + { + Application.Run(new Form1()); + } + + private void button1_Click(object sender, EventArgs e) + { + bSource.Add(new DemoCustomer(DateTime.Today)); + } +} + +// This simple class is used to demonstrate binding to a type. +public class DemoCustomer +{ + public DemoCustomer() + { + idValue = Guid.NewGuid(); + } + + public DemoCustomer(DateTime FirstOrderDate) + { + FirstOrder = FirstOrderDate; + idValue = Guid.NewGuid(); + } + // These fields hold the data that backs the public properties. + private DateTime firstOrderDateValue; + private Guid idValue; + private string custNameValue; + + public string CustomerName + { + get { return custNameValue; } + set { custNameValue = value; } + } + + // This is a property that represents a birth date. + public DateTime FirstOrder + { + get + { + return this.firstOrderDateValue; + } + set + { + if (value != this.firstOrderDateValue) + { + this.firstOrderDateValue = value; + } + } + } + + // This is a property that represents a customer ID. + public Guid ID + { + get + { + return this.idValue; + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CS/form1.cs new file mode 100644 index 0000000000..3a29145fcb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/CS/form1.cs @@ -0,0 +1,119 @@ +// +using System; +using System.ComponentModel; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.Collections; + +namespace System_Windows_Forms_UpdateBinding +{ + class Form1 : Form + { + // Declare the objects on the form. + private Label label1; + private Label label2; + private TextBox textBox1; + private TextBox textBox2; + private Button button1; + private BindingSource bindingSource1; + ArrayList states; + + public Form1() + { + // Basic form setup. + this.button1 = new System.Windows.Forms.Button(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.button1.Location = new System.Drawing.Point(12, 18); + this.button1.Size = new System.Drawing.Size(119, 38); + this.button1.Text = "RemoveAt(0)"; + this.button1.Click += new System.EventHandler(this.button1_Click); + this.textBox1.Location = new System.Drawing.Point(55, 75); + this.textBox1.ReadOnly = true; + this.textBox1.Size = new System.Drawing.Size(119, 20); + this.label1.Location = new System.Drawing.Point(12, 110); + this.label1.Size = new System.Drawing.Size(43, 14); + this.label1.Text = "Capital:"; + this.label2.Location = new System.Drawing.Point(12, 78); + this.label2.Size = new System.Drawing.Size(34, 14); + this.label2.Text = "State:"; + this.textBox2.Location = new System.Drawing.Point(55, 110); + this.textBox2.Size = new System.Drawing.Size(119, 20); + this.textBox2.ReadOnly = true; + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.textBox2); + this.Controls.Add(this.label2); + this.Controls.Add(this.label1); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.button1); + this.Text = "Form1"; + + // Create an ArrayList containing some of the State objects. + states = new ArrayList(); + states.Add(new State("California", "Sacramento")); + states.Add(new State("Oregon", "Salem")); + states.Add(new State("Washington", "Olympia")); + states.Add(new State("Idaho", "Boise")); + states.Add(new State("Utah", "Salt Lake City")); + states.Add(new State("Hawaii", "Honolulu")); + states.Add(new State("Colorado", "Denver")); + states.Add(new State("Montana", "Helena")); + + bindingSource1 = new BindingSource(); + + // Bind BindingSource1 to the list of states. + bindingSource1.DataSource = states; + + // Bind the two text boxes to properties of State. + textBox1.DataBindings.Add("Text", bindingSource1, "Name"); + textBox2.DataBindings.Add("Text", bindingSource1, "Capital"); + } + + // + private void button1_Click(object sender, EventArgs e) + { + // If items remain in the list, remove the first item. + if (states.Count > 0) + { + states.RemoveAt(0); + + // Call ResetBindings to update the textboxes. + bindingSource1.ResetBindings(false); + } + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + // The State class to add to the ArrayList. + private class State + { + private string stateName; + public string Name + { + get {return stateName;} + } + + private string stateCapital; + public string Capital + { + get {return stateCapital;} + } + + public State ( string name, string capital) + { + stateName = name; + stateCapital = capital; + } + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CS/form1.cs new file mode 100644 index 0000000000..808e73593a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/CS/form1.cs @@ -0,0 +1,160 @@ +// +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.Common; +using System.Diagnostics; +using System.Drawing; +using System.Data.SqlClient; +using System.Windows.Forms; +// + +// +// This form demonstrates using a BindingSource to bind +// a list to a DataGridView control. The list does not +// raise change notifications, so the ResetItem method +// on the BindingSource is used. +public class Form1 : System.Windows.Forms.Form +{ + // + // This button causes the value of a list element to be changed. + private Button changeItemBtn = new Button(); + + // This is the DataGridView control that displays the contents + // of the list. + private DataGridView customersDataGridView = new DataGridView(); + + // This is the BindingSource used to bind the list to the + // DataGridView control. + private BindingSource customersBindingSource = new BindingSource(); + // + + // + public Form1() + { + // Set up the "Change Item" button. + this.changeItemBtn.Text = "Change Item"; + this.changeItemBtn.Dock = DockStyle.Bottom; + this.changeItemBtn.Click += + new EventHandler(changeItemBtn_Click); + this.Controls.Add(this.changeItemBtn); + + // Set up the DataGridView. + customersDataGridView.Dock = DockStyle.Top; + this.Controls.Add(customersDataGridView); + this.Size = new Size(800, 200); + this.Load += new EventHandler(Form1_Load); + } + // + + // + private void Form1_Load(System.Object sender, System.EventArgs e) + { + // Create and populate the list of DemoCustomer objects + // which will supply data to the DataGridView. + List customerList = new List(); + customerList.Add(DemoCustomer.CreateNewCustomer()); + customerList.Add(DemoCustomer.CreateNewCustomer()); + customerList.Add(DemoCustomer.CreateNewCustomer()); + + // Bind the list to the BindingSource. + this.customersBindingSource.DataSource = customerList; + + // Attach the BindingSource to the DataGridView. + this.customersDataGridView.DataSource = + this.customersBindingSource; + } + // + + // + // This event handler changes the value of the CompanyName + // property for the first item in the list. + void changeItemBtn_Click(object sender, EventArgs e) + { + // Get a reference to the list from the BindingSource. + List customerList = + this.customersBindingSource.DataSource as List; + + // Change the value of the CompanyName property for the + // first item in the list. + customerList[0].CompanyName = "Tailspin Toys"; + + // Call ResetItem to alert the BindingSource that the + // list has changed. + this.customersBindingSource.ResetItem(0); + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// + +// +// This class implements a simple customer type. +public class DemoCustomer +{ + // These fields hold the values for the public properties. + private Guid idValue = Guid.NewGuid(); + private string customerName = String.Empty; + private string companyNameValue = String.Empty; + private string phoneNumberValue = String.Empty; + + // The constructor is private to enforce the factory pattern. + private DemoCustomer() + { + customerName = "no data"; + companyNameValue = "no data"; + phoneNumberValue = "no data"; + } + + // This is the public factory method. + public static DemoCustomer CreateNewCustomer() + { + return new DemoCustomer(); + } + + // This property represents an ID, suitable + // for use as a primary key in a database. + public Guid ID + { + get + { + return this.idValue; + } + } + + public string CompanyName + { + get + { + return this.companyNameValue; + } + + set + { + this.companyNameValue = value; + } + } + + public string PhoneNumber + { + get + { + return this.phoneNumberValue; + } + + set + { + this.phoneNumberValue = value; + } + } +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CS/form1.cs new file mode 100644 index 0000000000..330cc241ff --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/CS/form1.cs @@ -0,0 +1,137 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +class Form1 : Form +{ + private BindingSource BindingSource1 = new BindingSource(); + private TextBox textBox1 = new TextBox(); + private TextBox textBox2 = new TextBox(); + private TextBox textBox3 = new TextBox(); + + public Form1() + { + //Set up the textbox controls. + this.textBox1.Location = new System.Drawing.Point(82, 13); + this.textBox1.TabIndex = 1; + this.textBox2.Location = new System.Drawing.Point(81, 47); + this.textBox2.TabIndex = 2; + this.textBox3.Location = new System.Drawing.Point(81, 83); + this.textBox3.TabIndex = 3; + + // Add the textbox controls to the form + this.Controls.Add(this.textBox2); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.textBox3); + + // Handle the form's Load event. + this.Load += new System.EventHandler(this.Form1_Load); + } + Binding partNameBinding; + Binding partNumberBinding; + + // + private void Form1_Load(object sender, EventArgs e) + { + // Set the DataSource of BindingSource1 to the Part type. + BindingSource1.DataSource = typeof(Part); + + // Bind the textboxes to the properties of the Part type, + // enabling formatting. + partNameBinding = textBox1.DataBindings.Add("Text", + BindingSource1, "PartName", true); + + partNumberBinding = textBox2.DataBindings.Add("Text", BindingSource1, "PartNumber", + true); + + //Bind the textbox to the PartPrice value with currency formatting. + textBox3.DataBindings.Add("Text", BindingSource1, "PartPrice", true, + DataSourceUpdateMode.OnPropertyChanged, 0, "C"); + + // Handle the BindingComplete event for BindingSource1 and + // the partNameBinding. + partNumberBinding.BindingComplete += + new BindingCompleteEventHandler(partNumberBinding_BindingComplete); + partNameBinding.BindingComplete += + new BindingCompleteEventHandler(partNameBinding_BindingComplete); + + // Add a new part to BindingSource1. + BindingSource1.Add(new Part("Widget", 1234, 12.45)); + } + + // Handle the BindingComplete event to catch errors and exceptions + // in binding process. + void partNumberBinding_BindingComplete(object sender, + BindingCompleteEventArgs e) + { + if (e.BindingCompleteState != BindingCompleteState.Success) + MessageBox.Show("partNumberBinding: " + e.ErrorText); + } + + // Handle the BindingComplete event to catch errors and + // exceptions in binding process. + void partNameBinding_BindingComplete(object sender, + BindingCompleteEventArgs e) + { + if (e.BindingCompleteState != BindingCompleteState.Success) + MessageBox.Show("partNameBinding: " + e.ErrorText); + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} + +// +// Represents a business object that throws exceptions when invalid values are +// entered for some of its properties. +public class Part +{ + private string name; + private int number; + private double price; + + public Part(string name, int number, double price) + { + PartName = name; + PartNumber = number; + PartPrice = price; + } + + public string PartName + { + get { return name; } + set + { + if (value.Length <= 0) + throw new Exception("Each part must have a name."); + else + name = value; + } + } + public double PartPrice + { + get { return price; } + set { price = value; } + } + + public int PartNumber + { + get { return number; } + set + { + if (value < 100) + throw new Exception("Invalid part number." + + " Part numbers must be greater than 100."); + else + number = value; + } + } +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/CS/form1.cs new file mode 100644 index 0000000000..7ee2464ae7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/CS/form1.cs @@ -0,0 +1,185 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.SqlClient; +using System.Drawing; +using System.Windows.Forms; + +#endregion + +namespace FilterAndSort +{ + class Form1 : Form + { + + private BindingSource BindingSource1; + private DataGridView dataGridView1; + private Button button1; + private Label label1; + private Label label2; + + private IContainer components; + + public Form1() + { + InitializeComponent(); + this.Load += new EventHandler(Form1_Load); + } + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.BindingSource1 = new System.Windows.Forms.BindingSource(this.components); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.button1 = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.BindingSource1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + this.SuspendLayout(); + // + // dataGridView1 + // + this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Bottom; + this.dataGridView1.Location = new System.Drawing.Point(0, 100); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.Size = new System.Drawing.Size(292, 166); + this.dataGridView1.TabIndex = 0; + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 39); + this.button1.Name = "button1"; + this.button1.TabIndex = 1; + this.button1.Text = "button1"; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(112, 48); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(35, 14); + this.label1.TabIndex = 3; + this.label1.Text = "label1"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(112, 67); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(35, 14); + this.label2.TabIndex = 4; + this.label2.Text = "label2"; + // + // Form1 + // + + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.label2); + this.Controls.Add(this.label1); + this.Controls.Add(this.button1); + this.Controls.Add(this.dataGridView1); + this.Name = "Form1"; + ((System.ComponentModel.ISupportInitialize)(this.BindingSource1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + void Form1_Load(object sender, EventArgs e) + { + InitializeSortedFilteredBindingSource(); + } + // The following code example demonstrates BindingSource.Filter and + // BindingSource.Sort members. + + // To run this example paste the code into a form that contains a + // BindingSource named BindingSource1 and a DataGridView named + // dataGridView1. Handle the form's load event and call + // InitializeSortedFilteredBindingSource in the load event-handling + // method. + // + private void InitializeSortedFilteredBindingSource() + { + // Create the connection string, data adapter and data table. + SqlConnection connectionString = + new SqlConnection("Initial Catalog=Northwind;" + + "Data Source=localhost;Integrated Security=SSPI;"); + SqlDataAdapter customersTableAdapter = + new SqlDataAdapter("Select * from Customers", connectionString); + DataTable customerTable = new DataTable(); + + // Fill the adapter with the contents of the customer table. + customersTableAdapter.Fill(customerTable); + + // Set data source for BindingSource1. + BindingSource1.DataSource = customerTable; + + // Filter the items to show contacts who are owners. + // + BindingSource1.Filter = "ContactTitle='Owner'"; + // + + // Sort the items on the company name in descending order. + // + BindingSource1.Sort = "Country DESC, Address ASC"; + // + + // Set the data source for dataGridView1 to BindingSource1. + dataGridView1.DataSource = BindingSource1; + } + // + + // The following code example demonstrates BindingSource.Items, + // BindingSource.List, BindingSource.RemoveAt, BindingSource.Count + // BindingSourceItemCollection.Count. + + // To run this example paste the code into a form that contains a + // BindingSource named BindingSource1, two labels named label1 and label2 + // and a button named button1. Associate the button1_Click + // method with the click event for button1. + + // + private void button1_Click(object sender, EventArgs e) + { + // Create the connection string, data adapter and data table. + SqlConnection connectionString = + new SqlConnection("Initial Catalog=Northwind;" + + "Data Source=localhost;Integrated Security=SSPI;"); + SqlDataAdapter customersTableAdapter = + new SqlDataAdapter("Select * from Customers", connectionString); + DataTable customerTable = new DataTable(); + + // Fill the adapter with the contents of the customer table. + customersTableAdapter.Fill(customerTable); + + // Set data source for BindingSource1. + BindingSource1.DataSource = customerTable; + + // Set the label text to the number of items in the collection before + // an item is removed. + label1.Text = "Starting count: " + BindingSource1.Count.ToString(); + + // Access the List property and remove an item. + BindingSource1.List.RemoveAt(4); + + // Remove an item directly from the BindingSource. + // This is equivalent to the previous line of code. + BindingSource1.RemoveAt(4); + + // Show the new count. + label2.Text = "Count after removal: " + BindingSource1.Count.ToString(); + } + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs new file mode 100644 index 0000000000..315d9882e3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/CS/form1.cs @@ -0,0 +1,206 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace BindToWebService { + class Form1: Form + + { + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private BindingSource BindingSource1 = new BindingSource(); + private TextBox textBox1 = new TextBox(); + private TextBox textBox2 = new TextBox(); + private Button button1 = new Button(); + + public Form1() + { + this.Load += new EventHandler(Form1_Load); + textBox1.Location = new System.Drawing.Point(118, 131); + textBox1.ReadOnly = true; + button1.Location = new System.Drawing.Point(133, 60); + button1.Click += new EventHandler(button1_Click); + button1.Text = "Get zipcode"; + ClientSize = new System.Drawing.Size(292, 266); + Controls.Add(this.button1); + Controls.Add(this.textBox1); + } + + private void button1_Click(object sender, EventArgs e) + { + + textBox1.Text = "Calling Web service.."; + ZipCodeResolver resolver = new ZipCodeResolver(); + BindingSource1.Add(resolver.CorrectedAddressXml("0", + "One Microsoft Way", "Redmond", "WA")); + } + + public void Form1_Load(object sender, EventArgs e) + { + // + BindingSource1.DataSource = typeof(USPSAddress); + // + // + textBox1.DataBindings.Add("Text", this.BindingSource1, "FullZIP", true); + // + } + } + + [System.Web.Services.WebServiceBindingAttribute(Name="ZipCodeResolverSoap", + Namespace="http://webservices.eraserver.net/")] + public class ZipCodeResolver: + System.Web.Services.Protocols.SoapHttpClientProtocol + + { + + public ZipCodeResolver() : base() + { + this.Url = + "http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx"; + } + + //'' + [System.Web.Services.Protocols.SoapDocumentMethodAttribute + ("http://webservices.eraserver.net/CorrectedAddressXml", + RequestNamespace="http://webservices.eraserver.net/", + ResponseNamespace="http://webservices.eraserver.net/", + Use=System.Web.Services.Description.SoapBindingUse.Literal, + ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public USPSAddress CorrectedAddressXml(string accessCode, + string address, string city, string state) + { + object[] results = this.Invoke("CorrectedAddressXml", + new object[]{accessCode, address, city, state}); + return ((USPSAddress) results[0]); + } + + //'' + public System.IAsyncResult BeginCorrectedAddressXml(string accessCode, + string address, string city, string state, + System.AsyncCallback callback, object asyncState) + { + + return this.BeginInvoke("CorrectedAddressXml", + new object[]{accessCode, address, city, state}, callback, asyncState); + } + + public USPSAddress EndCorrectedAddressXml(System.IAsyncResult asyncResult) + { + object[] results = this.EndInvoke(asyncResult); + return ((USPSAddress) results[0]); + } + } + +// + [System.SerializableAttribute, System.Xml.Serialization.XmlTypeAttribute( + Namespace="http://webservices.eraserver.net/")] + public class USPSAddress + { + + private string streetField; + + private string cityField; + + private string stateField; + + private string shortZIPField; + + private string fullZIPField; + + public string Street + { + get + { + return this.streetField; + } + set + { + this.streetField = value; + } + } + + public string City + { + get + { + return this.cityField; + } + set + { + this.cityField = value; + } + } + + public string State + { + get + { + return this.stateField; + } + set + { + this.stateField = value; + } + } + + public string ShortZIP + { + get + { + return this.shortZIPField; + } + set + { + this.shortZIPField = value; + } + } + + public string FullZIP + { + get + { + return this.fullZIPField; + } + set + { + this.fullZIPField = value; + } + } + } +// + + public delegate void CorrectedAddressXmlCompletedEventHandler(object sender, + CorrectedAddressXmlCompletedEventArgs args); + + public class CorrectedAddressXmlCompletedEventArgs: + System.ComponentModel.AsyncCompletedEventArgs + + { + private object[] results; + + internal CorrectedAddressXmlCompletedEventArgs(object[] results, + System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) + { + this.results = results; + } + + public USPSAddress Result + { + get + { + this.RaiseExceptionIfNecessary(); + return ((USPSAddress) this.results[0]); + } + } + } + } +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CS/autosizing.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CS/autosizing.cs new file mode 100644 index 0000000000..f80c0069a9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/CS/autosizing.cs @@ -0,0 +1,336 @@ +// +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +public class AutoSizing : System.Windows.Forms.Form +{ + private FlowLayoutPanel flowLayoutPanel1; + private Button button1 = new Button(); + private Button button2 = new Button(); + private Button button3 = new Button(); + private Button button4 = new Button(); + private Button button5 = new Button(); + private Button button6 = new Button(); + private Button button7 = new Button(); + private Button button8 = new Button(); + private Button button9 = new Button(); + private Button button10 = new Button(); + private Button button11 = new Button(); + private DataGridView dataGridView1; + + public AutoSizing() + { + InitializeComponent(); + this.Load += new EventHandler(InitializeDataGridView); + + AddDirections(); + AddButton(button1, "Reset", + new EventHandler(ResetToDisorder)); + AddButton(button2, "Change Column 3 Header", + new EventHandler(ChangeColumn3Header)); + AddButton(button3, "Change Meatloaf Recipe", + new EventHandler(ChangeMeatloafRecipe)); + AddButton(button4, "Change Restaurant 2", + new EventHandler(ChangeRestaurant)); + AddButtonsForAutomaticResizing(); + } + + private void AddDirections() + { + Label directions = new Label(); + directions.AutoSize = true; + String newLine = Environment.NewLine; + directions.Text = "Press the buttons that start " + newLine + + "with 'Change' to see how different sizing " + newLine + + "modes deal with content changes."; + + flowLayoutPanel1.Controls.Add(directions); + } + + private void InitializeComponent() + { + flowLayoutPanel1 = new FlowLayoutPanel(); + flowLayoutPanel1.FlowDirection = FlowDirection.TopDown; + flowLayoutPanel1.Location = new System.Drawing.Point(492, 0); + flowLayoutPanel1.AutoSize = true; + flowLayoutPanel1.TabIndex = 1; + + ClientSize = new System.Drawing.Size(674, 419); + Controls.Add(flowLayoutPanel1); + Text = this.GetType().Name; + AutoSize = true; + } + + [STAThreadAttribute()] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new AutoSizing()); + } + + private Size startingSize; + private string thirdColumnHeader = "Main Ingredients"; + private string boringMeatloaf = "ground beef"; + private string boringMeatloafRanking = "*"; + private bool boringRecipe; + private bool shortMode; + private string otherRestaurant = "Gomes's Saharan Sushi"; + + private void InitializeDataGridView(Object ignored, + EventArgs ignoredToo) + { + dataGridView1 = new System.Windows.Forms.DataGridView(); + Controls.Add(dataGridView1); + startingSize = new Size(450, 400); + dataGridView1.Size = startingSize; + dataGridView1.AutoSizeRowsModeChanged += + new DataGridViewAutoSizeModeEventHandler + (WatchRowsModeChanges); + AddLabels(); + + SetUpColumns(); + PopulateRows(); + + shortMode = false; + boringRecipe = true; + } + + private void SetUpColumns() + { + dataGridView1.ColumnCount = 4; + dataGridView1.ColumnHeadersVisible = true; + + DataGridViewCellStyle columnHeaderStyle = + new DataGridViewCellStyle(); + + columnHeaderStyle.BackColor = Color.Aqua; + columnHeaderStyle.Font = new Font("Verdana", 10, + FontStyle.Bold); + dataGridView1.ColumnHeadersDefaultCellStyle = + columnHeaderStyle; + + dataGridView1.Columns[0].Name = "Recipe"; + dataGridView1.Columns[1].Name = "Category"; + dataGridView1.Columns[2].Name = thirdColumnHeader; + dataGridView1.Columns[3].Name = "Rating"; + } + + private void PopulateRows() + { + string[] row1 = { + "Meatloaf", "Main Dish", boringMeatloaf, boringMeatloafRanking + }; + string[] row2 = { + "Key Lime Pie", "Dessert", "lime juice, evaporated milk", "****" + }; + string[] row3 = { + "Orange-Salsa Pork Chops", "Main Dish", + "pork chops, salsa, orange juice", "****" + }; + string[] row4 = { + "Black Bean and Rice Salad", "Salad", + "black beans, brown rice", "****" + }; + string[] row5 = { + "Chocolate Cheesecake", "Dessert", "cream cheese", "***" + }; + string[] row6 = { + "Black Bean Dip", "Appetizer", "black beans, sour cream", "***" + }; + object[] rows = new object[] { + row1, row2, row3, row4, row5, row6 + }; + + foreach (string[] row in rows) + dataGridView1.Rows.Add(row); + + foreach (DataGridViewRow row in dataGridView1.Rows) + { + if (row.IsNewRow) break; + row.HeaderCell.Value = "Restaurant " + row.Index; + } + } + + private void AddButton(Button button, string buttonLabel, + EventHandler handler) + { + button.Click += handler; + button.Text = buttonLabel; + button.AutoSize = true; + button.TabIndex = flowLayoutPanel1.Controls.Count; + flowLayoutPanel1.Controls.Add(button); + } + + private void ResetToDisorder(Object sender, EventArgs e) + { + Controls.Remove(dataGridView1); + dataGridView1.Dispose(); + InitializeDataGridView(null, null); + } + + private void ChangeColumn3Header(Object sender, EventArgs e) + { + Toggle(ref shortMode); + if (shortMode) dataGridView1.Columns[2].HeaderText = "S"; + else + dataGridView1.Columns[2].HeaderText = thirdColumnHeader; + } + + private static Boolean Toggle(ref Boolean toggleThis) + { + toggleThis = !toggleThis; + return toggleThis; + } + + private void ChangeMeatloafRecipe(Object sender, EventArgs e) + { + Toggle(ref boringRecipe); + if (boringRecipe) + { + SetMeatloaf(boringMeatloaf, boringMeatloafRanking); + } + else + { + string greatMeatloafRecipe = "1 lb. lean ground beef, " + + "1/2 cup bread crumbs, 1/4 cup ketchup," + + "1/3 tsp onion powder, " + + "1 clove of garlic, 1/2 pack onion soup mix," + + " dash of your favorite BBQ Sauce"; + + SetMeatloaf(greatMeatloafRecipe, "***"); + } + } + + private void ChangeRestaurant(Object sender, EventArgs ignored) + { + if (dataGridView1.Rows[2].HeaderCell.Value.ToString() == + otherRestaurant) + dataGridView1.Rows[2].HeaderCell.Value = + "Restaurant 2"; + else + dataGridView1.Rows[2].HeaderCell.Value = + otherRestaurant; + } + + private void SetMeatloaf(string recipe, string rating) + { + dataGridView1.Rows[0].Cells[2].Value = recipe; + dataGridView1.Rows[0].Cells[3].Value = rating; + } + + private string currentLayoutName = + "DataGridView.AutoSizeRowsMode is currently: "; + private void AddLabels() + { + Label current = (Label) + flowLayoutPanel1.Controls[currentLayoutName]; + if (current == null) + { + current = new Label(); + current.AutoSize = true; + current.Name = currentLayoutName; + current.Text = currentLayoutName + + dataGridView1.AutoSizeRowsMode.ToString(); + flowLayoutPanel1.Controls.Add(current); + } + } + + #region "Automatic Resizing" + private void AddButtonsForAutomaticResizing() + { + AddButton(button5, "Keep Column Headers Sized", + new EventHandler(ColumnHeadersHeightSizeMode)); + AddButton(button6, "Keep Row Headers Sized", + new EventHandler(RowHeadersWidthSizeMode)); + AddButton(button7, "Keep Rows Sized", + new EventHandler(AutoSizeRowsMode)); + AddButton(button8, "Keep Row Headers Sized with RowsMode", + new EventHandler(AutoSizeRowHeadersUsingAllHeadersMode)); + AddButton(button9, "Disable AutoSizeRowsMode", + new EventHandler(DisableAutoSizeRowsMode)); + AddButton(button10, "AutoSize third column by rows", + new EventHandler(AutoSizeOneColumn)); + AddButton(button11, "AutoSize third column by rows and headers", + new EventHandler(AutoSizeOneColumnIncludingHeaders)); + } + + // + private void ColumnHeadersHeightSizeMode(Object sender, EventArgs e) + { + dataGridView1.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + } + // + + // + private void RowHeadersWidthSizeMode(Object sender, EventArgs e) + { + dataGridView1.RowHeadersWidthSizeMode = + DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders; + } + // + + // + private void AutoSizeRowsMode(Object sender, EventArgs es) + { + dataGridView1.AutoSizeRowsMode = + DataGridViewAutoSizeRowsMode.AllCells; + } + // + + private void AutoSizeRowHeadersUsingAllHeadersMode( + Object sender, System.EventArgs e) + { + dataGridView1.AutoSizeRowsMode = + DataGridViewAutoSizeRowsMode.AllHeaders; + } + + // + private void WatchRowsModeChanges(object sender, + DataGridViewAutoSizeModeEventArgs modeEvent) + { + Label label = + (Label)flowLayoutPanel1.Controls[currentLayoutName]; + + if (modeEvent.PreviousModeAutoSized) + { + label.Text = "changed to a different " + + label.Name + + dataGridView1.AutoSizeRowsMode.ToString(); + } + else + { + label.Text = label.Name + + dataGridView1.AutoSizeRowsMode.ToString(); + } + } + // + + private void DisableAutoSizeRowsMode(object sender, + EventArgs modeEvent) + { + dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None; + } + + // + private void AutoSizeOneColumn(object sender, + EventArgs theEvent) + { + DataGridViewColumn column = dataGridView1.Columns[2]; + column.AutoSizeMode = + DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader; + } + // + + private void AutoSizeOneColumnIncludingHeaders( + object sender, EventArgs theEvent) + { + DataGridViewColumn column = dataGridView1.Columns[2]; + column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; + } + #endregion +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewBandDemo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewBandDemo.cs new file mode 100644 index 0000000000..16e2462cf5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewBandDemo.cs @@ -0,0 +1,293 @@ +// +using System.Drawing; +using System.Windows.Forms; +using System; + +public class DataGridViewBandDemo : Form +{ + #region "form setup" + public DataGridViewBandDemo() + { + InitializeComponent(); + + AddButton(Button1, "Reset", + new EventHandler(Button1_Click)); + AddButton(Button2, "Change Column 3 Header", + new EventHandler(Button2_Click)); + AddButton(Button3, "Change Meatloaf Recipe", + new EventHandler(Button3_Click)); + AddAdditionalButtons(); + + InitializeDataGridView(); + } + + DataGridView dataGridView; + Button Button1 = new Button(); + Button Button2 = new Button(); + Button Button3 = new Button(); + Button Button4 = new Button(); + Button Button5 = new Button(); + Button Button6 = new Button(); + Button Button7 = new Button(); + Button Button8 = new Button(); + Button Button9 = new Button(); + Button Button10 = new Button(); + FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel(); + + private void InitializeComponent() + { + FlowLayoutPanel1.Location = new Point(454, 0); + FlowLayoutPanel1.AutoSize = true; + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; + AutoSize = true; + ClientSize = new System.Drawing.Size(614, 360); + FlowLayoutPanel1.Name = "flowlayoutpanel"; + Controls.Add(this.FlowLayoutPanel1); + Text = this.GetType().Name; + } + #endregion + + #region "setup DataGridView" + + private string thirdColumnHeader = "Main Ingredients"; + private string boringMeatloaf = "ground beef"; + private string boringMeatloafRanking = "*"; + private bool boringRecipe; + private bool shortMode; + + private void InitializeDataGridView() + { + dataGridView = new System.Windows.Forms.DataGridView(); + Controls.Add(dataGridView); + dataGridView.Size = new Size(300, 200); + + // Create an unbound DataGridView by declaring a + // column count. + dataGridView.ColumnCount = 4; + AdjustDataGridViewSizing(); + + // Set the column header style. + DataGridViewCellStyle columnHeaderStyle = + new DataGridViewCellStyle(); + columnHeaderStyle.BackColor = Color.Aqua; + columnHeaderStyle.Font = + new Font("Verdana", 10, FontStyle.Bold); + dataGridView.ColumnHeadersDefaultCellStyle = + columnHeaderStyle; + + // Set the column header names. + dataGridView.Columns[0].Name = "Recipe"; + dataGridView.Columns[1].Name = "Category"; + dataGridView.Columns[2].Name = thirdColumnHeader; + dataGridView.Columns[3].Name = "Rating"; + + // Populate the rows. + string[] row1 = new string[]{"Meatloaf", + "Main Dish", boringMeatloaf, boringMeatloafRanking}; + string[] row2 = new string[]{"Key Lime Pie", + "Dessert", "lime juice, evaporated milk", "****"}; + string[] row3 = new string[]{"Orange-Salsa Pork Chops", + "Main Dish", "pork chops, salsa, orange juice", "****"}; + string[] row4 = new string[]{"Black Bean and Rice Salad", + "Salad", "black beans, brown rice", "****"}; + string[] row5 = new string[]{"Chocolate Cheesecake", + "Dessert", "cream cheese", "***"}; + string[] row6 = new string[]{"Black Bean Dip", "Appetizer", + "black beans, sour cream", "***"}; + object[] rows = new object[] { row1, row2, row3, row4, row5, row6 }; + + foreach (string[] rowArray in rows) + { + dataGridView.Rows.Add(rowArray); + } + + PostRowCreation(); + + shortMode = false; + boringRecipe = true; + } + + void AddButton(Button button, string buttonLabel, + EventHandler handler) + { + FlowLayoutPanel1.Controls.Add(button); + button.TabIndex = FlowLayoutPanel1.Controls.Count; + button.Text = buttonLabel; + button.AutoSize = true; + button.Click += handler; + } + + // Reset columns to initial disorderly arrangement. + private void Button1_Click(object sender, System.EventArgs e) + { + Controls.Remove(dataGridView); + dataGridView.Dispose(); + InitializeDataGridView(); + } + + // Change the header in column three. + private void Button2_Click(object sender, + System.EventArgs e) + { + Toggle(ref shortMode); + if (shortMode) + { dataGridView.Columns[2].HeaderText = "S"; } + else + { dataGridView.Columns[2].HeaderText = thirdColumnHeader; } + } + + private static void Toggle(ref bool toggleThis) + { + toggleThis = !toggleThis; + } + + // Change the meatloaf recipe. + private void Button3_Click(object sender, + System.EventArgs e) + { + Toggle(ref boringRecipe); + if (boringRecipe) + { + SetMeatloaf(boringMeatloaf, boringMeatloafRanking); + } + else + { + string greatMeatloafRecipe = + "1 lb. lean ground beef, " + + "1/2 cup bread crumbs, 1/4 cup ketchup," + + "1/3 tsp onion powder, " + + "1 clove of garlic, 1/2 pack onion soup mix " + + " dash of your favorite BBQ Sauce"; + SetMeatloaf(greatMeatloafRecipe, "***"); + } + } + + private void SetMeatloaf(string recipe, string rating) + { + dataGridView.Rows[0].Cells[2].Value = recipe; + dataGridView.Rows[0].Cells[3].Value = rating; + } + #endregion + + #region "demonstration code" + private void AddAdditionalButtons() + { + AddButton(Button4, "Freeze First Row", + new EventHandler(Button4_Click)); + AddButton(Button5, "Freeze Second Column", + new EventHandler(Button5_Click)); + AddButton(Button6, "Hide Salad Row", + new EventHandler(Button6_Click)); + AddButton(Button7, "Disable First Column Resizing", + new EventHandler(Button7_Click)); + AddButton(Button8, "Make ReadOnly", + new EventHandler(Button8_Click)); + AddButton(Button9, "Style Using Tag", + new EventHandler(Button9_Click)); + } + + private void AdjustDataGridViewSizing() + { + dataGridView.AutoSizeRowsMode = + DataGridViewAutoSizeRowsMode.AllCells; + dataGridView.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + } + + // + // Freeze the first row. + private void Button4_Click(object sender, System.EventArgs e) + { + + FreezeBand(dataGridView.Rows[0]); + } + + private void Button5_Click(object sender, System.EventArgs e) + { + + FreezeBand(dataGridView.Columns[1]); + } + + private static void FreezeBand(DataGridViewBand band) + { + band.Frozen = true; + DataGridViewCellStyle style = new DataGridViewCellStyle(); + style.BackColor = Color.WhiteSmoke; + band.DefaultCellStyle = style; + } + // + + // + // Hide a band of cells. + private void Button6_Click(object sender, System.EventArgs e) + { + + DataGridViewBand band = dataGridView.Rows[3]; + band.Visible = false; + } + // + + // + // Turn off user's ability to resize a column. + private void Button7_Click(object sender, EventArgs e) + { + + DataGridViewBand band = dataGridView.Columns[0]; + band.Resizable = DataGridViewTriState.False; + } + // + + // + // Make the entire DataGridView read only. + private void Button8_Click(object sender, System.EventArgs e) + { + foreach (DataGridViewBand band in dataGridView.Columns) + { + band.ReadOnly = true; + } + } + // + + // + private void PostRowCreation() + { + SetBandColor(dataGridView.Columns[0], Color.CadetBlue); + SetBandColor(dataGridView.Rows[1], Color.Coral); + SetBandColor(dataGridView.Columns[2], Color.DodgerBlue); + } + + private static void SetBandColor(DataGridViewBand band, Color color) + { + band.Tag = color; + } + + // Color the bands by the value stored in their tag. + private void Button9_Click(object sender, System.EventArgs e) + { + + foreach (DataGridViewBand band in dataGridView.Columns) + { + if (band.Tag != null) + { + band.DefaultCellStyle.BackColor = (Color)band.Tag; + } + } + + foreach (DataGridViewBand band in dataGridView.Rows) + { + if (band.Tag != null) + { + band.DefaultCellStyle.BackColor = (Color)band.Tag; + } + } + } + // + #endregion + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new DataGridViewBandDemo()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewColumnDemo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewColumnDemo.cs new file mode 100644 index 0000000000..bb08f1c8d0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewColumnDemo.cs @@ -0,0 +1,427 @@ +// +using System.Windows.Forms; +using System; +using System.Drawing; + +public class DataGridViewColumnDemo : Form +{ + #region "set up form" + public DataGridViewColumnDemo() + { + InitializeComponent(); + + AddButton(Button1, "Reset", + new EventHandler(ResetToDisorder)); + AddButton(Button2, "Change Column 3 Header", + new EventHandler(ChangeColumn3Header)); + AddButton(Button3, "Change Meatloaf Recipe", + new EventHandler(ChangeMeatloafRecipe)); + AddAdditionalButtons(); + + InitializeDataGridView(); + } + + DataGridView dataGridView; + Button Button1 = new Button(); + Button Button2 = new Button(); + Button Button3 = new Button(); + Button Button4 = new Button(); + Button Button5 = new Button(); + Button Button6 = new Button(); + Button Button7 = new Button(); + Button Button8 = new Button(); + Button Button9 = new Button(); + Button Button10 = new Button(); + FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel(); + + private void InitializeComponent() + { + FlowLayoutPanel1.Location = new Point(454, 0); + FlowLayoutPanel1.AutoSize = true; + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; + FlowLayoutPanel1.Name = "flowlayoutpanel"; + ClientSize = new System.Drawing.Size(614, 360); + Controls.Add(this.FlowLayoutPanel1); + Text = this.GetType().Name; + AutoSize = true; + } + #endregion + + #region "set up DataGridView" + + private string thirdColumnHeader = "Main Ingredients"; + private string boringMeatloaf = "ground beef"; + private string boringMeatloafRanking = "*"; + private bool boringRecipe; + private bool shortMode; + + private void InitializeDataGridView() + { + dataGridView = new System.Windows.Forms.DataGridView(); + Controls.Add(dataGridView); + dataGridView.Size = new Size(300, 200); + + // Create an unbound DataGridView by declaring a + // column count. + dataGridView.ColumnCount = 4; + AdjustDataGridViewSizing(); + + // Set the column header style. + DataGridViewCellStyle columnHeaderStyle = + new DataGridViewCellStyle(); + columnHeaderStyle.BackColor = Color.Aqua; + columnHeaderStyle.Font = + new Font("Verdana", 10, FontStyle.Bold); + dataGridView.ColumnHeadersDefaultCellStyle = + columnHeaderStyle; + + // Set the column header names. + dataGridView.Columns[0].Name = "Recipe"; + dataGridView.Columns[1].Name = "Category"; + dataGridView.Columns[2].Name = thirdColumnHeader; + dataGridView.Columns[3].Name = "Rating"; + + PostColumnCreation(); + + // Populate the rows. + string[] row1 = new string[]{"Meatloaf", + "Main Dish", boringMeatloaf, boringMeatloafRanking}; + string[] row2 = new string[]{"Key Lime Pie", + "Dessert", "lime juice, evaporated milk", "****"}; + string[] row3 = new string[]{"Orange-Salsa Pork Chops", + "Main Dish", "pork chops, salsa, orange juice", "****"}; + string[] row4 = new string[]{"Black Bean and Rice Salad", + "Salad", "black beans, brown rice", "****"}; + string[] row5 = new string[]{"Chocolate Cheesecake", + "Dessert", "cream cheese", "***"}; + string[] row6 = new string[]{"Black Bean Dip", "Appetizer", + "black beans, sour cream", "***"}; + object[] rows = new object[] { row1, row2, row3, row4, row5, row6 }; + + foreach (string[] rowArray in rows) + { + dataGridView.Rows.Add(rowArray); + } + + shortMode = false; + boringRecipe = true; + } + + private void AddButton(Button button, string buttonLabel, + EventHandler handler) + { + FlowLayoutPanel1.Controls.Add(button); + button.TabIndex = FlowLayoutPanel1.Controls.Count; + button.Text = buttonLabel; + button.AutoSize = true; + button.Click += handler; + } + + private void ResetToDisorder(object sender, System.EventArgs e) + { + Controls.Remove(dataGridView); + dataGridView.Dispose(); + InitializeDataGridView(); + } + + private void ChangeColumn3Header(object sender, + System.EventArgs e) + { + Toggle(ref shortMode); + if (shortMode) + { dataGridView.Columns[2].HeaderText = "S"; } + else + { dataGridView.Columns[2].HeaderText = thirdColumnHeader; } + } + + private static void Toggle(ref bool toggleThis) + { + toggleThis = !toggleThis; + } + + private void ChangeMeatloafRecipe(object sender, + System.EventArgs e) + { + Toggle(ref boringRecipe); + if (boringRecipe) + { + SetMeatloaf(boringMeatloaf, boringMeatloafRanking); + } + else + { + string greatMeatloafRecipe = + "1 lb. lean ground beef, " + + "1/2 cup bread crumbs, 1/4 cup ketchup," + + "1/3 tsp onion powder, " + + "1 clove of garlic, 1/2 pack onion soup mix " + + " dash of your favorite BBQ Sauce"; + SetMeatloaf(greatMeatloafRecipe, "***"); + } + } + + private void SetMeatloaf(string recipe, string rating) + { + dataGridView.Rows[0].Cells[2].Value = recipe; + dataGridView.Rows[0].Cells[3].Value = rating; + } + #endregion + + #region "demonstration code" + private void PostColumnCreation() + { + AddContextLabel(); + AddCriteriaLabel(); + CustomizeCellsInThirdColumn(); + AddContextMenu(); + SetDefaultCellInFirstColumn(); + ToolTips(); + + dataGridView.CellMouseEnter += + dataGridView_CellMouseEnter; + dataGridView.AutoSizeColumnModeChanged += + dataGridView_AutoSizeColumnModeChanged; + } + + private string criteriaLabel = "Column 3 sizing criteria: "; + private void AddCriteriaLabel() + { + AddLabelToPanelIfNotAlreadyThere(criteriaLabel, + criteriaLabel + + dataGridView.Columns[2].AutoSizeMode.ToString() + + "."); + } + + private void AddContextLabel() + { + string labelName = "label"; + AddLabelToPanelIfNotAlreadyThere(labelName, + "Use shortcut menu to change cell color."); + } + + private void AddLabelToPanelIfNotAlreadyThere( + string labelName, string labelText) + { + Label label; + if (FlowLayoutPanel1.Controls[labelName] == null) + { + label = new Label(); + label.AutoSize = true; + label.Name = labelName; + label.BackColor = Color.Bisque; + FlowLayoutPanel1.Controls.Add(label); + } + else + { + label = (Label)FlowLayoutPanel1.Controls[labelName]; + } + label.Text = labelText; + } + + // + private void CustomizeCellsInThirdColumn() + { + int thirdColumn = 2; + DataGridViewColumn column = + dataGridView.Columns[thirdColumn]; + DataGridViewCell cell = new DataGridViewTextBoxCell(); + + cell.Style.BackColor = Color.Wheat; + column.CellTemplate = cell; + } + // + + // + ToolStripMenuItem toolStripItem1 = new ToolStripMenuItem(); + + private void AddContextMenu() + { + toolStripItem1.Text = "Redden"; + toolStripItem1.Click += new EventHandler(toolStripItem1_Click); + ContextMenuStrip strip = new ContextMenuStrip(); + foreach (DataGridViewColumn column in dataGridView.Columns) + { + + column.ContextMenuStrip = strip; + column.ContextMenuStrip.Items.Add(toolStripItem1); + } + } + + private DataGridViewCellEventArgs mouseLocation; + + // Change the cell's color. + private void toolStripItem1_Click(object sender, EventArgs args) + { + dataGridView.Rows[mouseLocation.RowIndex] + .Cells[mouseLocation.ColumnIndex].Style.BackColor + = Color.Red; + } + + // Deal with hovering over a cell. + private void dataGridView_CellMouseEnter(object sender, + DataGridViewCellEventArgs location) + { + mouseLocation = location; + } + // + + // + private void SetDefaultCellInFirstColumn() + { + DataGridViewColumn firstColumn = dataGridView.Columns[0]; + DataGridViewCellStyle cellStyle = + new DataGridViewCellStyle(); + cellStyle.BackColor = Color.Thistle; + + firstColumn.DefaultCellStyle = cellStyle; + } + // + + // + private void ToolTips() + { + DataGridViewColumn firstColumn = dataGridView.Columns[0]; + DataGridViewColumn thirdColumn = dataGridView.Columns[2]; + firstColumn.ToolTipText = + "This column uses a default cell."; + thirdColumn.ToolTipText = + "This column uses a template cell." + + " Style changes to one cell apply to all cells."; + } + // + + private void AddAdditionalButtons() + { + AddButton(Button4, "Set Minimum Width of Column Two", + new EventHandler(Button4_Click)); + AddButton(Button5, "Set Width of Column One", + new EventHandler(Button5_Click)); + AddButton(Button6, "Autosize Third Column", + new EventHandler(Button6_Click)); + AddButton(Button7, "Add Thick Vertical Edge", + new EventHandler(Button7_Click)); + AddButton(Button8, "Style and Number Columns", + new EventHandler(Button8_Click)); + AddButton(Button9, "Change Column Header Text", + new EventHandler(Button9_Click)); + AddButton(Button10, "Swap First and Last Columns", + new EventHandler(Button10_Click)); + } + + private void AdjustDataGridViewSizing() + { + dataGridView.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + } + + // + //Set the minimum width. + private void Button4_Click(object sender, + System.EventArgs e) + { + DataGridViewColumn column = dataGridView.Columns[1]; + column.MinimumWidth = 40; + } + // + + // + // Set the width. + private void Button5_Click(object sender, System.EventArgs e) + { + DataGridViewColumn column = dataGridView.Columns[0]; + column.Width = 60; + } + // + + // + // AutoSize the third column. + private void Button6_Click(object sender, + System.EventArgs e) + { + DataGridViewColumn column = dataGridView.Columns[2]; + column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; + } + // + + // + // Set the vertical edge. + private void Button7_Click(object sender, + System.EventArgs e) + { + int thirdColumn = 2; + DataGridViewColumn column = + dataGridView.Columns[thirdColumn]; + column.DividerWidth = 10; + } + // + + // + // Style and number columns. + private void Button8_Click(object sender, + EventArgs args) + { + DataGridViewCellStyle style = new DataGridViewCellStyle(); + style.Alignment = + DataGridViewContentAlignment.MiddleCenter; + style.ForeColor = Color.IndianRed; + style.BackColor = Color.Ivory; + + foreach (DataGridViewColumn column in dataGridView.Columns) + { + column.HeaderCell.Value = column.Index.ToString(); + column.HeaderCell.Style = style; + } + } + // + + // + // Change the text in the column header. + private void Button9_Click(object sender, + EventArgs args) + { + foreach (DataGridViewColumn column in dataGridView.Columns) + { + + column.HeaderText = String.Concat("Column ", + column.Index.ToString()); + } + } + // + + // + // Swap the last column with the first. + private void Button10_Click(object sender, EventArgs args) + { + DataGridViewColumnCollection columnCollection = dataGridView.Columns; + + DataGridViewColumn firstVisibleColumn = + columnCollection.GetFirstColumn(DataGridViewElementStates.Visible); + DataGridViewColumn lastVisibleColumn = + columnCollection.GetLastColumn( + DataGridViewElementStates.Visible, DataGridViewElementStates.None); + + int firstColumn_sIndex = firstVisibleColumn.DisplayIndex; + firstVisibleColumn.DisplayIndex = lastVisibleColumn.DisplayIndex; + lastVisibleColumn.DisplayIndex = firstColumn_sIndex; + } + // + + // + // Updated the criteria label. + private void dataGridView_AutoSizeColumnModeChanged(object sender, + DataGridViewAutoSizeColumnModeEventArgs args) + { + args.Column.DataGridView.Parent. + Controls["flowlayoutpanel"].Controls[criteriaLabel]. + Text = criteriaLabel + + args.Column.AutoSizeMode.ToString(); + } + // + #endregion + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new DataGridViewColumnDemo()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewRowDemo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewRowDemo.cs new file mode 100644 index 0000000000..1433f08c21 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/CS/DataGridViewRowDemo.cs @@ -0,0 +1,270 @@ +// +using System.Windows.Forms; +using System; +using System.Drawing; + +public class DataGridViewRowDemo : Form +{ + #region "form setup" + public DataGridViewRowDemo() + { + InitializeComponent(); + + AddButton(Button1, "Reset", + new EventHandler(Button1_Click)); + AddButton(Button2, "Change Column 3 Header", + new EventHandler(Button2_Click)); + AddButton(Button3, "Change Meatloaf Recipe", + new EventHandler(Button3_Click)); + AddAdditionalButtons(); + + InitializeDataGridView(); + } + + private DataGridView dataGridView; + private Button Button1 = new Button(); + private Button Button2 = new Button(); + private Button Button3 = new Button(); + private Button Button4 = new Button(); + private Button Button5 = new Button(); + private Button Button6 = new Button(); + private Button Button7 = new Button(); + private Button Button8 = new Button(); + private Button Button9 = new Button(); + private Button Button10 = new Button(); + private FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel(); + + private void InitializeComponent() + { + FlowLayoutPanel1.Location = new Point(454, 0); + FlowLayoutPanel1.AutoSize = true; + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; + AutoSize = true; + ClientSize = new System.Drawing.Size(614, 360); + FlowLayoutPanel1.Name = "flowlayoutpanel"; + Controls.Add(this.FlowLayoutPanel1); + Text = this.GetType().Name; + } + #endregion + + #region "setup DataGridView" + + private string thirdColumnHeader = "Main Ingredients"; + private string boringMeatloaf = "ground beef"; + private string boringMeatloafRanking = "*"; + private bool boringRecipe; + private bool shortMode; + + private void InitializeDataGridView() + { + dataGridView = new System.Windows.Forms.DataGridView(); + Controls.Add(dataGridView); + dataGridView.Size = new Size(300, 200); + + // Create an unbound DataGridView by declaring a + // column count. + dataGridView.ColumnCount = 4; + dataGridView.ColumnHeadersVisible = true; + AdjustDataGridViewSizing(); + + // Set the column header style. + DataGridViewCellStyle columnHeaderStyle = + new DataGridViewCellStyle(); + columnHeaderStyle.BackColor = Color.Aqua; + columnHeaderStyle.Font = + new Font("Verdana", 10, FontStyle.Bold); + dataGridView.ColumnHeadersDefaultCellStyle = + columnHeaderStyle; + + // Set the column header names. + dataGridView.Columns[0].Name = "Recipe"; + dataGridView.Columns[1].Name = "Category"; + dataGridView.Columns[2].Name = thirdColumnHeader; + dataGridView.Columns[3].Name = "Rating"; + + // Populate the rows. + string[] row1 = new string[]{"Meatloaf", + "Main Dish", boringMeatloaf, boringMeatloafRanking}; + string[] row2 = new string[]{"Key Lime Pie", + "Dessert", "lime juice, evaporated milk", "****"}; + string[] row3 = new string[]{"Orange-Salsa Pork Chops", + "Main Dish", "pork chops, salsa, orange juice", "****"}; + string[] row4 = new string[]{"Black Bean and Rice Salad", + "Salad", "black beans, brown rice", "****"}; + string[] row5 = new string[]{"Chocolate Cheesecake", + "Dessert", "cream cheese", "***"}; + string[] row6 = new string[]{"Black Bean Dip", "Appetizer", + "black beans, sour cream", "***"}; + object[] rows = new object[] { row1, row2, row3, row4, row5, row6 }; + + foreach (string[] rowArray in rows) + { + dataGridView.Rows.Add(rowArray); + } + + shortMode = false; + boringRecipe = true; + } + + private void AddButton(Button button, string buttonLabel, + EventHandler handler) + { + FlowLayoutPanel1.Controls.Add(button); + button.TabIndex = FlowLayoutPanel1.Controls.Count; + button.Text = buttonLabel; + button.AutoSize = true; + button.Click += handler; + } + + // Reset columns to initial disorderly arrangement. + private void Button1_Click(object sender, System.EventArgs e) + { + Controls.Remove(dataGridView); + dataGridView.Dispose(); + InitializeDataGridView(); + } + + // Change column 3 header. + private void Button2_Click(object sender, + System.EventArgs e) + { + Toggle(ref shortMode); + if (shortMode) + { dataGridView.Columns[2].HeaderText = "S"; } + else + { dataGridView.Columns[2].HeaderText = thirdColumnHeader; } + } + + private static void Toggle(ref bool toggleThis) + { + toggleThis = !toggleThis; + } + + // Change meatloaf recipe. + private void Button3_Click(object sender, + System.EventArgs e) + { + Toggle(ref boringRecipe); + if (boringRecipe) + { + SetMeatloaf(boringMeatloaf, boringMeatloafRanking); + } + else + { + string greatMeatloafRecipe = + "1 lb. lean ground beef, " + + "1/2 cup bread crumbs, 1/4 cup ketchup," + + "1/3 tsp onion powder, " + + "1 clove of garlic, 1/2 pack onion soup mix " + + " dash of your favorite BBQ Sauce"; + SetMeatloaf(greatMeatloafRecipe, "***"); + } + } + + private void SetMeatloaf(string recipe, string rating) + { + dataGridView.Rows[0].Cells[2].Value = recipe; + dataGridView.Rows[0].Cells[3].Value = rating; + } + #endregion + + #region "demonstration code" + private void AddAdditionalButtons() + { + AddButton(Button4, "Set Row Two Minimum Height", + new EventHandler(Button4_Click)); + AddButton(Button5, "Set Row One Height", + new EventHandler(Button5_Click)); + AddButton(Button6, "Label Rows", + new EventHandler(Button6_Click)); + AddButton(Button7, "Turn on Extra Edge", + new EventHandler(Button7_Click)); + AddButton(Button8, "Give Cheesecake an Excellent Rating", + new EventHandler(Button8_Click)); + } + + private void AdjustDataGridViewSizing() + { + dataGridView.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns[ratingColumn].Width = 50; + } + + // + // Set minimum height. + private void Button4_Click(object sender, System.EventArgs e) + { + + int secondRow = 1; + DataGridViewRow row = dataGridView.Rows[secondRow]; + row.MinimumHeight = 40; + } + // + + // + // Set height. + private void Button5_Click(object sender, System.EventArgs e) + { + + DataGridViewRow row = dataGridView.Rows[0]; + row.Height = 15; + } + // + + // + // Set row labels. + private void Button6_Click(object sender, System.EventArgs e) + { + + int rowNumber = 1; + foreach (DataGridViewRow row in dataGridView.Rows) + { + if (row.IsNewRow) continue; + row.HeaderCell.Value = "Row " + rowNumber; + rowNumber = rowNumber + 1; + } + dataGridView.AutoResizeRowHeadersWidth( + DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders); + } + // + + // + // Set a thick horizontal edge. + private void Button7_Click(object sender, + System.EventArgs e) + { + int secondRow = 1; + DataGridViewRow row = dataGridView.Rows[secondRow]; + row.DividerHeight = 10; + } + // + + // + // Give cheescake excellent rating. + private void Button8_Click(object sender, + System.EventArgs e) + { + UpdateStars(dataGridView.Rows[4], "******************"); + } + + int ratingColumn = 3; + + private void UpdateStars(DataGridViewRow row, string stars) + { + + row.Cells[ratingColumn].Value = stars; + + // Resize the column width to account for the new value. + row.DataGridView.AutoResizeColumn(ratingColumn, + DataGridViewAutoSizeColumnMode.DisplayedCells); + } + // + #endregion + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new DataGridViewRowDemo()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs new file mode 100644 index 0000000000..b3d95d7f6b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/CS/errorhandling.cs @@ -0,0 +1,81 @@ +// +// +using System; +using System.Data; +using System.Data.SqlClient; +using System.Windows.Forms; + +public class Form1 : System.Windows.Forms.Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private BindingSource bindingSource1 = new BindingSource(); + + public Form1() + { + // Initialize the form. + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(dataGridView1); + this.Load += new EventHandler(Form1_Load); + } + // + + // + private void Form1_Load(System.Object sender, System.EventArgs e) + { + // Attach the DataError event to the corresponding event handler. + this.dataGridView1.DataError += + new DataGridViewDataErrorEventHandler(dataGridView1_DataError); + + // Initialize the BindingSource and bind the DataGridView to it. + bindingSource1.DataSource = GetData("select * from Customers"); + this.dataGridView1.DataSource = bindingSource1; + this.dataGridView1.AutoResizeColumns( + DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); + } + // + + // + private void dataGridView1_DataError(object sender, + DataGridViewDataErrorEventArgs e) + { + // If the data source raises an exception when a cell value is + // commited, display an error message. + if (e.Exception != null && + e.Context == DataGridViewDataErrorContexts.Commit) + { + MessageBox.Show("CustomerID value must be unique."); + } + } + // + + // + private static DataTable GetData(string selectCommand) + { + string connectionString = + "Integrated Security=SSPI;Persist Security Info=False;" + + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096"; + + // Connect to the database and fill a data table, including the + // schema information that contains the CustomerID column + // constraint. + SqlDataAdapter adapter = + new SqlDataAdapter(selectCommand, connectionString); + DataTable data = new DataTable(); + data.Locale = System.Globalization.CultureInfo.InvariantCulture; + adapter.Fill(data); + adapter.FillSchema(data, SchemaType.Source); + + return data; + } + // + + // + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/CS/form1.cs new file mode 100644 index 0000000000..317f2d029c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/CS/form1.cs @@ -0,0 +1,228 @@ +// This sample shows how to create a custom button column/cell that allows specific +// button cells to be disabled. This is done by rendering the disabled buttons in +// the overridden Paint method with ButtonRenderer. + +// Snippet0 (entire sample) will go in How to: Disable Buttons in a Button Column +// in the Windows Forms DataGridView Control +// Snippet5 will go in DataGridView.CurrentCellDirtyStateChanged, CommitEdit +// and CellValueChanged +// Snippet20 will go in DataGridViewButtonCell.Paint() (and/or DataGridViewCell.Paint?) +// Snippet20 will also go in DataGridViewCell.BorderWidths() + +// +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + this.AutoSize = true; + this.Load += new EventHandler(Form1_Load); + } + + public void Form1_Load(object sender, EventArgs e) + { + DataGridViewCheckBoxColumn column0 = + new DataGridViewCheckBoxColumn(); + DataGridViewDisableButtonColumn column1 = + new DataGridViewDisableButtonColumn(); + column0.Name = "CheckBoxes"; + column1.Name = "Buttons"; + dataGridView1.Columns.Add(column0); + dataGridView1.Columns.Add(column1); + dataGridView1.RowCount = 8; + dataGridView1.AutoSize = true; + dataGridView1.AllowUserToAddRows = false; + dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = + DataGridViewContentAlignment.MiddleCenter; + + // Set the text for each button. + for (int i = 0; i < dataGridView1.RowCount; i++) + { + dataGridView1.Rows[i].Cells["Buttons"].Value = + "Button " + i.ToString(); + } + + dataGridView1.CellValueChanged += + new DataGridViewCellEventHandler(dataGridView1_CellValueChanged); + dataGridView1.CurrentCellDirtyStateChanged += + new EventHandler(dataGridView1_CurrentCellDirtyStateChanged); + dataGridView1.CellClick += + new DataGridViewCellEventHandler(dataGridView1_CellClick); + + this.Controls.Add(dataGridView1); + } + + // + // This event handler manually raises the CellValueChanged event + // by calling the CommitEdit method. + void dataGridView1_CurrentCellDirtyStateChanged(object sender, + EventArgs e) + { + if (dataGridView1.IsCurrentCellDirty) + { + dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); + } + } + + // If a check box cell is clicked, this event handler disables + // or enables the button in the same row as the clicked cell. + public void dataGridView1_CellValueChanged(object sender, + DataGridViewCellEventArgs e) + { + if (dataGridView1.Columns[e.ColumnIndex].Name == "CheckBoxes") + { + DataGridViewDisableButtonCell buttonCell = + (DataGridViewDisableButtonCell)dataGridView1. + Rows[e.RowIndex].Cells["Buttons"]; + + DataGridViewCheckBoxCell checkCell = + (DataGridViewCheckBoxCell)dataGridView1. + Rows[e.RowIndex].Cells["CheckBoxes"]; + buttonCell.Enabled = !(Boolean)checkCell.Value; + + dataGridView1.Invalidate(); + } + } + // + + // If the user clicks on an enabled button cell, this event handler + // reports that the button is enabled. + void dataGridView1_CellClick(object sender, + DataGridViewCellEventArgs e) + { + if (dataGridView1.Columns[e.ColumnIndex].Name == "Buttons") + { + DataGridViewDisableButtonCell buttonCell = + (DataGridViewDisableButtonCell)dataGridView1. + Rows[e.RowIndex].Cells["Buttons"]; + + if (buttonCell.Enabled) + { + MessageBox.Show(dataGridView1.Rows[e.RowIndex]. + Cells[e.ColumnIndex].Value.ToString() + + " is enabled"); + } + } + } +} + +// +public class DataGridViewDisableButtonColumn : DataGridViewButtonColumn +{ + public DataGridViewDisableButtonColumn() + { + this.CellTemplate = new DataGridViewDisableButtonCell(); + } +} +// + +public class DataGridViewDisableButtonCell : DataGridViewButtonCell +{ + private bool enabledValue; + public bool Enabled + { + get + { + return enabledValue; + } + set + { + enabledValue = value; + } + } + + // Override the Clone method so that the Enabled property is copied. + public override object Clone() + { + DataGridViewDisableButtonCell cell = + (DataGridViewDisableButtonCell)base.Clone(); + cell.Enabled = this.Enabled; + return cell; + } + + // + // By default, enable the button cell. + public DataGridViewDisableButtonCell() + { + this.enabledValue = true; + } + // + + // + protected override void Paint(Graphics graphics, + Rectangle clipBounds, Rectangle cellBounds, int rowIndex, + DataGridViewElementStates elementState, object value, + object formattedValue, string errorText, + DataGridViewCellStyle cellStyle, + DataGridViewAdvancedBorderStyle advancedBorderStyle, + DataGridViewPaintParts paintParts) + { + // The button cell is disabled, so paint the border, + // background, and disabled button for the cell. + if (!this.enabledValue) + { + // Draw the cell background, if specified. + if ((paintParts & DataGridViewPaintParts.Background) == + DataGridViewPaintParts.Background) + { + SolidBrush cellBackground = + new SolidBrush(cellStyle.BackColor); + graphics.FillRectangle(cellBackground, cellBounds); + cellBackground.Dispose(); + } + + // Draw the cell borders, if specified. + if ((paintParts & DataGridViewPaintParts.Border) == + DataGridViewPaintParts.Border) + { + PaintBorder(graphics, clipBounds, cellBounds, cellStyle, + advancedBorderStyle); + } + + // Calculate the area in which to draw the button. + Rectangle buttonArea = cellBounds; + Rectangle buttonAdjustment = + this.BorderWidths(advancedBorderStyle); + buttonArea.X += buttonAdjustment.X; + buttonArea.Y += buttonAdjustment.Y; + buttonArea.Height -= buttonAdjustment.Height; + buttonArea.Width -= buttonAdjustment.Width; + + // Draw the disabled button. + ButtonRenderer.DrawButton(graphics, buttonArea, + PushButtonState.Disabled); + + // Draw the disabled button text. + if (this.FormattedValue is String) + { + TextRenderer.DrawText(graphics, + (string)this.FormattedValue, + this.DataGridView.Font, + buttonArea, SystemColors.GrayText); + } + } + else + { + // The button cell is enabled, so let the base class + // handle the painting. + base.Paint(graphics, clipBounds, cellBounds, rowIndex, + elementState, value, formattedValue, errorText, + cellStyle, advancedBorderStyle, paintParts); + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CS/tictactoe.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CS/tictactoe.cs new file mode 100644 index 0000000000..9b774330d7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/CS/tictactoe.cs @@ -0,0 +1,433 @@ +// This example demonstrates using images to create a +// TicTacToe game. +// +using System.IO; +using System.Windows.Forms; +using System.Drawing; +using System; + +public class TicTacToe : System.Windows.Forms.Form +{ + public TicTacToe() + { + blank = new Bitmap(new MemoryStream(blankImage)); + x = new Bitmap(new MemoryStream(xImage)); + o = new Bitmap(new MemoryStream(oImage)); + + this.AutoSize = true; + SetupButtons(); + InitializeDataGridView(null, null); + } + + private DataGridView dataGridView1; + private Button Button1 = new Button(); + private Label turn = new Label(); + private Button Button2 = new Button(); + private Button Button3 = new Button(); + private Button Button4 = new Button(); + private Button Button5 = new Button(); + private FlowLayoutPanel Panel1 = new FlowLayoutPanel(); + + #region "bitmaps" + private byte[] oImage = new byte[] { + 0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x76, + 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, 0xB, 0x0, 0x0, 0x0, 0xA, + 0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, + 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x80, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, 0x80, 0x0, + 0x80, 0x0, 0x0, 0x0, 0x80, 0x0, 0x80, 0x0, 0x80, 0x80, 0x0, + 0x0, 0xC0, 0xC0, 0xC0, 0x0, 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, + 0xFF, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF, + 0x0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0xF, 0xFF, 0xF0, + 0x0, 0x0, 0xFF, 0x0, 0xFF, 0xF0, 0xF, 0xF0, 0x0, 0x0, 0xF0, + 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF0, 0xFF, 0xFF, + 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x0, 0x0, 0x0, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0, 0x0, 0x0, + 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF0, 0xFF, + 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0xF0, + 0xF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xF, 0xFF, 0xF0, 0x0, + 0x0}; + + private byte[] xImage = new byte[]{ + 0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x76, 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, + 0xB, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x50, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x80, + 0x0, 0x0, 0x0, 0x80, 0x80, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, + 0x0, 0x80, 0x0, 0x80, 0x80, 0x0, 0x0, 0xC0, 0xC0, 0xC0, 0x0, + 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0xFF, 0x0, + 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0x0, + 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0x0, + 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, 0xF, + 0xFF, 0xFF, 0xF, 0xF0, 0x0, 0x0, 0xFF, 0xF0, 0xFF, 0xF0, + 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xF, 0xF, 0xFF, 0xF0, 0x0, + 0x0, 0xFF, 0xFF, 0xF, 0xF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, + 0xF, 0xF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xF0, 0xFF, 0xF0, + 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xF, 0xFF, 0xFF, 0xF, 0xF0, 0x0, + 0x0, 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0}; + + private byte[] blankImage = new byte[] { + 0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x76, + 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, 0xB, 0x0, 0x0, 0x0, 0xA, + 0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, + 0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x80, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, 0x80, 0x0, + 0x80, 0x0, 0x0, 0x0, 0x80, 0x0, 0x80, 0x0, 0x80, 0x80, 0x0, + 0x0, 0xC0, 0xC0, 0xC0, 0x0, 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, + 0xFF, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF, + 0x0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, + 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, + 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xF0, 0x0, 0x0}; + #endregion + + private Bitmap blank; + private Bitmap x; + private Bitmap o; + private string xString = "X's turn"; + private string oString = "O's turn"; + private string gameOverString = "Game Over"; + private int bitmapPadding = 6; + + private void InitializeDataGridView(object sender, + EventArgs e) + { + this.Panel1.SuspendLayout(); + this.SuspendLayout(); + + ConfigureForm(); + SizeGrid(); + CreateColumns(); + CreateRows(); + + this.Panel1.ResumeLayout(false); + this.ResumeLayout(false); + } + + private void ConfigureForm() + { + AutoSize = true; + turn.Size = new System.Drawing.Size(75, 34); + turn.TextAlign = ContentAlignment.MiddleLeft; + turn.Text = xString; + + Panel1.Location = new System.Drawing.Point(0, 8); + Panel1.Size = new System.Drawing.Size(120, 196); + Panel1.FlowDirection = FlowDirection.TopDown; + + ClientSize = new System.Drawing.Size(355, 200); + Controls.Add(this.Panel1); + Text = "TicTacToe"; + + dataGridView1 = new System.Windows.Forms.DataGridView(); + dataGridView1.Location = new Point(120, 0); + dataGridView1.AllowUserToAddRows = false; + dataGridView1.CellClick += new + DataGridViewCellEventHandler(dataGridView1_CellClick); + dataGridView1.CellMouseEnter += new + DataGridViewCellEventHandler(dataGridView1_CellMouseEnter); + dataGridView1.CellMouseLeave += new + DataGridViewCellEventHandler(dataGridView1_CellMouseLeave); + + Controls.Add(dataGridView1); + } + + private void SetupButtons() + { + Button1.AutoSize = true; + SetupButton(Button1, "Restart", new EventHandler(Reset)); + Panel1.Controls.Add(turn); + SetupButton(Button2, "Increase Cell Size", new EventHandler(MakeCellsLarger)); + SetupButton(Button3, "Stretch Images", new EventHandler(Stretch)); + SetupButton(Button4, "Zoom Images", new EventHandler(ZoomToImage)); + SetupButton(Button5, "Normal Images", new EventHandler(NormalImage)); + } + + private void SetupButton(Button button, string buttonLabel, EventHandler handler) + { + Panel1.Controls.Add(button); + button.Text = buttonLabel; + button.AutoSize = true; + button.Click += handler; + } + + // + private void CreateColumns() + { + DataGridViewImageColumn imageColumn; + int columnCount = 0; + do + { + Bitmap unMarked = blank; + imageColumn = new DataGridViewImageColumn(); + + //Add twice the padding for the left and + //right sides of the cell. + imageColumn.Width = x.Width + 2 * bitmapPadding + 1; + + imageColumn.Image = unMarked; + dataGridView1.Columns.Add(imageColumn); + columnCount = columnCount + 1; + } + while (columnCount < 3); + } + // + + private void CreateRows() + { + dataGridView1.Rows.Add(); + dataGridView1.Rows.Add(); + dataGridView1.Rows.Add(); + } + + // + private void SizeGrid() + { + dataGridView1.ColumnHeadersVisible = false; + dataGridView1.RowHeadersVisible = false; + dataGridView1.AllowUserToResizeColumns = false;; + dataGridView1.AllowUserToResizeRows = false; + dataGridView1.BorderStyle = BorderStyle.None; + + //Add twice the padding for the top of the cell + //and the bottom. + dataGridView1.RowTemplate.Height = x.Height + + 2 * bitmapPadding + 1; + + dataGridView1.AutoSize = true; + } + // + + private void Reset(object sender, System.EventArgs e) + { + dataGridView1.Dispose(); + InitializeDataGridView(null, null); + } + + // + private void dataGridView1_CellClick(object sender, + DataGridViewCellEventArgs e) + { + + if (turn.Text.Equals(gameOverString)) { return; } + + DataGridViewImageCell cell = (DataGridViewImageCell) + dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; + + if (cell.Value == blank) + { + if (IsOsTurn()) + { + cell.Value = o; + } + else + { + cell.Value = x; + } + ToggleTurn(); + } + if (IsAWin()) + { + turn.Text = gameOverString; + } + } + // + + // + private void dataGridView1_CellMouseEnter(object sender, + DataGridViewCellEventArgs e) + { + Bitmap markingUnderMouse = (Bitmap)dataGridView1. + Rows[e.RowIndex]. + Cells[e.ColumnIndex].Value; + + if (markingUnderMouse == blank) + { + dataGridView1.Cursor = Cursors.Default; + } + else if (markingUnderMouse == o || markingUnderMouse == x) + { + dataGridView1.Cursor = Cursors.No; + ToolTip(e, true); + } + } + + private void ToolTip(DataGridViewCellEventArgs e, bool showTip) + { + DataGridViewImageCell cell = (DataGridViewImageCell) + dataGridView1 + .Rows[e.RowIndex].Cells[e.ColumnIndex]; + DataGridViewImageColumn imageColumn = + (DataGridViewImageColumn) + dataGridView1.Columns[cell.ColumnIndex]; + + if (showTip) + { + cell.ToolTipText = imageColumn.Description; + } + else { cell.ToolTipText = String.Empty; } + } + + private void dataGridView1_CellMouseLeave(object sender, + DataGridViewCellEventArgs e) + { + ToolTip(e, false); + dataGridView1.Cursor = Cursors.Default; + } + // + + // + private void Stretch(object sender, EventArgs e) + { + foreach (DataGridViewImageColumn column in + dataGridView1.Columns) + { + column.ImageLayout = DataGridViewImageCellLayout.Stretch; + column.Description = "Stretched"; + } + } + + private void ZoomToImage(object sender, EventArgs e) + { + + foreach (DataGridViewImageColumn column in + dataGridView1.Columns) + { + column.ImageLayout = DataGridViewImageCellLayout.Zoom; + column.Description = "Zoomed"; + } + } + + private void NormalImage(object sender, EventArgs e) + { + + foreach (DataGridViewImageColumn column in + dataGridView1.Columns) + { + column.ImageLayout = DataGridViewImageCellLayout.Normal; + column.Description = "Normal"; + } + } + // + + private void MakeCellsLarger(object sender, EventArgs e) + { + foreach (DataGridViewImageColumn column in + dataGridView1.Columns) + { + column.Width = column.Width * 2; + } + foreach (DataGridViewRow row in dataGridView1.Rows) + { + if (row.IsNewRow) break; + row.Height = (int)(row.Height * 1.5); + } + } + + private bool IsAWin() + { + if (ARowIsSame() || AColumnIsSame() || ADiagonalIsSame()) + return true; + else return false; + } + + private bool ARowIsSame() + { + Bitmap marking = null; + + foreach (DataGridViewRow row in dataGridView1.Rows) + { + if (row.IsNewRow) break; + marking = (Bitmap)row.Cells[0].Value; + if (marking != blank) + { + if (marking == row.Cells[1].Value && + marking == row.Cells[2].Value) return true; + } + } + return false; + } + + private bool AColumnIsSame() + { + int columnIndex = 0; + Bitmap marking; + do + { + marking = (Bitmap) + dataGridView1.Rows[0].Cells[columnIndex].Value; + if (marking != blank) + { + if (marking == (Bitmap)dataGridView1.Rows[1] + .Cells[columnIndex].Value + && marking == (Bitmap)dataGridView1.Rows[2]. + Cells[columnIndex].Value) return true; + } + columnIndex = columnIndex + 1; + } + while (columnIndex < dataGridView1.Columns.GetColumnCount( + DataGridViewElementStates.Visible)); + return false; + } + + private bool ADiagonalIsSame() + { + if (LeftToRightDiagonalIsSame()) { return true; } + if (RightToLeftDiagonalIsSame()) { return true; } + return false; + } + + private bool LeftToRightDiagonalIsSame() + { + return IsDiagonalSame(0, 2); + } + + private bool RightToLeftDiagonalIsSame() + { + return IsDiagonalSame(2, 0); + } + + private bool IsDiagonalSame(int startingColumn, int lastColumn) + { + Bitmap marking = (Bitmap)dataGridView1.Rows[0] + .Cells[startingColumn].Value; + + if (marking == blank) return false; + if (marking == dataGridView1.Rows[1].Cells[1] + .Value && marking == dataGridView1.Rows[2] + .Cells[lastColumn].Value) return true; + + return false; + } + + private void ToggleTurn() + { + if (turn.Text.Equals(xString)) { turn.Text = oString; } + else { turn.Text = xString; } + } + + private bool IsOsTurn() + { + if (turn.Text.Equals(oString)) return true; + return false; + } + + [STAThread] + public static void Main() + { + Application.Run(new TicTacToe()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CS/programmaticsizing.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CS/programmaticsizing.cs new file mode 100644 index 0000000000..d52f1ed495 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/CS/programmaticsizing.cs @@ -0,0 +1,311 @@ +// +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +public class ProgrammaticSizing : System.Windows.Forms.Form +{ + private FlowLayoutPanel flowLayoutPanel1; + private Button button1 = new Button(); + private Button button2 = new Button(); + private Button button3 = new Button(); + private Button button4 = new Button(); + private Button button5 = new Button(); + private Button button6 = new Button(); + private Button button7 = new Button(); + private Button button8 = new Button(); + private Button button9 = new Button(); + private Button button10 = new Button(); + private Button button11 = new Button(); + + public ProgrammaticSizing() + { + InitializeComponent(); + AddDirections(); + this.Load += new EventHandler(InitializeDataGridView); + + AddButton(button1, "Reset", + new EventHandler(ResetToDisorder)); + AddButton(button2, "Change Column 3 Header", + new EventHandler(ChangeColumn3Header)); + AddButton(button3, "Change Meatloaf Recipe", + new EventHandler(ChangeMeatloafRecipe)); + AddButton(button10, "Change Restaurant 2", + new EventHandler(ChangeRestaurant)); + AddButtonsForProgrammaticResizing(); + } + + #region form code + private void InitializeComponent() + { + this.flowLayoutPanel1 = new FlowLayoutPanel(); + this.flowLayoutPanel1.FlowDirection + = FlowDirection.TopDown; + this.flowLayoutPanel1.Location = new Point(492, 0); + this.flowLayoutPanel1.AutoSize = true; + + this.AutoSize = true; + this.Controls.Add(this.flowLayoutPanel1); + this.Text = this.GetType().Name; + } + + private void AddDirections() + { + Label directions = new Label(); + directions.AutoSize = true; + String newLine = Environment.NewLine; + directions.Text = "Press the buttons that start " + newLine + + "with 'Change' to see how different sizing " + newLine + + "modes deal with content changes."; + + flowLayoutPanel1.Controls.Add(directions); + } + #endregion + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new ProgrammaticSizing()); + } + + private Size startingSize; + private string thirdColumnHeader = "Main Ingredients"; + private string boringMeatloaf = "ground beef"; + private string boringMeatloafRanking = "*"; + private bool boringRecipe; + private bool shortMode; + private DataGridView dataGridView1; + private string otherRestaurant = "Gomes's Saharan Sushi"; + + private void InitializeDataGridView(Object sender, + EventArgs ignoredToo) + { + this.dataGridView1 = new DataGridView(); + this.dataGridView1.Location = new Point(0, 0); + this.dataGridView1.Size = new Size(292, 266); + this.Controls.Add(this.dataGridView1); + startingSize = new Size(450, 400); + dataGridView1.Size = startingSize; + + AddColumns(); + PopulateRows(); + + shortMode = false; + boringRecipe = true; + } + + private void AddColumns() + { + dataGridView1.ColumnCount = 4; + dataGridView1.ColumnHeadersVisible = true; + + DataGridViewCellStyle columnHeaderStyle = + new DataGridViewCellStyle(); + + columnHeaderStyle.BackColor = Color.Aqua; + columnHeaderStyle.Font = new Font("Verdana", 10, + FontStyle.Bold); + dataGridView1.ColumnHeadersDefaultCellStyle = + columnHeaderStyle; + + dataGridView1.Columns[0].Name = "Recipe"; + dataGridView1.Columns[1].Name = "Category"; + dataGridView1.Columns[2].Name = thirdColumnHeader; + dataGridView1.Columns[3].Name = "Rating"; + } + + private void PopulateRows() + { + string[] row1 = { + "Meatloaf", "Main Dish", + boringMeatloaf, boringMeatloafRanking + }; + string[] row2 = { + "Key Lime Pie", "Dessert", + "lime juice, evaporated milk", "****" + }; + string[] row3 = { + "Orange-Salsa Pork Chops", "Main Dish", + "pork chops, salsa, orange juice", "****" + }; + string[] row4 = { + "Black Bean and Rice Salad", "Salad", + "black beans, brown rice", "****" + }; + string[] row5 = { + "Chocolate Cheesecake", "Dessert", + "cream cheese", "***" + }; + string[] row6 = { + "Black Bean Dip", + "Appetizer", "black beans, sour cream", "***" + }; + object[] rows = new object[] { + row1, row2, row3, row4, row5, row6 + }; + + foreach (string[] row in rows) + dataGridView1.Rows.Add(row); + foreach (DataGridViewRow row in dataGridView1.Rows) + { + if (row.IsNewRow) break; + row.HeaderCell.Value = "Restaurant " + row.Index; + } + } + + private void AddButton(Button button, string buttonLabel, + EventHandler handler) + { + button.Text = buttonLabel; + button.AutoSize = true; + flowLayoutPanel1.Controls.Add(button); + button.Click += handler; + } + + private void ResetToDisorder(Object sender, EventArgs e) + { + Controls.Remove(dataGridView1); + dataGridView1.Size = startingSize; + dataGridView1.Dispose(); + InitializeDataGridView(null, null); + } + + private void ChangeColumn3Header(Object sender, EventArgs e) + { + Toggle(ref shortMode); + if (shortMode) + dataGridView1.Columns[2].HeaderText = "S"; + else + dataGridView1.Columns[2].HeaderText = + thirdColumnHeader; + } + + private static void Toggle(ref Boolean toggleThis) + { + toggleThis = !toggleThis; + } + + private void ChangeMeatloafRecipe(Object sender, + EventArgs e) + { + Toggle(ref boringRecipe); + + if (boringRecipe) + { + SetMeatloaf(boringMeatloaf, boringMeatloafRanking); + } + else + { + string greatMeatloafRecipe = + "1 lb. lean ground beef, " + + "1/2 cup bread crumbs, 1/4 cup ketchup," + + "1/3 tsp onion powder, " + + "1 clove of garlic, 1/2 pack onion soup mix " + + " dash of your favorite BBQ Sauce"; + + SetMeatloaf(greatMeatloafRecipe, "***"); + } + } + + private void SetMeatloaf(string recipe, string rating) + { + dataGridView1.Rows[0].Cells[2].Value = recipe; + dataGridView1.Rows[0].Cells[3].Value = rating; + } + + private void ChangeRestaurant(Object sender, + EventArgs ignored) + { + if (dataGridView1.Rows[2].HeaderCell.Value.Equals(otherRestaurant)) + { + dataGridView1.Rows[2].HeaderCell.Value = + "Restaurant 2"; + } + else + { + dataGridView1.Rows[2].HeaderCell.Value = otherRestaurant; + } + } + + #region "programmatic resizing" + + private void AddButtonsForProgrammaticResizing() + { + AddButton(button4, "Size Third Column", + new EventHandler(SizeThirdColumnHeader)); + AddButton(button5, "Size Column Headers", + new EventHandler(SizeColumnHeaders)); + AddButton(button6, "Size All Columns", + new EventHandler(SizeAllColumns)); + AddButton(button7, "Size Third Row", + new EventHandler(SizeThirdRow)); + AddButton(button8, "Size First Row Header Using All Headers", + new EventHandler(SizeFirstRowHeaderToAllHeaders)); + AddButton(button9, "Size All Rows and Row Headers", + new EventHandler(SizeAllRowsAndTheirHeaders)); + AddButton(button11, "Size All Rows ", + new EventHandler(SizeAllRows)); + } + + // + private void SizeThirdColumnHeader(Object sender, + EventArgs e) + { + dataGridView1.AutoResizeColumn( + 2, DataGridViewAutoSizeColumnMode.ColumnHeader); + } + // + + // + private void SizeColumnHeaders(Object sender, EventArgs e) + { + dataGridView1.AutoResizeColumnHeadersHeight(2); + } + // + + // + private void SizeAllColumns(Object sender, EventArgs e) + { + dataGridView1.AutoResizeColumns( + DataGridViewAutoSizeColumnsMode.AllCells); + } + // + + // + private void SizeThirdRow(Object sender, EventArgs e) + { + dataGridView1.AutoResizeRow( + 2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader); + } + // + + // + private void SizeFirstRowHeaderToAllHeaders(Object sender, EventArgs e) + { + dataGridView1.AutoResizeRowHeadersWidth( + 0, DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders); + } + // + + // + private void SizeAllRowsAndTheirHeaders(Object sender, EventArgs e) + { + dataGridView1.AutoResizeRows( + DataGridViewAutoSizeRowsMode.AllCells); + } + // + + // + private void SizeAllRows(Object sender, + EventArgs e) + { + dataGridView1.AutoResizeRows( + DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders); + } + // + #endregion +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CS/datagridviewrowtemplate.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CS/datagridviewrowtemplate.cs new file mode 100644 index 0000000000..8f38e56f34 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/CS/datagridviewrowtemplate.cs @@ -0,0 +1,35 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(this.dataGridView1); + this.Load += new EventHandler(Form1_Load); + this.Text = "DataGridView.RowTemplate demo"; + } + + void Form1_Load(object sender, EventArgs e) + { + // + DataGridViewRow row = this.dataGridView1.RowTemplate; + row.DefaultCellStyle.BackColor = Color.Bisque; + row.Height = 35; + row.MinimumHeight = 20; + // + + this.dataGridView1.ColumnCount = 5; + this.dataGridView1.RowCount = 10; + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/CS/form1.cs new file mode 100644 index 0000000000..9007974ebe --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/CS/form1.cs @@ -0,0 +1,85 @@ +// +#region Using directives + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +#endregion +class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + // Establish the main entry point for the application. + [STAThreadAttribute()] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + // Initialize the form. + // This code can be replaced with designer generated code. + dataGridView1.AllowUserToAddRows = false; + dataGridView1.Dock = DockStyle.Fill; + dataGridView1.SortCompare += new DataGridViewSortCompareEventHandler( + this.dataGridView1_SortCompare); + Controls.Add(this.dataGridView1); + this.Text = "DataGridView.SortCompare demo"; + + PopulateDataGridView(); + } + + // + // Replace this with your own population code. + public void PopulateDataGridView() + { + // Add columns to the DataGridView. + dataGridView1.ColumnCount = 3; + + // Set the properties of the DataGridView columns. + dataGridView1.Columns[0].Name = "ID"; + dataGridView1.Columns[1].Name = "Name"; + dataGridView1.Columns[2].Name = "City"; + dataGridView1.Columns["ID"].HeaderText = "ID"; + dataGridView1.Columns["Name"].HeaderText = "Name"; + dataGridView1.Columns["City"].HeaderText = "City"; + + // Add rows of data to the DataGridView. + dataGridView1.Rows.Add(new string[] { "1", "Parker", "Seattle" }); + dataGridView1.Rows.Add(new string[] { "2", "Parker", "New York" }); + dataGridView1.Rows.Add(new string[] { "3", "Watson", "Seattle" }); + dataGridView1.Rows.Add(new string[] { "4", "Jameson", "New Jersey" }); + dataGridView1.Rows.Add(new string[] { "5", "Brock", "New York" }); + dataGridView1.Rows.Add(new string[] { "6", "Conner", "Portland" }); + + // Autosize the columns. + dataGridView1.AutoResizeColumns(); + } + // + + // + private void dataGridView1_SortCompare(object sender, + DataGridViewSortCompareEventArgs e) + { + // Try to sort based on the cells in the current column. + e.SortResult = System.String.Compare( + e.CellValue1.ToString(), e.CellValue2.ToString()); + + // If the cells are equal, sort based on the ID column. + if (e.SortResult == 0 && e.Column.Name != "ID") + { + e.SortResult = System.String.Compare( + dataGridView1.Rows[e.RowIndex1].Cells["ID"].Value.ToString(), + dataGridView1.Rows[e.RowIndex2].Cells["ID"].Value.ToString()); + } + e.Handled = true; + } + // +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs new file mode 100644 index 0000000000..7e2713a9af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/CS/virtualmode.cs @@ -0,0 +1,308 @@ +// The purpose of this snippet is to demonstrate how to use all the primary virtual-mode events. +// Additionally, this example implements row-level commit-scope. To experiment with this feature, +// make some edits in multiple cells within a single row, then click ESC once to revert the edit +// for a single cell, and twice to revert the edit for the entire row. You can commit all edits +// for a row without changing focus by pressing CTRL-ENTER. + +// +// +using System; +using System.Windows.Forms; + +// +public class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + // Declare an ArrayList to serve as the data store. + private System.Collections.ArrayList customers = + new System.Collections.ArrayList(); + + // Declare a Customer object to store data for a row being edited. + private Customer customerInEdit; + + // Declare a variable to store the index of a row being edited. + // A value of -1 indicates that there is no row currently in edit. + private int rowInEdit = -1; + + // Declare a variable to indicate the commit scope. + // Set this value to false to use cell-level commit scope. + private bool rowScopeCommit = true; + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + // Initialize the form. + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(this.dataGridView1); + this.Load += new EventHandler(Form1_Load); + this.Text = "DataGridView virtual-mode demo (row-level commit scope)"; + } + // + + // + private void Form1_Load(object sender, EventArgs e) + { + // Enable virtual mode. + this.dataGridView1.VirtualMode = true; + + // Connect the virtual-mode events to event handlers. + this.dataGridView1.CellValueNeeded += new + DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded); + this.dataGridView1.CellValuePushed += new + DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed); + this.dataGridView1.NewRowNeeded += new + DataGridViewRowEventHandler(dataGridView1_NewRowNeeded); + this.dataGridView1.RowValidated += new + DataGridViewCellEventHandler(dataGridView1_RowValidated); + this.dataGridView1.RowDirtyStateNeeded += new + QuestionEventHandler(dataGridView1_RowDirtyStateNeeded); + this.dataGridView1.CancelRowEdit += new + QuestionEventHandler(dataGridView1_CancelRowEdit); + this.dataGridView1.UserDeletingRow += new + DataGridViewRowCancelEventHandler(dataGridView1_UserDeletingRow); + + // Add columns to the DataGridView. + DataGridViewTextBoxColumn companyNameColumn = new + DataGridViewTextBoxColumn(); + companyNameColumn.HeaderText = "Company Name"; + companyNameColumn.Name = "Company Name"; + DataGridViewTextBoxColumn contactNameColumn = new + DataGridViewTextBoxColumn(); + contactNameColumn.HeaderText = "Contact Name"; + contactNameColumn.Name = "Contact Name"; + this.dataGridView1.Columns.Add(companyNameColumn); + this.dataGridView1.Columns.Add(contactNameColumn); + this.dataGridView1.AutoSizeColumnsMode = + DataGridViewAutoSizeColumnsMode.AllCells; + + // Add some sample entries to the data store. + this.customers.Add(new Customer( + "Bon app'", "Laurence Lebihan")); + this.customers.Add(new Customer( + "Bottom-Dollar Markets", "Elizabeth Lincoln")); + this.customers.Add(new Customer( + "B's Beverages", "Victoria Ashworth")); + + // Set the row count, including the row for new records. + this.dataGridView1.RowCount = 4; + } + // + + // + private void dataGridView1_CellValueNeeded(object sender, + System.Windows.Forms.DataGridViewCellValueEventArgs e) + { + // If this is the row for new records, no values are needed. + if (e.RowIndex == this.dataGridView1.RowCount - 1) return; + + Customer customerTmp = null; + + // Store a reference to the Customer object for the row being painted. + if (e.RowIndex == rowInEdit) + { + customerTmp = this.customerInEdit; + } + else + { + customerTmp = (Customer)this.customers[e.RowIndex]; + } + + // Set the cell value to paint using the Customer object retrieved. + switch (this.dataGridView1.Columns[e.ColumnIndex].Name) + { + case "Company Name": + e.Value = customerTmp.CompanyName; + break; + + case "Contact Name": + e.Value = customerTmp.ContactName; + break; + } + } + // + + // + private void dataGridView1_CellValuePushed(object sender, + System.Windows.Forms.DataGridViewCellValueEventArgs e) + { + Customer customerTmp = null; + + // Store a reference to the Customer object for the row being edited. + if (e.RowIndex < this.customers.Count) + { + // If the user is editing a new row, create a new Customer object. + this.customerInEdit ??= new Customer( + ((Customer)this.customers[e.RowIndex]).CompanyName, + ((Customer)this.customers[e.RowIndex]).ContactName); + customerTmp = this.customerInEdit; + this.rowInEdit = e.RowIndex; + } + else + { + customerTmp = this.customerInEdit; + } + + // Set the appropriate Customer property to the cell value entered. + String newValue = e.Value as String; + switch (this.dataGridView1.Columns[e.ColumnIndex].Name) + { + case "Company Name": + customerTmp.CompanyName = newValue; + break; + + case "Contact Name": + customerTmp.ContactName = newValue; + break; + } + } + // + + // + private void dataGridView1_NewRowNeeded(object sender, + System.Windows.Forms.DataGridViewRowEventArgs e) + { + // Create a new Customer object when the user edits + // the row for new records. + this.customerInEdit = new Customer(); + this.rowInEdit = this.dataGridView1.Rows.Count - 1; + } + // + + // + private void dataGridView1_RowValidated(object sender, + System.Windows.Forms.DataGridViewCellEventArgs e) + { + // Save row changes if any were made and release the edited + // Customer object if there is one. + if (e.RowIndex >= this.customers.Count && + e.RowIndex != this.dataGridView1.Rows.Count - 1) + { + // Add the new Customer object to the data store. + this.customers.Add(this.customerInEdit); + this.customerInEdit = null; + this.rowInEdit = -1; + } + else if (this.customerInEdit != null && + e.RowIndex < this.customers.Count) + { + // Save the modified Customer object in the data store. + this.customers[e.RowIndex] = this.customerInEdit; + this.customerInEdit = null; + this.rowInEdit = -1; + } + else if (this.dataGridView1.ContainsFocus) + { + this.customerInEdit = null; + this.rowInEdit = -1; + } + } + // + + // + private void dataGridView1_RowDirtyStateNeeded(object sender, + System.Windows.Forms.QuestionEventArgs e) + { + if (!rowScopeCommit) + { + // In cell-level commit scope, indicate whether the value + // of the current cell has been modified. + e.Response = this.dataGridView1.IsCurrentCellDirty; + } + } + // + + // + private void dataGridView1_CancelRowEdit(object sender, + System.Windows.Forms.QuestionEventArgs e) + { + if (this.rowInEdit == this.dataGridView1.Rows.Count - 2 && + this.rowInEdit == this.customers.Count) + { + // If the user has canceled the edit of a newly created row, + // replace the corresponding Customer object with a new, empty one. + this.customerInEdit = new Customer(); + } + else + { + // If the user has canceled the edit of an existing row, + // release the corresponding Customer object. + this.customerInEdit = null; + this.rowInEdit = -1; + } + } + // + + // + private void dataGridView1_UserDeletingRow(object sender, + System.Windows.Forms.DataGridViewRowCancelEventArgs e) + { + if (e.Row.Index < this.customers.Count) + { + // If the user has deleted an existing row, remove the + // corresponding Customer object from the data store. + this.customers.RemoveAt(e.Row.Index); + } + + if (e.Row.Index == this.rowInEdit) + { + // If the user has deleted a newly created row, release + // the corresponding Customer object. + this.rowInEdit = -1; + this.customerInEdit = null; + } + } + // + // +} +// +// + +// +public class Customer +{ + private String companyNameValue; + private String contactNameValue; + + public Customer() + { + // Leave fields empty. + } + + public Customer(String companyName, String contactName) + { + companyNameValue = companyName; + contactNameValue = contactName; + } + + public String CompanyName + { + get + { + return companyNameValue; + } + set + { + companyNameValue = value; + } + } + + public String ContactName + { + get + { + return contactNameValue; + } + set + { + contactNameValue = value; + } + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs new file mode 100644 index 0000000000..447e41ecfb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/CS/lazyloading.cs @@ -0,0 +1,369 @@ +// +// +using System; +using System.Data; +using System.Data.SqlClient; +using System.Drawing; +using System.Windows.Forms; + +public class VirtualJustInTimeDemo : System.Windows.Forms.Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private Cache memoryCache; + + // Specify a connection string. Replace the given value with a + // valid connection string for a Northwind SQL Server sample + // database accessible to your system. + private string connectionString = + "Initial Catalog=NorthWind;Data Source=localhost;" + + "Integrated Security=SSPI;Persist Security Info=False"; + private string table = "Orders"; + + protected override void OnLoad(EventArgs e) + { + // Initialize the form. + this.AutoSize = true; + this.Controls.Add(this.dataGridView1); + this.Text = "DataGridView virtual-mode just-in-time demo"; + + // Complete the initialization of the DataGridView. + this.dataGridView1.Size = new Size(800, 250); + this.dataGridView1.Dock = DockStyle.Fill; + this.dataGridView1.VirtualMode = true; + this.dataGridView1.ReadOnly = true; + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToOrderColumns = false; + this.dataGridView1.SelectionMode = + DataGridViewSelectionMode.FullRowSelect; + this.dataGridView1.CellValueNeeded += new + DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded); + + // Create a DataRetriever and use it to create a Cache object + // and to initialize the DataGridView columns and rows. + try + { + DataRetriever retriever = + new DataRetriever(connectionString, table); + memoryCache = new Cache(retriever, 16); + foreach (DataColumn column in retriever.Columns) + { + dataGridView1.Columns.Add( + column.ColumnName, column.ColumnName); + } + this.dataGridView1.RowCount = retriever.RowCount; + } + catch (SqlException) + { + MessageBox.Show("Connection could not be established. " + + "Verify that the connection string is valid."); + Application.Exit(); + } + + // Adjust the column widths based on the displayed values. + this.dataGridView1.AutoResizeColumns( + DataGridViewAutoSizeColumnsMode.DisplayedCells); + + base.OnLoad(e); + } + + private void dataGridView1_CellValueNeeded(object sender, + DataGridViewCellValueEventArgs e) + { + e.Value = memoryCache.RetrieveElement(e.RowIndex, e.ColumnIndex); + } + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new VirtualJustInTimeDemo()); + } +} +// + +// +public interface IDataPageRetriever +{ + DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage); +} +// + +// +public class DataRetriever : IDataPageRetriever +{ + private string tableName; + private SqlCommand command; + + public DataRetriever(string connectionString, string tableName) + { + SqlConnection connection = new SqlConnection(connectionString); + connection.Open(); + command = connection.CreateCommand(); + this.tableName = tableName; + } + + private int rowCountValue = -1; + + public int RowCount + { + get + { + // Return the existing value if it has already been determined. + if (rowCountValue != -1) + { + return rowCountValue; + } + + // Retrieve the row count from the database. + command.CommandText = "SELECT COUNT(*) FROM " + tableName; + rowCountValue = (int)command.ExecuteScalar(); + return rowCountValue; + } + } + + private DataColumnCollection columnsValue; + + public DataColumnCollection Columns + { + get + { + // Return the existing value if it has already been determined. + if (columnsValue != null) + { + return columnsValue; + } + + // Retrieve the column information from the database. + command.CommandText = "SELECT * FROM " + tableName; + SqlDataAdapter adapter = new SqlDataAdapter(); + adapter.SelectCommand = command; + DataTable table = new DataTable(); + table.Locale = System.Globalization.CultureInfo.InvariantCulture; + adapter.FillSchema(table, SchemaType.Source); + columnsValue = table.Columns; + return columnsValue; + } + } + + private string commaSeparatedListOfColumnNamesValue = null; + + private string CommaSeparatedListOfColumnNames + { + get + { + // Return the existing value if it has already been determined. + if (commaSeparatedListOfColumnNamesValue != null) + { + return commaSeparatedListOfColumnNamesValue; + } + + // Store a list of column names for use in the + // SupplyPageOfData method. + System.Text.StringBuilder commaSeparatedColumnNames = + new System.Text.StringBuilder(); + bool firstColumn = true; + foreach (DataColumn column in Columns) + { + if (!firstColumn) + { + commaSeparatedColumnNames.Append(", "); + } + commaSeparatedColumnNames.Append(column.ColumnName); + firstColumn = false; + } + + commaSeparatedListOfColumnNamesValue = + commaSeparatedColumnNames.ToString(); + return commaSeparatedListOfColumnNamesValue; + } + } + + // Declare variables to be reused by the SupplyPageOfData method. + private string columnToSortBy; + private SqlDataAdapter adapter = new SqlDataAdapter(); + + public DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage) + { + // Store the name of the ID column. This column must contain unique + // values so the SQL below will work properly. + columnToSortBy ??= this.Columns[0].ColumnName; + + if (!this.Columns[columnToSortBy].Unique) + { + throw new InvalidOperationException(String.Format( + "Column {0} must contain unique values.", columnToSortBy)); + } + + // Retrieve the specified number of rows from the database, starting + // with the row specified by the lowerPageBoundary parameter. + command.CommandText = "Select Top " + rowsPerPage + " " + + CommaSeparatedListOfColumnNames + " From " + tableName + + " WHERE " + columnToSortBy + " NOT IN (SELECT TOP " + + lowerPageBoundary + " " + columnToSortBy + " From " + + tableName + " Order By " + columnToSortBy + + ") Order By " + columnToSortBy; + adapter.SelectCommand = command; + + DataTable table = new DataTable(); + table.Locale = System.Globalization.CultureInfo.InvariantCulture; + adapter.Fill(table); + return table; + } +} +// + +// +public class Cache +{ + private static int RowsPerPage; + + // Represents one page of data. + public struct DataPage + { + public DataTable table; + private int lowestIndexValue; + private int highestIndexValue; + + public DataPage(DataTable table, int rowIndex) + { + this.table = table; + lowestIndexValue = MapToLowerBoundary(rowIndex); + highestIndexValue = MapToUpperBoundary(rowIndex); + System.Diagnostics.Debug.Assert(lowestIndexValue >= 0); + System.Diagnostics.Debug.Assert(highestIndexValue >= 0); + } + + public int LowestIndex + { + get + { + return lowestIndexValue; + } + } + + public int HighestIndex + { + get + { + return highestIndexValue; + } + } + + public static int MapToLowerBoundary(int rowIndex) + { + // Return the lowest index of a page containing the given index. + return (rowIndex / RowsPerPage) * RowsPerPage; + } + + private static int MapToUpperBoundary(int rowIndex) + { + // Return the highest index of a page containing the given index. + return MapToLowerBoundary(rowIndex) + RowsPerPage - 1; + } + } + + private DataPage[] cachePages; + private IDataPageRetriever dataSupply; + + public Cache(IDataPageRetriever dataSupplier, int rowsPerPage) + { + dataSupply = dataSupplier; + Cache.RowsPerPage = rowsPerPage; + LoadFirstTwoPages(); + } + + // Sets the value of the element parameter if the value is in the cache. + private bool IfPageCached_ThenSetElement(int rowIndex, + int columnIndex, ref string element) + { + if (IsRowCachedInPage(0, rowIndex)) + { + element = cachePages[0].table + .Rows[rowIndex % RowsPerPage][columnIndex].ToString(); + return true; + } + else if (IsRowCachedInPage(1, rowIndex)) + { + element = cachePages[1].table + .Rows[rowIndex % RowsPerPage][columnIndex].ToString(); + return true; + } + + return false; + } + + public string RetrieveElement(int rowIndex, int columnIndex) + { + string element = null; + + if (IfPageCached_ThenSetElement(rowIndex, columnIndex, ref element)) + { + return element; + } + else + { + return RetrieveData_CacheIt_ThenReturnElement( + rowIndex, columnIndex); + } + } + + private void LoadFirstTwoPages() + { + cachePages = new DataPage[]{ + new DataPage(dataSupply.SupplyPageOfData( + DataPage.MapToLowerBoundary(0), RowsPerPage), 0), + new DataPage(dataSupply.SupplyPageOfData( + DataPage.MapToLowerBoundary(RowsPerPage), + RowsPerPage), RowsPerPage)}; + } + + private string RetrieveData_CacheIt_ThenReturnElement( + int rowIndex, int columnIndex) + { + // Retrieve a page worth of data containing the requested value. + DataTable table = dataSupply.SupplyPageOfData( + DataPage.MapToLowerBoundary(rowIndex), RowsPerPage); + + // Replace the cached page furthest from the requested cell + // with a new page containing the newly retrieved data. + cachePages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, rowIndex); + + return RetrieveElement(rowIndex, columnIndex); + } + + // Returns the index of the cached page most distant from the given index + // and therefore least likely to be reused. + private int GetIndexToUnusedPage(int rowIndex) + { + if (rowIndex > cachePages[0].HighestIndex && + rowIndex > cachePages[1].HighestIndex) + { + int offsetFromPage0 = rowIndex - cachePages[0].HighestIndex; + int offsetFromPage1 = rowIndex - cachePages[1].HighestIndex; + if (offsetFromPage0 < offsetFromPage1) + { + return 1; + } + return 0; + } + else + { + int offsetFromPage0 = cachePages[0].LowestIndex - rowIndex; + int offsetFromPage1 = cachePages[1].LowestIndex - rowIndex; + if (offsetFromPage0 < offsetFromPage1) + { + return 1; + } + return 0; + } + } + + // Returns a value indicating whether the given row index is contained + // in the given DataPage. + private bool IsRowCachedInPage(int pageNumber, int rowIndex) + { + return rowIndex <= cachePages[pageNumber].HighestIndex && + rowIndex >= cachePages[pageNumber].LowestIndex; + } +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/CS/collectionbound.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/CS/collectionbound.cs new file mode 100644 index 0000000000..4db7719194 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/CS/collectionbound.cs @@ -0,0 +1,131 @@ +// +using System; +using System.Windows.Forms; +// +public enum Title +{ + King, + Sir +}; +// +public class EnumsAndComboBox : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private BindingSource bindingSource1 = new BindingSource(); + + public EnumsAndComboBox() + { + this.Load += new System.EventHandler(EnumsAndComboBox_Load); + } + + // + private void EnumsAndComboBox_Load(object sender, System.EventArgs e) + { + // Populate the data source. + bindingSource1.Add(new Knight(Title.King, "Uther", true)); + bindingSource1.Add(new Knight(Title.King, "Arthur", true)); + bindingSource1.Add(new Knight(Title.Sir, "Mordred", false)); + bindingSource1.Add(new Knight(Title.Sir, "Gawain", true)); + bindingSource1.Add(new Knight(Title.Sir, "Galahad", true)); + + // Initialize the DataGridView. + dataGridView1.AutoGenerateColumns = false; + dataGridView1.AutoSize = true; + dataGridView1.DataSource = bindingSource1; + + dataGridView1.Columns.Add(CreateComboBoxWithEnums()); + + // Initialize and add a text box column. + DataGridViewColumn column = new DataGridViewTextBoxColumn(); + column.DataPropertyName = "Name"; + column.Name = "Knight"; + dataGridView1.Columns.Add(column); + + // Initialize and add a check box column. + column = new DataGridViewCheckBoxColumn(); + column.DataPropertyName = "GoodGuy"; + column.Name = "Good"; + dataGridView1.Columns.Add(column); + + // Initialize the form. + this.Controls.Add(dataGridView1); + this.AutoSize = true; + this.Text = "DataGridView object binding demo"; + } + + DataGridViewComboBoxColumn CreateComboBoxWithEnums() + { + DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn(); + combo.DataSource = Enum.GetValues(typeof(Title)); + combo.DataPropertyName = "Title"; + combo.Name = "Title"; + return combo; + } + #region "business object" + private class Knight + { + private string hisName; + private bool good; + private Title hisTitle; + + public Knight(Title title, string name, bool good) + { + hisTitle = title; + hisName = name; + this.good = good; + } + + public Knight() + { + hisTitle = Title.Sir; + hisName = ""; + good = true; + } + + public string Name + { + get + { + return hisName; + } + + set + { + hisName = value; + } + } + + public bool GoodGuy + { + get + { + return good; + } + set + { + good = value; + } + } + + public Title Title + { + get + { + return hisTitle; + } + set + { + hisTitle = value; + } + } + } + #endregion + // + + [STAThread] + public static void Main() + { + Application.Run(new EnumsAndComboBox()); + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/CS/datagridviewboundeditable.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/CS/datagridviewboundeditable.cs new file mode 100644 index 0000000000..ce7071d2f4 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/CS/datagridviewboundeditable.cs @@ -0,0 +1,110 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using System.Globalization; +using System.Windows.Forms; + +namespace WindowsFormsApp +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} +public class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private BindingSource bindingSource1 = new BindingSource(); + private SqlDataAdapter dataAdapter = new SqlDataAdapter(); + private Button reloadButton = new Button(); + private Button submitButton = new Button(); + + [STAThread()] + public static void Main() + { + Application.Run(new Form1()); + } + + // Initialize the form. + public Form1() + { + dataGridView1.Dock = DockStyle.Fill; + + reloadButton.Text = "Reload"; + submitButton.Text = "Submit"; + reloadButton.Click += new EventHandler(ReloadButton_Click); + submitButton.Click += new EventHandler(SubmitButton_Click); + + FlowLayoutPanel panel = new FlowLayoutPanel + { + Dock = DockStyle.Top, + AutoSize = true + }; + panel.Controls.AddRange(new Control[] { reloadButton, submitButton }); + + Controls.AddRange(new Control[] { dataGridView1, panel }); + Load += new EventHandler(Form1_Load); + Text = "DataGridView data binding and updating demo"; + } + + private void GetData(string selectCommand) + { + try + { + // Specify a connection string. + // Replace with the SQL Server for your Northwind sample database. + // Replace "Integrated Security=True" with user login information if necessary. + String connectionString = + "Data Source=;Initial Catalog=Northwind;" + + "Integrated Security=True"; + + // Create a new data adapter based on the specified query. + dataAdapter = new SqlDataAdapter(selectCommand, connectionString); + + // Create a command builder to generate SQL update, insert, and + // delete commands based on selectCommand. + SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); + + // Populate a new data table and bind it to the BindingSource. + DataTable table = new DataTable + { + Locale = CultureInfo.InvariantCulture + }; + dataAdapter.Fill(table); + bindingSource1.DataSource = table; + + // Resize the DataGridView columns to fit the newly loaded content. + dataGridView1.AutoResizeColumns( + DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); + } + catch (SqlException) + { + MessageBox.Show("To run this example, replace the value of the " + + "connectionString variable with a connection string that is " + + "valid for your system."); + } + } + + private void Form1_Load(object sender, EventArgs e) + { + // Bind the DataGridView to the BindingSource + // and load the data from the database. + dataGridView1.DataSource = bindingSource1; + GetData("select * from Customers"); + } + + private void ReloadButton_Click(object sender, EventArgs e) + { + // Reload the data from the database. + GetData(dataAdapter.SelectCommand.CommandText); + } + + private void SubmitButton_Click(object sender, EventArgs e) + { + // Update the database with changes. + dataAdapter.Update((DataTable)bindingSource1.DataSource); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/CS/datagridviewcalendarcolumn.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/CS/datagridviewcalendarcolumn.cs new file mode 100644 index 0000000000..39be3332bb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/CS/datagridviewcalendarcolumn.cs @@ -0,0 +1,310 @@ +// +// +using System; +using System.Windows.Forms; +// + +// +public class CalendarColumn : DataGridViewColumn +{ + public CalendarColumn() : base(new CalendarCell()) + { + } + + public override DataGridViewCell CellTemplate + { + get + { + return base.CellTemplate; + } + set + { + // Ensure that the cell used for the template is a CalendarCell. + if (value != null && + !value.GetType().IsAssignableFrom(typeof(CalendarCell))) + { + throw new InvalidCastException("Must be a CalendarCell"); + } + base.CellTemplate = value; + } + } +} +// + +// +public class CalendarCell : DataGridViewTextBoxCell +{ + + public CalendarCell() + : base() + { + // Use the short date format. + this.Style.Format = "d"; + } + + // + public override void InitializeEditingControl(int rowIndex, object + initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) + { + // Set the value of the editing control to the current cell value. + base.InitializeEditingControl(rowIndex, initialFormattedValue, + dataGridViewCellStyle); + CalendarEditingControl ctl = + DataGridView.EditingControl as CalendarEditingControl; + // Use the default row value when Value property is null. + if (this.Value == null) + { + ctl.Value = (DateTime)this.DefaultNewRowValue; + } + else + { + ctl.Value = (DateTime)this.Value; + } + } + // + + public override Type EditType + { + get + { + // Return the type of the editing control that CalendarCell uses. + return typeof(CalendarEditingControl); + } + } + + public override Type ValueType + { + get + { + // Return the type of the value that CalendarCell contains. + + return typeof(DateTime); + } + } + + public override object DefaultNewRowValue + { + get + { + // Use the current date and time as the default value. + return DateTime.Now; + } + } +} +// + +// +class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl +{ + DataGridView dataGridView; + private bool valueChanged = false; + int rowIndex; + + public CalendarEditingControl() + { + this.Format = DateTimePickerFormat.Short; + } + + // + // Implements the IDataGridViewEditingControl.EditingControlFormattedValue + // property. + public object EditingControlFormattedValue + { + get + { + return this.Value.ToShortDateString(); + } + set + { + if (value is String) + { + try + { + // This will throw an exception of the string is + // null, empty, or not in the format of a date. + this.Value = DateTime.Parse((String)value); + } + catch + { + // In the case of an exception, just use the + // default value so we're not left with a null + // value. + this.Value = DateTime.Now; + } + } + } + } + // + + // + // Implements the + // IDataGridViewEditingControl.GetEditingControlFormattedValue method. + public object GetEditingControlFormattedValue( + DataGridViewDataErrorContexts context) + { + return EditingControlFormattedValue; + } + // + + // + // Implements the + // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. + public void ApplyCellStyleToEditingControl( + DataGridViewCellStyle dataGridViewCellStyle) + { + this.Font = dataGridViewCellStyle.Font; + this.CalendarForeColor = dataGridViewCellStyle.ForeColor; + this.CalendarMonthBackground = dataGridViewCellStyle.BackColor; + } + // + + // + // Implements the IDataGridViewEditingControl.EditingControlRowIndex + // property. + public int EditingControlRowIndex + { + get + { + return rowIndex; + } + set + { + rowIndex = value; + } + } + // + + // + // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey + // method. + public bool EditingControlWantsInputKey( + Keys key, bool dataGridViewWantsInputKey) + { + // Let the DateTimePicker handle the keys listed. + switch (key & Keys.KeyCode) + { + case Keys.Left: + case Keys.Up: + case Keys.Down: + case Keys.Right: + case Keys.Home: + case Keys.End: + case Keys.PageDown: + case Keys.PageUp: + return true; + default: + return !dataGridViewWantsInputKey; + } + } + // + + // + // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit + // method. + public void PrepareEditingControlForEdit(bool selectAll) + { + // No preparation needs to be done. + } + // + + // + // Implements the IDataGridViewEditingControl + // .RepositionEditingControlOnValueChange property. + public bool RepositionEditingControlOnValueChange + { + get + { + return false; + } + } + // + + // + // Implements the IDataGridViewEditingControl + // .EditingControlDataGridView property. + public DataGridView EditingControlDataGridView + { + get + { + return dataGridView; + } + set + { + dataGridView = value; + } + } + // + + // + // Implements the IDataGridViewEditingControl + // .EditingControlValueChanged property. + public bool EditingControlValueChanged + { + get + { + return valueChanged; + } + set + { + valueChanged = value; + } + } + // + + // + // Implements the IDataGridViewEditingControl + // .EditingPanelCursor property. + public Cursor EditingPanelCursor + { + get + { + return base.Cursor; + } + } + // + + // + protected override void OnValueChanged(EventArgs eventargs) + { + // Notify the DataGridView that the contents of the cell + // have changed. + valueChanged = true; + this.EditingControlDataGridView.NotifyCurrentCellDirty(true); + base.OnValueChanged(eventargs); + } + // +} +// + +// +public class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(this.dataGridView1); + this.Load += new EventHandler(Form1_Load); + this.Text = "DataGridView calendar column demo"; + } + + private void Form1_Load(object sender, EventArgs e) + { + CalendarColumn col = new CalendarColumn(); + this.dataGridView1.Columns.Add(col); + this.dataGridView1.RowCount = 5; + foreach (DataGridViewRow row in this.dataGridView1.Rows) + { + row.Cells[0].Value = DateTime.Now; + } + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/CS/datagridviewcell.tooltiptext.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/CS/datagridviewcell.tooltiptext.cs new file mode 100644 index 0000000000..99dc0b8202 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/CS/datagridviewcell.tooltiptext.cs @@ -0,0 +1,78 @@ +using System; +using System.Windows.Forms; + +class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + this.dataGridView1.Dock = DockStyle.Fill; + // Set the column header names. + this.dataGridView1.ColumnCount = 5; + this.dataGridView1.Columns[0].Name = "Recipe"; + this.dataGridView1.Columns[1].Name = "Category"; + this.dataGridView1.Columns[2].Name = "Main Ingredients"; + this.dataGridView1.Columns[3].Name = "Last Fixed"; + this.dataGridView1.Columns[4].Name = "Rating"; + + // Populate the rows. + object[] row1 = new object[]{"Meatloaf", + "Main Dish", "ground beef", new DateTime(2000, 3, 23), "*"}; + object[] row2 = new object[]{"Key Lime Pie", + "Dessert", "lime juice, evaporated milk", new DateTime(2002, 4, 12), "****"}; + object[] row3 = new object[]{"Orange-Salsa Pork Chops", + "Main Dish", "pork chops, salsa, orange juice", new DateTime(2000, 8, 9), "****"}; + object[] row4 = new object[]{"Black Bean and Rice Salad", + "Salad", "black beans, brown rice", new DateTime(1999, 5, 7), "****"}; + object[] row5 = new object[]{"Chocolate Cheesecake", + "Dessert", "cream cheese", new DateTime(2003, 3, 12), "***"}; + object[] row6 = new object[]{"Black Bean Dip", "Appetizer", + "black beans, sour cream", new DateTime(2003, 12, 23), "***"}; + object[] rows = new object[] { row1, row2, row3, row4, row5, row6 }; + + foreach (object[] rowArray in rows) + { + this.dataGridView1.Rows.Add(rowArray); + } + this.Controls.Add(this.dataGridView1); + this.Text = "DataGridView cell ToolTip demo"; + this.dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting); + } + + // + // Sets the ToolTip text for cells in the Rating column. + void dataGridView1_CellFormatting(object sender, + DataGridViewCellFormattingEventArgs e) + { + if ( (e.ColumnIndex == this.dataGridView1.Columns["Rating"].Index) + && e.Value != null ) + { + DataGridViewCell cell = + this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; + if (e.Value.Equals("*")) + { + cell.ToolTipText = "very bad"; + } + else if (e.Value.Equals("**")) + { + cell.ToolTipText = "bad"; + } + else if (e.Value.Equals("***")) + { + cell.ToolTipText = "good"; + } + else if (e.Value.Equals("****")) + { + cell.ToolTipText = "very good"; + } + } + } + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/CS/form1.cs new file mode 100644 index 0000000000..9ae21a3855 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/CS/form1.cs @@ -0,0 +1,92 @@ +// +#region Using directives + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.SqlClient; +using System.Drawing; +using System.Windows.Forms; + +#endregion + +class Form1 : Form +{ + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + private DataGridView dataGridView1 = new DataGridView(); + + public Form1() + { + this.dataGridView1.Dock = DockStyle.Fill; + DataTable data = new DataTable(); + data.Locale = System.Globalization.CultureInfo.InvariantCulture; + new SqlDataAdapter( + "select * from customers", + "data source=localhost;initial catalog=northwind;" + + "integrated security=sspi") + .Fill(data); + this.dataGridView1.DataSource = data; + this.Controls.Add(this.dataGridView1); + this.Text = "DataGridView.CellPainting demo"; + } + + protected override void OnLoad(EventArgs e) + { + this.dataGridView1.CellPainting += new + DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting); + base.OnLoad(e); + } + + // + private void dataGridView1_CellPainting(object sender, + System.Windows.Forms.DataGridViewCellPaintingEventArgs e) + { + if (this.dataGridView1.Columns["ContactName"].Index == + e.ColumnIndex && e.RowIndex >= 0) + { + Rectangle newRect = new Rectangle(e.CellBounds.X + 1, + e.CellBounds.Y + 1, e.CellBounds.Width - 4, + e.CellBounds.Height - 4); + + using ( + Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor), + backColorBrush = new SolidBrush(e.CellStyle.BackColor)) + { + using (Pen gridLinePen = new Pen(gridBrush)) + { + // Erase the cell. + e.Graphics.FillRectangle(backColorBrush, e.CellBounds); + + // Draw the grid lines (only the right and bottom lines; + // DataGridView takes care of the others). + e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, + e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, + e.CellBounds.Bottom - 1); + e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, + e.CellBounds.Top, e.CellBounds.Right - 1, + e.CellBounds.Bottom); + + // Draw the inset highlight box. + e.Graphics.DrawRectangle(Pens.Blue, newRect); + + // Draw the text content of the cell, ignoring alignment. + if (e.Value != null) + { + e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, + Brushes.Crimson, e.CellBounds.X + 2, + e.CellBounds.Y + 2, StringFormat.GenericDefault); + } + e.Handled = true; + } + } + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/CS/datagridviewclipboarddemo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/CS/datagridviewclipboarddemo.cs new file mode 100644 index 0000000000..af1dd263a8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/CS/datagridviewclipboarddemo.cs @@ -0,0 +1,79 @@ +// +using System; +using System.Windows.Forms; + +public class Form1 : Form +{ + private DataGridView DataGridView1 = new DataGridView(); + private Button CopyPasteButton = new Button(); + private TextBox TextBox1 = new TextBox(); + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + this.DataGridView1.AllowUserToAddRows = false; + this.DataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(this.DataGridView1); + + this.CopyPasteButton.Text = "copy/paste selected cells"; + this.CopyPasteButton.Dock = DockStyle.Top; + this.CopyPasteButton.Click += new EventHandler(CopyPasteButton_Click); + this.Controls.Add(this.CopyPasteButton); + + this.TextBox1.Multiline = true; + this.TextBox1.Height = 100; + this.TextBox1.Dock = DockStyle.Bottom; + this.Controls.Add(this.TextBox1); + + this.Load += new EventHandler(Form1_Load); + this.Text = "DataGridView Clipboard demo"; + } + + // + private void Form1_Load(object sender, System.EventArgs e) + { + // Initialize the DataGridView control. + this.DataGridView1.ColumnCount = 5; + this.DataGridView1.Rows.Add(new string[] { "A", "B", "C", "D", "E" }); + this.DataGridView1.Rows.Add(new string[] { "F", "G", "H", "I", "J" }); + this.DataGridView1.Rows.Add(new string[] { "K", "L", "M", "N", "O" }); + this.DataGridView1.Rows.Add(new string[] { "P", "Q", "R", "S", "T" }); + this.DataGridView1.Rows.Add(new string[] { "U", "V", "W", "X", "Y" }); + this.DataGridView1.AutoResizeColumns(); + // + this.DataGridView1.ClipboardCopyMode = + DataGridViewClipboardCopyMode.EnableWithoutHeaderText; + // + } + + // + private void CopyPasteButton_Click(object sender, System.EventArgs e) + { + if (this.DataGridView1 + .GetCellCount(DataGridViewElementStates.Selected) > 0) + { + try + { + // Add the selection to the clipboard. + Clipboard.SetDataObject( + this.DataGridView1.GetClipboardContent()); + + // Replace the text box contents with the clipboard text. + this.TextBox1.Text = Clipboard.GetText(); + } + catch (System.Runtime.InteropServices.ExternalException) + { + this.TextBox1.Text = + "The Clipboard could not be accessed. Please try again."; + } + } + } + // + // +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs new file mode 100644 index 0000000000..3d34895d8a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/CS/form1.cs @@ -0,0 +1,210 @@ +// +using System; +using System.Text; +using System.Collections.Generic; +using System.Windows.Forms; + +// +public class Form1 : Form +{ + private List employees = new List(); + private List tasks = new List(); + private Button reportButton = new Button(); + private DataGridView dataGridView1 = new DataGridView(); + + [STAThread] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + dataGridView1.Dock = DockStyle.Fill; + dataGridView1.AutoSizeColumnsMode = + DataGridViewAutoSizeColumnsMode.AllCells; + reportButton.Text = "Generate Report"; + reportButton.Dock = DockStyle.Top; + reportButton.Click += new EventHandler(reportButton_Click); + + Controls.Add(dataGridView1); + Controls.Add(reportButton); + Load += new EventHandler(Form1_Load); + Text = "DataGridViewComboBoxColumn Demo"; + } + + // Initializes the data source and populates the DataGridView control. + private void Form1_Load(object sender, EventArgs e) + { + PopulateLists(); + dataGridView1.AutoGenerateColumns = false; + dataGridView1.DataSource = tasks; + AddColumns(); + } + + // Populates the employees and tasks lists. + private void PopulateLists() + { + employees.Add(new Employee("Harry")); + employees.Add(new Employee("Sally")); + employees.Add(new Employee("Roy")); + employees.Add(new Employee("Pris")); + tasks.Add(new Task(1, employees[1])); + tasks.Add(new Task(2)); + tasks.Add(new Task(3, employees[2])); + tasks.Add(new Task(4)); + } + + // Configures columns for the DataGridView control. + private void AddColumns() + { + DataGridViewTextBoxColumn idColumn = + new DataGridViewTextBoxColumn(); + idColumn.Name = "Task"; + idColumn.DataPropertyName = "Id"; + idColumn.ReadOnly = true; + + // + DataGridViewComboBoxColumn assignedToColumn = + new DataGridViewComboBoxColumn(); + + // Populate the combo box drop-down list with Employee objects. + foreach (Employee e in employees) assignedToColumn.Items.Add(e); + + // Add "unassigned" to the drop-down list and display it for + // empty AssignedTo values or when the user presses CTRL+0. + assignedToColumn.Items.Add("unassigned"); + assignedToColumn.DefaultCellStyle.NullValue = "unassigned"; + // + + assignedToColumn.Name = "Assigned To"; + assignedToColumn.DataPropertyName = "AssignedTo"; + assignedToColumn.AutoComplete = true; + // + assignedToColumn.DisplayMember = "Name"; + assignedToColumn.ValueMember = "Self"; + // + + // Add a button column. + DataGridViewButtonColumn buttonColumn = + new DataGridViewButtonColumn(); + buttonColumn.HeaderText = ""; + buttonColumn.Name = "Status Request"; + buttonColumn.Text = "Request Status"; + buttonColumn.UseColumnTextForButtonValue = true; + + dataGridView1.Columns.Add(idColumn); + dataGridView1.Columns.Add(assignedToColumn); + dataGridView1.Columns.Add(buttonColumn); + + // Add a CellClick handler to handle clicks in the button column. + dataGridView1.CellClick += + new DataGridViewCellEventHandler(dataGridView1_CellClick); + } + + // Reports on task assignments. + private void reportButton_Click(object sender, EventArgs e) + { + StringBuilder report = new StringBuilder(); + foreach (Task t in tasks) + { + String assignment = + t.AssignedTo == null ? + "unassigned" : "assigned to " + t.AssignedTo.Name; + report.AppendFormat("Task {0} is {1}.", t.Id, assignment); + report.Append(Environment.NewLine); + } + MessageBox.Show(report.ToString(), "Task Assignments"); + } + + // Calls the Employee.RequestStatus method. + void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) + { + // Ignore clicks that are not on button cells. + if (e.RowIndex < 0 || e.ColumnIndex != + dataGridView1.Columns["Status Request"].Index) return; + + // Retrieve the task ID. + Int32 taskID = (Int32)dataGridView1[0, e.RowIndex].Value; + + // + // Retrieve the Employee object from the "Assigned To" cell. + Employee assignedTo = dataGridView1.Rows[e.RowIndex] + .Cells["Assigned To"].Value as Employee; + // + + // Request status through the Employee object if present. + if (assignedTo != null) + { + assignedTo.RequestStatus(taskID); + } + else + { + MessageBox.Show(String.Format( + "Task {0} is unassigned.", taskID), "Status Request"); + } + } +} +// + +// +public class Task +{ + public Task(Int32 id) + { + idValue = id; + } + + public Task(Int32 id, Employee assignedTo) + { + idValue = id; + assignedToValue = assignedTo; + } + + private Int32 idValue; + public Int32 Id + { + get { return idValue; } + set { idValue = value; } + } + + private Employee assignedToValue; + public Employee AssignedTo + { + get { return assignedToValue; } + set { assignedToValue = value; } + } +} +// + +// +public class Employee +{ + public Employee(String name) + { + nameValue = name; + } + + private String nameValue; + public String Name + { + get { return nameValue; } + set { nameValue = value; } + } + + // + public Employee Self + { + get { return this; } + } + // + + public void RequestStatus(Int32 taskID) + { + MessageBox.Show(String.Format( + "Status for task {0} has been requested from {1}.", + taskID, nameValue), "Status Request"); + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/cs/customFormatting.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/cs/customFormatting.cs new file mode 100644 index 0000000000..f8a8486797 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/cs/customFormatting.cs @@ -0,0 +1,102 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +public class Form1 : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private Bitmap highPriImage; + private Bitmap mediumPriImage; + private Bitmap lowPriImage; + + // + public Form1() + { + // Initialize the images. + try + { + highPriImage = new Bitmap("highPri.bmp"); + mediumPriImage = new Bitmap("mediumPri.bmp"); + lowPriImage = new Bitmap("lowPri.bmp"); + } + catch (ArgumentException) + { + MessageBox.Show("The Priority column requires Bitmap images " + + "named highPri.bmp, mediumPri.bmp, and lowPri.bmp " + + "residing in the same directory as the executable file."); + } + + // Initialize the DataGridView. + dataGridView1.Dock = DockStyle.Fill; + dataGridView1.AllowUserToAddRows = false; + dataGridView1.Columns.AddRange( + new DataGridViewTextBoxColumn(), + new DataGridViewImageColumn()); + dataGridView1.Columns[0].Name = "Balance"; + dataGridView1.Columns[1].Name = "Priority"; + dataGridView1.Rows.Add("-100", "high"); + dataGridView1.Rows.Add("0", "medium"); + dataGridView1.Rows.Add("100", "low"); + dataGridView1.CellFormatting += + new System.Windows.Forms.DataGridViewCellFormattingEventHandler( + this.dataGridView1_CellFormatting); + this.Controls.Add(dataGridView1); + } + // + + // + // Changes how cells are displayed depending on their columns and values. + private void dataGridView1_CellFormatting(object sender, + System.Windows.Forms.DataGridViewCellFormattingEventArgs e) + { + // + // Set the background to red for negative values in the Balance column. + if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance")) + { + Int32 intValue; + if (Int32.TryParse((String)e.Value, out intValue) && + (intValue < 0)) + { + e.CellStyle.BackColor = Color.Red; + e.CellStyle.SelectionBackColor = Color.DarkRed; + } + } + // + + // + // Replace string values in the Priority column with images. + if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Priority")) + { + // Ensure that the value is a string. + String stringValue = e.Value as string; + if (stringValue == null) return; + + // Set the cell ToolTip to the text value. + DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex]; + cell.ToolTipText = stringValue; + + // Replace the string value with the image value. + switch (stringValue) + { + case "high": + e.Value = highPriImage; + break; + case "medium": + e.Value = mediumPriImage; + break; + case "low": + e.Value = lowPriImage; + break; + } + } + // + } + // + + public static void Main() + { + Application.Run(new Form1()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs new file mode 100644 index 0000000000..9c27943e87 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/CS/datavalidation.cs @@ -0,0 +1,95 @@ +// +// +using System; +using System.Data; +using System.Data.SqlClient; +using System.Windows.Forms; + +public class Form1 : System.Windows.Forms.Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private BindingSource bindingSource1 = new BindingSource(); + + public Form1() + { + // Initialize the form. + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(dataGridView1); + this.Load += new EventHandler(Form1_Load); + this.Text = "DataGridView validation demo (disallows empty CompanyName)"; + } + // + + // + private void Form1_Load(System.Object sender, System.EventArgs e) + { + // Attach DataGridView events to the corresponding event handlers. + this.dataGridView1.CellValidating += new + DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); + this.dataGridView1.CellEndEdit += new + DataGridViewCellEventHandler(dataGridView1_CellEndEdit); + + // Initialize the BindingSource and bind the DataGridView to it. + bindingSource1.DataSource = GetData("select * from Customers"); + this.dataGridView1.DataSource = bindingSource1; + this.dataGridView1.AutoResizeColumns( + DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); + } + // + + // + private void dataGridView1_CellValidating(object sender, + DataGridViewCellValidatingEventArgs e) + { + string headerText = + dataGridView1.Columns[e.ColumnIndex].HeaderText; + + // Abort validation if cell is not in the CompanyName column. + if (!headerText.Equals("CompanyName")) return; + + // Confirm that the cell is not empty. + if (string.IsNullOrEmpty(e.FormattedValue.ToString())) + { + dataGridView1.Rows[e.RowIndex].ErrorText = + "Company Name must not be empty"; + e.Cancel = true; + } + } + + // + void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) + { + // Clear the row error in case the user presses ESC. + dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; + } + // + // + + // + private static DataTable GetData(string selectCommand) + { + string connectionString = + "Integrated Security=SSPI;Persist Security Info=False;" + + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096"; + + // Connect to the database and fill a data table. + SqlDataAdapter adapter = + new SqlDataAdapter(selectCommand, connectionString); + DataTable data = new DataTable(); + data.Locale = System.Globalization.CultureInfo.InvariantCulture; + adapter.Fill(data); + + return data; + } + // + + // + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/CS/fillcolumns.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/CS/fillcolumns.cs new file mode 100644 index 0000000000..cfc0660816 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/CS/fillcolumns.cs @@ -0,0 +1,230 @@ +// +using System; +using System.ComponentModel; +using System.Reflection; +using System.Windows.Forms; + +public class Form1 : Form +{ + [STAThread] + public static void Main() + { + Application.Run(new Form1()); + } + + private DataGridView dataGridView1 = new DataGridView(); + + public Form1() + { + dataGridView1.Dock = DockStyle.Fill; + Controls.Add(dataGridView1); + InitializeDataGridView(); + Width *= 2; + Text = "Column Fill-Mode Demo"; + } + + private void InitializeDataGridView() + { + // Add columns to the DataGridView, binding them to the + // specified DataGridViewColumn properties. + AddReadOnlyColumn("HeaderText", "Column"); + AddColumn("AutoSizeMode"); + AddColumn("FillWeight"); + AddColumn("MinimumWidth"); + AddColumn("Width"); + + // Bind the DataGridView to its own Columns collection. + dataGridView1.AutoGenerateColumns = false; + dataGridView1.DataSource = dataGridView1.Columns; + + // Configure the DataGridView so that users can manually change + // only the column widths, which are set to fill mode. + dataGridView1.AllowUserToAddRows = false; + dataGridView1.AllowUserToDeleteRows = false; + dataGridView1.AllowUserToResizeRows = false; + dataGridView1.RowHeadersWidthSizeMode = + DataGridViewRowHeadersWidthSizeMode.DisableResizing; + dataGridView1.ColumnHeadersHeightSizeMode = + DataGridViewColumnHeadersHeightSizeMode.DisableResizing; + dataGridView1.AutoSizeColumnsMode = + DataGridViewAutoSizeColumnsMode.Fill; + + // Configure the top left header cell as a reset button. + dataGridView1.TopLeftHeaderCell.Value = "reset"; + dataGridView1.TopLeftHeaderCell.Style.ForeColor = + System.Drawing.Color.Blue; + + // Add handlers to DataGridView events. + dataGridView1.CellClick += + new DataGridViewCellEventHandler(dataGridView1_CellClick); + dataGridView1.ColumnWidthChanged += new + DataGridViewColumnEventHandler(dataGridView1_ColumnWidthChanged); + dataGridView1.CurrentCellDirtyStateChanged += + new EventHandler(dataGridView1_CurrentCellDirtyStateChanged); + dataGridView1.DataError += + new DataGridViewDataErrorEventHandler(dataGridView1_DataError); + dataGridView1.CellEndEdit += + new DataGridViewCellEventHandler(dataGridView1_CellEndEdit); + dataGridView1.CellValueChanged += + new DataGridViewCellEventHandler(dataGridView1_CellValueChanged); + } + + private void AddReadOnlyColumn(String dataPropertyName, String columnName) + { + AddColumn(typeof(DataGridViewColumn), dataPropertyName, true, + columnName); + } + + private void AddColumn(String dataPropertyName) + { + AddColumn(typeof(DataGridViewColumn), dataPropertyName, false, + dataPropertyName); + } + + // + // Adds a column to the DataGridView control, binding it to specified + // property of the specified type and optionally making it read-only. + private void AddColumn( + Type type, + String dataPropertyName, + Boolean readOnly, + String columnName) + { + // Retrieve information about the property through reflection. + PropertyInfo property = type.GetProperty(dataPropertyName); + + // Confirm that the property exists and is accessible. + if (property == null) throw new ArgumentException("No accessible " + + dataPropertyName + " property was found in the " + type.Name + " type."); + + // Confirm that the property is browsable. + BrowsableAttribute[] browsables = (BrowsableAttribute[]) + property.GetCustomAttributes(typeof(BrowsableAttribute), false); + if (browsables.Length > 0 && !browsables[0].Browsable) + { + throw new ArgumentException("The " + dataPropertyName + " property has a " + + "Browsable(false) attribute, and therefore cannot be bound."); + } + + // Create and initialize a column, using a combo box column for + // enumeration properties, a check box column for Boolean properties, + // and a text box column otherwise. + DataGridViewColumn column; + Type valueType = property.PropertyType; + if (valueType.IsEnum) + { + column = new DataGridViewComboBoxColumn(); + + // Populate the drop-down list with the enumeration values. + ((DataGridViewComboBoxColumn)column).DataSource + = Enum.GetValues(valueType); + } + else if (valueType.Equals(typeof(Boolean))) + { + column = new DataGridViewCheckBoxColumn(); + } + else + { + column = new DataGridViewTextBoxColumn(); + } + + // Initialize and bind the column. + column.ValueType = valueType; + column.Name = columnName; + column.DataPropertyName = dataPropertyName; + column.ReadOnly = readOnly; + + // Add the column to the control. + dataGridView1.Columns.Add(column); + } + // + + // + private void ResetDataGridView() + { + dataGridView1.CancelEdit(); + dataGridView1.Columns.Clear(); + dataGridView1.DataSource = null; + InitializeDataGridView(); + } + // + + private void dataGridView1_CellClick( + object sender, DataGridViewCellEventArgs e) + { + if (e.ColumnIndex == -1 && e.RowIndex == -1) + { + ResetDataGridView(); + } + } + + private void dataGridView1_ColumnWidthChanged( + object sender, DataGridViewColumnEventArgs e) + { + // Invalidate the row corresponding to the column that changed + // to ensure that the FillWeight and Width entries are updated. + dataGridView1.InvalidateRow(e.Column.Index); + } + + private void dataGridView1_CurrentCellDirtyStateChanged( + object sender, EventArgs e) + { + // For combo box and check box cells, commit any value change as soon + // as it is made rather than waiting for the focus to leave the cell. + if (!dataGridView1.CurrentCell.OwningColumn.GetType() + .Equals(typeof(DataGridViewTextBoxColumn))) + { + dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); + } + } + + private void dataGridView1_DataError( + object sender, DataGridViewDataErrorEventArgs e) + { + if (e.Exception == null) return; + + // If the user-specified value is invalid, cancel the change + // and display the error icon in the row header. + if ((e.Context & DataGridViewDataErrorContexts.Commit) != 0 && + (typeof(FormatException).IsAssignableFrom(e.Exception.GetType()) || + typeof(ArgumentException).IsAssignableFrom(e.Exception.GetType()))) + { + dataGridView1.Rows[e.RowIndex].ErrorText = + "The specified value is invalid."; + e.Cancel = true; + } + else + { + // Rethrow any exceptions that aren't related to the user input. + e.ThrowException = true; + } + } + + private void dataGridView1_CellEndEdit( + object sender, DataGridViewCellEventArgs e) + { + // Ensure that the error icon in the row header is hidden. + dataGridView1.Rows[e.RowIndex].ErrorText = ""; + } + + private void dataGridView1_CellValueChanged( + object sender, DataGridViewCellEventArgs e) + { + // Retrieve the property to change. + String nameOfPropertyToChange = + dataGridView1.Columns[e.ColumnIndex].Name; + PropertyInfo propertyToChange = + typeof(DataGridViewColumn).GetProperty(nameOfPropertyToChange); + + // Retrieve the column to change. + String nameOfColumnToChange = + (String)dataGridView1["Column", e.RowIndex].Value; + DataGridViewColumn columnToChange = + dataGridView1.Columns[nameOfColumnToChange]; + + // Use reflection to update the value of the column property. + propertyToChange.SetValue(columnToChange, + dataGridView1[nameOfPropertyToChange, e.RowIndex].Value, null); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/CS/form1.cs new file mode 100644 index 0000000000..ac46ef0603 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/CS/form1.cs @@ -0,0 +1,135 @@ +// +#region Using directives + +using System; +using System.Drawing; +using System.Windows.Forms; + +#endregion + +class Form1 : Form +{ + private DataGridView DataGridView1 = new DataGridView(); + private FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel(); + private Button Button1 = new Button(); + private RadioButton RadioButton1 = new RadioButton(); + private RadioButton RadioButton2 = new RadioButton(); + + // Establish the main entry point for the application. + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + // Initialize the form. + // This code can be replaced with designer generated code. + AutoSize = true; + Text = "DataGridView IComparer sort demo"; + + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; + FlowLayoutPanel1.Location = new System.Drawing.Point( 304, 0 ); + FlowLayoutPanel1.AutoSize = true; + + FlowLayoutPanel1.Controls.Add( RadioButton1 ); + FlowLayoutPanel1.Controls.Add( RadioButton2 ); + FlowLayoutPanel1.Controls.Add( Button1 ); + + Button1.Text = "Sort"; + RadioButton1.Text = "Ascending"; + RadioButton2.Text = "Descending"; + RadioButton1.Checked = true; + + Controls.Add( FlowLayoutPanel1 ); + Controls.Add( DataGridView1 ); + } + + protected override void OnLoad( EventArgs e ) + { + PopulateDataGridView(); + Button1.Click += new EventHandler(Button1_Click); + + base.OnLoad( e ); + } + + // Replace this with your own code to populate the DataGridView. + private void PopulateDataGridView() + { + + DataGridView1.Size = new Size(300, 300); + + // Add columns to the DataGridView. + DataGridView1.ColumnCount = 2; + + // Set the properties of the DataGridView columns. + DataGridView1.Columns[0].Name = "First"; + DataGridView1.Columns[1].Name = "Last"; + DataGridView1.Columns["First"].HeaderText = "First Name"; + DataGridView1.Columns["Last"].HeaderText = "Last Name"; + DataGridView1.Columns["First"].SortMode = + DataGridViewColumnSortMode.Programmatic; + DataGridView1.Columns["Last"].SortMode = + DataGridViewColumnSortMode.Programmatic; + + // Add rows of data to the DataGridView. + DataGridView1.Rows.Add(new string[] { "Peter", "Parker" }); + DataGridView1.Rows.Add(new string[] { "James", "Jameson" }); + DataGridView1.Rows.Add(new string[] { "May", "Parker" }); + DataGridView1.Rows.Add(new string[] { "Mary", "Watson" }); + DataGridView1.Rows.Add(new string[] { "Eddie", "Brock" }); + } + + // + private void Button1_Click( object sender, EventArgs e ) + { + if ( RadioButton1.Checked == true ) + { + DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) ); + } + else if ( RadioButton2.Checked == true ) + { + DataGridView1.Sort( new RowComparer( SortOrder.Descending ) ); + } + } + + private class RowComparer : System.Collections.IComparer + { + private static int sortOrderModifier = 1; + + public RowComparer(SortOrder sortOrder) + { + if (sortOrder == SortOrder.Descending) + { + sortOrderModifier = -1; + } + else if (sortOrder == SortOrder.Ascending) + { + sortOrderModifier = 1; + } + } + + public int Compare(object x, object y) + { + DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x; + DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y; + + // Try to sort based on the Last Name column. + int CompareResult = System.String.Compare( + DataGridViewRow1.Cells[1].Value.ToString(), + DataGridViewRow2.Cells[1].Value.ToString()); + + // If the Last Names are equal, sort based on the First Name. + if ( CompareResult == 0 ) + { + CompareResult = System.String.Compare( + DataGridViewRow1.Cells[0].Value.ToString(), + DataGridViewRow2.Cells[0].Value.ToString()); + } + return CompareResult * sortOrderModifier; + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs new file mode 100644 index 0000000000..7818ab8ba5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/CS/masterdetails.cs @@ -0,0 +1,112 @@ +// +// +using System; +using System.Data; +using System.Data.SqlClient; +using System.Windows.Forms; + +public class Form1 : System.Windows.Forms.Form +{ + private DataGridView masterDataGridView = new DataGridView(); + private BindingSource masterBindingSource = new BindingSource(); + private DataGridView detailsDataGridView = new DataGridView(); + private BindingSource detailsBindingSource = new BindingSource(); + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + // Initializes the form. + public Form1() + { + masterDataGridView.Dock = DockStyle.Fill; + detailsDataGridView.Dock = DockStyle.Fill; + + SplitContainer splitContainer1 = new SplitContainer(); + splitContainer1.Dock = DockStyle.Fill; + splitContainer1.Orientation = Orientation.Horizontal; + splitContainer1.Panel1.Controls.Add(masterDataGridView); + splitContainer1.Panel2.Controls.Add(detailsDataGridView); + + this.Controls.Add(splitContainer1); + this.Load += new System.EventHandler(Form1_Load); + this.Text = "DataGridView master/detail demo"; + } + // + + // + private void Form1_Load(object sender, System.EventArgs e) + { + // Bind the DataGridView controls to the BindingSource + // components and load the data from the database. + masterDataGridView.DataSource = masterBindingSource; + detailsDataGridView.DataSource = detailsBindingSource; + GetData(); + + // Resize the master DataGridView columns to fit the newly loaded data. + masterDataGridView.AutoResizeColumns(); + + // Configure the details DataGridView so that its columns automatically + // adjust their widths when the data changes. + detailsDataGridView.AutoSizeColumnsMode = + DataGridViewAutoSizeColumnsMode.AllCells; + } + // + + // + private void GetData() + { + try + { + // Specify a connection string. Replace the given value with a + // valid connection string for a Northwind SQL Server sample + // database accessible to your system. + String connectionString = + "Integrated Security=SSPI;Persist Security Info=False;" + + "Initial Catalog=Northwind;Data Source=localhost"; + SqlConnection connection = new SqlConnection(connectionString); + + // Create a DataSet. + DataSet data = new DataSet(); + data.Locale = System.Globalization.CultureInfo.InvariantCulture; + + // Add data from the Customers table to the DataSet. + SqlDataAdapter masterDataAdapter = new + SqlDataAdapter("select * from Customers", connection); + masterDataAdapter.Fill(data, "Customers"); + + // Add data from the Orders table to the DataSet. + SqlDataAdapter detailsDataAdapter = new + SqlDataAdapter("select * from Orders", connection); + detailsDataAdapter.Fill(data, "Orders"); + + // Establish a relationship between the two tables. + DataRelation relation = new DataRelation("CustomersOrders", + data.Tables["Customers"].Columns["CustomerID"], + data.Tables["Orders"].Columns["CustomerID"]); + data.Relations.Add(relation); + + // Bind the master data connector to the Customers table. + masterBindingSource.DataSource = data; + masterBindingSource.DataMember = "Customers"; + + // Bind the details data connector to the master data connector, + // using the DataRelation name to filter the information in the + // details table based on the current row in the master table. + detailsBindingSource.DataSource = masterBindingSource; + detailsBindingSource.DataMember = "CustomersOrders"; + } + catch (SqlException) + { + MessageBox.Show("To run this example, replace the value of the " + + "connectionString variable with a connection string that is " + + "valid for your system."); + } + } + // + // +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs new file mode 100644 index 0000000000..04b54fcf74 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/CS/datagridviewmisc.cs @@ -0,0 +1,475 @@ +// This file is for miscellaneous, tiny snippets that do not need to exist within a wider scope. +// Do not wrap the entire file in a snippet tag for use in any topic. + +#region Using directives + +using System; +using System.Data; +//using System.Data.SqlClient; +using System.Drawing; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; +using System.Windows.Forms; + +#endregion + +class DataGridViewMisc : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + + public DataGridViewMisc() + { + dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete; + } + + [STAThreadAttribute()] + public static void Main() + { + } + + // How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control + // + private void CreateUnboundButtonColumn() + { + // Initialize the button column. + DataGridViewButtonColumn buttonColumn = + new DataGridViewButtonColumn(); + buttonColumn.Name = "Details"; + buttonColumn.HeaderText = "Details"; + buttonColumn.Text = "View Details"; + + // Use the Text property for the button text for all cells rather + // than using each cell's value as the text for its own button. + buttonColumn.UseColumnTextForButtonValue = true; + + // Add the button column to the control. + dataGridView1.Columns.Insert(0, buttonColumn); + } + // + + // How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control + private DataGridView customersDataGridView = new DataGridView(); + private DataSet customersDataSet = new DataSet(); + // + private void BindData() + { + customersDataGridView.AutoGenerateColumns = true; + customersDataGridView.DataSource = customersDataSet; + customersDataGridView.DataMember = "Customers"; + } + // + + // How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control + // + private void SetBorderAndGridlineStyles() + { + // + this.dataGridView1.GridColor = Color.BlueViolet; + // + // + this.dataGridView1.BorderStyle = BorderStyle.Fixed3D; + // + // + this.dataGridView1.CellBorderStyle = + DataGridViewCellBorderStyle.None; + this.dataGridView1.RowHeadersBorderStyle = + DataGridViewHeaderBorderStyle.Single; + this.dataGridView1.ColumnHeadersBorderStyle = + DataGridViewHeaderBorderStyle.Single; + // + } + // + + // How to: Change the Order of the Columns in the Windows Forms DataGridView Control + // + private void AdjustColumnOrder() + { + customersDataGridView.Columns["CustomerID"].Visible = false; + customersDataGridView.Columns["ContactName"].DisplayIndex = 0; + customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1; + customersDataGridView.Columns["City"].DisplayIndex = 2; + customersDataGridView.Columns["Country"].DisplayIndex = 3; + customersDataGridView.Columns["CompanyName"].DisplayIndex = 4; + } + // + + // 1 of 2 for How to: Display Images in Cells of the Windows Forms DataGridView Control + // + private void createGraphicsColumn() + { + Icon treeIcon = new Icon(this.GetType(), "tree.ico"); + DataGridViewImageColumn iconColumn = new DataGridViewImageColumn(); + iconColumn.Image = treeIcon.ToBitmap(); + iconColumn.Name = "Tree"; + iconColumn.HeaderText = "Nice tree"; + dataGridView1.Columns.Insert(2, iconColumn); + } + // + + // 2 of 2 for How to: Display Images in Cells of the Windows Forms DataGridView Control + // + private void dataGridView1_CellFormatting(object sender, + System.Windows.Forms.DataGridViewCellFormattingEventArgs e) + { + if (dataGridView1.Columns[e.ColumnIndex].Name == "Icon") + { + if (e.RowIndex % 5 == 0) + { + Bitmap bmp = new Bitmap(this.GetType(), "Bitmap2.bmp"); + e.Value = bmp; + } + } + } + // + + private void TinySnippets() + { + // How to: Enable Column Reordering in the Windows Forms DataGridView Control + // + dataGridView1.AllowUserToOrderColumns = true; + // + + // How to: Freeze Columns in the Windows Forms DataGridView Control + // + this.dataGridView1.Columns["AddToCartButton"].Frozen = true; + // + + // How to: Hide Column Headers in the Windows Forms DataGridView Control + // + dataGridView1.ColumnHeadersVisible = false; + // + + // How to: Hide Columns in the Windows Forms DataGridView Control + // + this.dataGridView1.Columns["CustomerID"].Visible = false; + // + + // How to: Make Columns in the Windows Forms DataGridView Control Read-Only + // + dataGridView1.Columns["CompanyName"].ReadOnly = true; + // + + // How to: Set the Selection Mode of the Windows Forms DataGridView Control + // + this.dataGridView1.SelectionMode = + DataGridViewSelectionMode.FullRowSelect; + this.dataGridView1.MultiSelect = false; + // + + // How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control + // + this.dataGridView1.Columns["Priority"].SortMode = + DataGridViewColumnSortMode.Automatic; + // + + // How to: Specify the Edit Mode for the Windows Forms DataGridView Control + // + this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; + // + + // How to: Set Alternating Row Styles for the Windows Forms DataGridView Control + // + this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; + this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = + Color.Beige; + // + + // + this.dataGridView1.EditingPanel.BorderStyle = BorderStyle.Fixed3D; + // + } + + // How to: Format Data in the Windows Forms DataGridView Control + // + private void SetFormatting() + { + // + this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c"; + this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format = "d"; + // + // + this.dataGridView1.Columns["CustomerName"].DefaultCellStyle + .Alignment = DataGridViewContentAlignment.MiddleRight; + // + // + this.dataGridView1.DefaultCellStyle.NullValue = "no entry"; + // + // + this.dataGridView1.DefaultCellStyle.WrapMode = + DataGridViewTriState.True; + // + } + // + + // 1 of 2 for How to: Get and Set the Current Cell in the Windows Forms DataGridView Control + // + private void getCurrentCellButton_Click(object sender, System.EventArgs e) + { + string msg = String.Format("Row: {0}, Column: {1}", + dataGridView1.CurrentCell.RowIndex, + dataGridView1.CurrentCell.ColumnIndex); + MessageBox.Show(msg, "Current Cell"); + } + // + + // 2 of 2 for How to: Get and Set the Current Cell in the Windows Forms DataGridView Control + // + private void setCurrentCellButton_Click(object sender, System.EventArgs e) + { + // Set the current cell to the cell in column 1, Row 0. + this.dataGridView1.CurrentCell = this.dataGridView1[1,0]; + } + // + + // How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control + // + private void MakeReadOnly() + { + dataGridView1.AllowUserToAddRows = false; + dataGridView1.AllowUserToDeleteRows = false; + dataGridView1.ReadOnly = true; + } + // + + // How to: Set Font and Color Styles in the Windows Forms DataGridView Control + // + private void SetFontAndColors() + { + // + this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 15); + // + // + this.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue; + this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige; + // + // + this.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow; + this.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black; + // + } + // + + // How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control + // + private void BindDataAndInitializeColumns() + { + // + dataGridView1.AutoGenerateColumns = true; + dataGridView1.DataSource = customersDataSet; + dataGridView1.Columns.Remove("Fax"); + // + // + dataGridView1.Columns["CustomerID"].Visible = false; + // + } + // + + // How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control + private Object NewCustomerId() { return new Object(); } + // + private void dataGridView1_DefaultValuesNeeded(object sender, + System.Windows.Forms.DataGridViewRowEventArgs e) + { + e.Row.Cells["Region"].Value = "WA"; + e.Row.Cells["City"].Value = "Redmond"; + e.Row.Cells["PostalCode"].Value = "98052-6399"; + e.Row.Cells["Country"].Value = "USA"; + e.Row.Cells["CustomerID"].Value = NewCustomerId(); + } + // + + // 1 of 2 for How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control + // + private void dataGridView1_CellValueChanged(object sender, + DataGridViewCellEventArgs e) + { + string msg = String.Format( + "Cell at row {0}, column {1} value changed", + e.RowIndex, e.ColumnIndex); + MessageBox.Show(msg, "Cell Value Changed"); + } + // + + // 2 of 2 for How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control + // + private void dataGridView1_CellStateChanged(object sender, + DataGridViewCellStateChangedEventArgs e) + { + DataGridViewElementStates state = e.StateChanged; + string msg = String.Format("Row {0}, Column {1}, {2}", + e.Cell.RowIndex, e.Cell.ColumnIndex, e.StateChanged); + MessageBox.Show(msg, "Cell State Changed"); + } + // + + // How to: Set Default Cell Styles for the Windows Forms DataGridView Control + // + private void SetDefaultCellStyles() + { + // + this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige; + this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 12); + // + + // + DataGridViewCellStyle highlightCellStyle = new DataGridViewCellStyle(); + highlightCellStyle.BackColor = Color.Red; + + DataGridViewCellStyle currencyCellStyle = new DataGridViewCellStyle(); + currencyCellStyle.Format = "C"; + currencyCellStyle.ForeColor = Color.Green; + // + + // + this.dataGridView1.Rows[3].DefaultCellStyle = highlightCellStyle; + this.dataGridView1.Rows[8].DefaultCellStyle = highlightCellStyle; + this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle = + currencyCellStyle; + this.dataGridView1.Columns["TotalPrice"].DefaultCellStyle = + currencyCellStyle; + // + } + // + + // + private void dataGridView1_Sorted(object sender, EventArgs e) + { + this.dataGridView1.FirstDisplayedCell = this.dataGridView1.CurrentCell; + } + // + + // + private void dataGridView1_ColumnHeaderMouseClick( + object sender, DataGridViewCellMouseEventArgs e) + { + DataGridViewColumn newColumn = dataGridView1.Columns[e.ColumnIndex]; + DataGridViewColumn oldColumn = dataGridView1.SortedColumn; + ListSortDirection direction; + + // If oldColumn is null, then the DataGridView is not sorted. + if (oldColumn != null) + { + // Sort the same column again, reversing the SortOrder. + if (oldColumn == newColumn && + dataGridView1.SortOrder == SortOrder.Ascending) + { + direction = ListSortDirection.Descending; + } + else + { + // Sort a new column and remove the old SortGlyph. + direction = ListSortDirection.Ascending; + oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None; + } + } + else + { + direction = ListSortDirection.Ascending; + } + + // Sort the selected column. + dataGridView1.Sort(newColumn, direction); + newColumn.HeaderCell.SortGlyphDirection = + direction == ListSortDirection.Ascending ? + SortOrder.Ascending : SortOrder.Descending; + } + + private void dataGridView1_DataBindingComplete(object sender, + DataGridViewBindingCompleteEventArgs e) + { + // Put each of the columns into programmatic sort mode. + foreach (DataGridViewColumn column in dataGridView1.Columns) + { + column.SortMode = DataGridViewColumnSortMode.Programmatic; + } + } + // + + // + private void clearSelectionButton_Click(object sender, EventArgs e) + { + dataGridView1.ClearSelection(); + } + // + + // + private void selectAllButton_Click(object sender, EventArgs e) + { + dataGridView1.SelectAll(); + } + // + + // + private void dataGridView1_CellEnter(object sender, + DataGridViewCellEventArgs e) + { + dataGridView1[e.ColumnIndex, e.RowIndex].Style + .SelectionBackColor = Color.Blue; + } + + private void dataGridView1_CellLeave(object sender, + DataGridViewCellEventArgs e) + { + dataGridView1[e.ColumnIndex, e.RowIndex].Style + .SelectionBackColor = Color.Empty; + } + // + + // + private void dataGridView1_RowEnter(object sender, + DataGridViewCellEventArgs e) + { + for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++) + { + dataGridView1[i, e.RowIndex].Style.BackColor = Color.Yellow; + } + } + + private void dataGridView1_RowLeave(object sender, + DataGridViewCellEventArgs e) + { + for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++) + { + dataGridView1[i, e.RowIndex].Style.BackColor = Color.Empty; + } + } + // + + // + private void dataGridView1_EditingControlShowing(object sender, + DataGridViewEditingControlShowingEventArgs e) + { + e.CellStyle.BackColor = Color.Aquamarine; + } + // + + // + private void dataGridView1_CellBeginEdit(object sender, + DataGridViewCellCancelEventArgs e) + { + string msg = String.Format("Editing Cell at ({0}, {1})", + e.ColumnIndex, e.RowIndex); + this.Text = msg; + } + + private void dataGridView1_CellEndEdit(object sender, + DataGridViewCellEventArgs e) + { + string msg = String.Format("Finished Editing Cell at ({0}, {1})", + e.ColumnIndex, e.RowIndex); + this.Text = msg; + } + // + + private void DemonstrateIndexer() + { + // + // Retrieve the cell value for the cell at column 3, row 7. + String testValue1 = (String)dataGridView1[3, 7].Value; + + // Retrieve the cell value for the cell in the Name column at row 4. + String testValue2 = (String)dataGridView1["Name", 4].Value; + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/CS/datagridviewobjectbinding.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/CS/datagridviewobjectbinding.cs new file mode 100644 index 0000000000..6c558de96b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/CS/datagridviewobjectbinding.cs @@ -0,0 +1,93 @@ +// +using System; +using System.Windows.Forms; + +public class DataGridViewObjectBinding : Form +{ + // These declarations and the Main() and New() methods + // below can be replaced with designer-generated code. + private Button invoiceButton = new Button(); + private DataGridView dataGridView1 = new DataGridView(); + + // Entry point code. + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new DataGridViewObjectBinding()); + } + + // Sets up the form. + public DataGridViewObjectBinding() + { + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(this.dataGridView1); + + this.invoiceButton.Text = "invoice the selected customers"; + this.invoiceButton.Dock = DockStyle.Top; + this.invoiceButton.Click += new EventHandler(invoiceButton_Click); + this.Controls.Add(this.invoiceButton); + + this.Load += new EventHandler(DataGridViewObjectBinding_Load); + this.Text = "DataGridView collection-binding demo"; + } + + void DataGridViewObjectBinding_Load(object sender, EventArgs e) + { + // Set up a collection of objects for binding. + System.Collections.ArrayList customers = new System.Collections.ArrayList(); + customers.Add(new Customer("Harry")); + customers.Add(new Customer("Sally")); + customers.Add(new Customer("Roy")); + customers.Add(new Customer("Pris")); + + // Initialize and bind the DataGridView. + this.dataGridView1.SelectionMode = + DataGridViewSelectionMode.FullRowSelect; + this.dataGridView1.AutoGenerateColumns = true; + this.dataGridView1.DataSource = customers; + } + + // Calls the SendInvoice() method for the Customer + // object bound to each selected row. + // + void invoiceButton_Click(object sender, EventArgs e) + { + foreach (DataGridViewRow row in this.dataGridView1.SelectedRows) + { + Customer cust = row.DataBoundItem as Customer; + if (cust != null) + { + cust.SendInvoice(); + } + } + } + // +} + +public class Customer +{ + private String nameValue; + + public Customer(String name) + { + nameValue = name; + } + + public String Name + { + get + { + return nameValue; + } + set + { + nameValue = value; + } + } + + public void SendInvoice() + { + MessageBox.Show(nameValue + " has been billed."); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/CS/form1.cs new file mode 100644 index 0000000000..491e87dbe0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/CS/form1.cs @@ -0,0 +1,119 @@ +// +using System; +using System.ComponentModel; +using System.Windows.Forms; + +class Form1 : Form +{ + private Button sortButton = new Button(); + private DataGridView dataGridView1 = new DataGridView(); + + // Initializes the form. + // You can replace this code with designer-generated code. + public Form1() + { + dataGridView1.Dock = DockStyle.Fill; + dataGridView1.AllowUserToAddRows = false; + dataGridView1.SelectionMode = + DataGridViewSelectionMode.ColumnHeaderSelect; + dataGridView1.MultiSelect = false; + + sortButton.Dock = DockStyle.Bottom; + sortButton.Text = "Sort"; + + Controls.Add(dataGridView1); + Controls.Add(sortButton); + Text = "DataGridView programmatic sort demo"; + } + + // Establishes the main entry point for the application. + [STAThreadAttribute()] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + // + // Populates the DataGridView. + // Replace this with your own code to populate the DataGridView. + public void PopulateDataGridView() + { + // Add columns to the DataGridView. + dataGridView1.ColumnCount = 2; + dataGridView1.Columns[0].HeaderText = "Last Name"; + dataGridView1.Columns[1].HeaderText = "City"; + // Put the new columns into programmatic sort mode + dataGridView1.Columns[0].SortMode = + DataGridViewColumnSortMode.Programmatic; + dataGridView1.Columns[1].SortMode = + DataGridViewColumnSortMode.Programmatic; + + // Populate the DataGridView. + dataGridView1.Rows.Add(new string[] { "Parker", "Seattle" }); + dataGridView1.Rows.Add(new string[] { "Watson", "Seattle" }); + dataGridView1.Rows.Add(new string[] { "Osborn", "New York" }); + dataGridView1.Rows.Add(new string[] { "Jameson", "New York" }); + dataGridView1.Rows.Add(new string[] { "Brock", "New Jersey" }); + } + // + + protected override void OnLoad(EventArgs e) + { + sortButton.Click += new EventHandler(sortButton_Click); + + PopulateDataGridView(); + base.OnLoad(e); + } + + // + private void sortButton_Click(object sender, System.EventArgs e) + { + // Check which column is selected, otherwise set NewColumn to null. + DataGridViewColumn newColumn = + dataGridView1.Columns.GetColumnCount( + DataGridViewElementStates.Selected) == 1 ? + dataGridView1.SelectedColumns[0] : null; + + DataGridViewColumn oldColumn = dataGridView1.SortedColumn; + ListSortDirection direction; + + // If oldColumn is null, then the DataGridView is not currently sorted. + if (oldColumn != null) + { + // Sort the same column again, reversing the SortOrder. + if (oldColumn == newColumn && + dataGridView1.SortOrder == SortOrder.Ascending) + { + direction = ListSortDirection.Descending; + } + else + { + // Sort a new column and remove the old SortGlyph. + direction = ListSortDirection.Ascending; + oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None; + } + } + else + { + direction = ListSortDirection.Ascending; + } + + // If no column has been selected, display an error dialog box. + if (newColumn == null) + { + MessageBox.Show("Select a single column and try again.", + "Error: Invalid Selection", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + else + { + dataGridView1.Sort(newColumn, direction); + newColumn.HeaderCell.SortGlyphDirection = + direction == ListSortDirection.Ascending ? + SortOrder.Ascending : SortOrder.Descending; + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs new file mode 100644 index 0000000000..d3717f7d46 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/CS/rollovercell.cs @@ -0,0 +1,98 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +// +class Form1 : Form +{ + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + public Form1() + { + DataGridView dataGridView1 = new DataGridView(); + DataGridViewRolloverCellColumn col = + new DataGridViewRolloverCellColumn(); + dataGridView1.Columns.Add(col); + dataGridView1.Rows.Add(new string[] { "" }); + dataGridView1.Rows.Add(new string[] { "" }); + dataGridView1.Rows.Add(new string[] { "" }); + dataGridView1.Rows.Add(new string[] { "" }); + this.Controls.Add(dataGridView1); + this.Text = "DataGridView rollover-cell demo"; + } +} +// + +// +// +public class DataGridViewRolloverCell : DataGridViewTextBoxCell +{ +// + // + protected override void Paint( + Graphics graphics, + Rectangle clipBounds, + Rectangle cellBounds, + int rowIndex, + DataGridViewElementStates cellState, + object value, + object formattedValue, + string errorText, + DataGridViewCellStyle cellStyle, + DataGridViewAdvancedBorderStyle advancedBorderStyle, + DataGridViewPaintParts paintParts) + { + // Call the base class method to paint the default cell appearance. + base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, + value, formattedValue, errorText, cellStyle, + advancedBorderStyle, paintParts); + + // Retrieve the client location of the mouse pointer. + Point cursorPosition = + this.DataGridView.PointToClient(Cursor.Position); + + // If the mouse pointer is over the current cell, draw a custom border. + if (cellBounds.Contains(cursorPosition)) + { + Rectangle newRect = new Rectangle(cellBounds.X + 1, + cellBounds.Y + 1, cellBounds.Width - 4, + cellBounds.Height - 4); + graphics.DrawRectangle(Pens.Red, newRect); + } + } + // + + // + // Force the cell to repaint itself when the mouse pointer enters it. + protected override void OnMouseEnter(int rowIndex) + { + this.DataGridView.InvalidateCell(this); + } + + // Force the cell to repaint itself when the mouse pointer leaves it. + protected override void OnMouseLeave(int rowIndex) + { + this.DataGridView.InvalidateCell(this); + } + // + +// +} +// +// + +// +public class DataGridViewRolloverCellColumn : DataGridViewColumn +{ + public DataGridViewRolloverCellColumn() + { + this.CellTemplate = new DataGridViewRolloverCell(); + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/CS/datagridviewrowpainting.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/CS/datagridviewrowpainting.cs new file mode 100644 index 0000000000..b6927ce12a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/CS/datagridviewrowpainting.cs @@ -0,0 +1,261 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +class DataGridViewRowPainting : Form +{ + private DataGridView dataGridView1 = new DataGridView(); + private Int32 oldRowIndex = 0; + private const Int32 CUSTOM_CONTENT_HEIGHT = 30; + + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new DataGridViewRowPainting()); + } + + public DataGridViewRowPainting() + { + this.dataGridView1.Dock = DockStyle.Fill; + this.Controls.Add(this.dataGridView1); + this.Load += new EventHandler(DataGridViewRowPainting_Load); + this.Text = "DataGridView row painting demo"; + } + + void DataGridViewRowPainting_Load(object sender, EventArgs e) + { + // + // Set a cell padding to provide space for the top of the focus + // rectangle and for the content that spans multiple columns. + Padding newPadding = new Padding(0, 1, 0, CUSTOM_CONTENT_HEIGHT); + this.dataGridView1.RowTemplate.DefaultCellStyle.Padding = newPadding; + + // Set the selection background color to transparent so + // the cell won't paint over the custom selection background. + this.dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor = + Color.Transparent; + + // Set the row height to accommodate the content that + // spans multiple columns. + this.dataGridView1.RowTemplate.Height += CUSTOM_CONTENT_HEIGHT; + // + + // Initialize other DataGridView properties. + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2; + this.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None; + this.dataGridView1.SelectionMode = + DataGridViewSelectionMode.FullRowSelect; + + // Set the column header names. + this.dataGridView1.ColumnCount = 4; + this.dataGridView1.Columns[0].Name = "Recipe"; + this.dataGridView1.Columns[0].SortMode = + DataGridViewColumnSortMode.NotSortable; + this.dataGridView1.Columns[1].Name = "Category"; + this.dataGridView1.Columns[2].Name = "Main Ingredients"; + this.dataGridView1.Columns[3].Name = "Rating"; + + // Hide the column that contains the content that spans + // multiple columns. + this.dataGridView1.Columns[2].Visible = false; + + // Populate the rows of the DataGridView. + string[] row1 = new string[]{"Meatloaf", "Main Dish", + "1 lb. lean ground beef, 1/2 cup bread crumbs, " + + "1/4 cup ketchup, 1/3 tsp onion powder, 1 clove of garlic, " + + "1/2 pack onion soup mix, dash of your favorite BBQ Sauce", + "****"}; + string[] row2 = new string[]{"Key Lime Pie", "Dessert", + "lime juice, whipped cream, eggs, evaporated milk", "****"}; + string[] row3 = new string[]{"Orange-Salsa Pork Chops", + "Main Dish", "pork chops, salsa, orange juice, pineapple", "****"}; + string[] row4 = new string[]{"Black Bean and Rice Salad", + "Salad", "black beans, brown rice", "****"}; + string[] row5 = new string[]{"Chocolate Cheesecake", + "Dessert", "cream cheese, unsweetened chocolate", "***"}; + string[] row6 = new string[]{"Black Bean Dip", "Appetizer", + "black beans, sour cream, salsa, chips", "***"}; + object[] rows = new object[] { row1, row2, row3, row4, row5, row6 }; + foreach (string[] rowArray in rows) + { + this.dataGridView1.Rows.Add(rowArray); + } + + // Adjust the row heights to accommodate the normal cell content. + this.dataGridView1.AutoResizeRows( + DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders); + + // Attach handlers to DataGridView events. + this.dataGridView1.ColumnWidthChanged += new + DataGridViewColumnEventHandler(dataGridView1_ColumnWidthChanged); + this.dataGridView1.RowPrePaint += new + DataGridViewRowPrePaintEventHandler(dataGridView1_RowPrePaint); + this.dataGridView1.RowPostPaint += new + DataGridViewRowPostPaintEventHandler(dataGridView1_RowPostPaint); + this.dataGridView1.CurrentCellChanged += new + EventHandler(dataGridView1_CurrentCellChanged); + this.dataGridView1.RowHeightChanged += new + DataGridViewRowEventHandler(dataGridView1_RowHeightChanged); + } + + // + // Forces the control to repaint itself when the user + // manually changes the width of a column. + void dataGridView1_ColumnWidthChanged(object sender, + DataGridViewColumnEventArgs e) + { + this.dataGridView1.Invalidate(); + } + // + + // + // Forces the row to repaint itself when the user changes the + // current cell. This is necessary to refresh the focus rectangle. + void dataGridView1_CurrentCellChanged(object sender, EventArgs e) + { + if (oldRowIndex != -1) + { + this.dataGridView1.InvalidateRow(oldRowIndex); + } + oldRowIndex = this.dataGridView1.CurrentCellAddress.Y; + } + // + + // + // Paints the custom selection background for selected rows. + void dataGridView1_RowPrePaint(object sender, + DataGridViewRowPrePaintEventArgs e) + { + // Do not automatically paint the focus rectangle. + e.PaintParts &= ~DataGridViewPaintParts.Focus; + + // + // Determine whether the cell should be painted + // with the custom selection background. + if ((e.State & DataGridViewElementStates.Selected) == + DataGridViewElementStates.Selected) + { + // Calculate the bounds of the row. + Rectangle rowBounds = new Rectangle( + this.dataGridView1.RowHeadersWidth, e.RowBounds.Top, + this.dataGridView1.Columns.GetColumnsWidth( + DataGridViewElementStates.Visible) - + this.dataGridView1.HorizontalScrollingOffset + 1, + e.RowBounds.Height); + + // Paint the custom selection background. + using (Brush backbrush = + new System.Drawing.Drawing2D.LinearGradientBrush(rowBounds, + this.dataGridView1.DefaultCellStyle.SelectionBackColor, + e.InheritedRowStyle.ForeColor, + System.Drawing.Drawing2D.LinearGradientMode.Horizontal)) + { + e.Graphics.FillRectangle(backbrush, rowBounds); + } + } + // + } + // + + // + // Paints the content that spans multiple columns and the focus rectangle. + void dataGridView1_RowPostPaint(object sender, + DataGridViewRowPostPaintEventArgs e) + { + // Calculate the bounds of the row. + Rectangle rowBounds = new Rectangle( + this.dataGridView1.RowHeadersWidth, e.RowBounds.Top, + this.dataGridView1.Columns.GetColumnsWidth( + DataGridViewElementStates.Visible) - + this.dataGridView1.HorizontalScrollingOffset + 1, + e.RowBounds.Height); + + SolidBrush forebrush = null; + try + { + // + // Determine the foreground color. + if ((e.State & DataGridViewElementStates.Selected) == + DataGridViewElementStates.Selected) + { + forebrush = new SolidBrush(e.InheritedRowStyle.SelectionForeColor); + } + else + { + forebrush = new SolidBrush(e.InheritedRowStyle.ForeColor); + } + // + + // + // Get the content that spans multiple columns. + object recipe = + this.dataGridView1.Rows.SharedRow(e.RowIndex).Cells[2].Value; + + if (recipe != null) + { + String text = recipe.ToString(); + + // Calculate the bounds for the content that spans multiple + // columns, adjusting for the horizontal scrolling position + // and the current row height, and displaying only whole + // lines of text. + Rectangle textArea = rowBounds; + textArea.X -= this.dataGridView1.HorizontalScrollingOffset; + textArea.Width += this.dataGridView1.HorizontalScrollingOffset; + textArea.Y += rowBounds.Height - e.InheritedRowStyle.Padding.Bottom; + textArea.Height -= rowBounds.Height - + e.InheritedRowStyle.Padding.Bottom; + textArea.Height = (textArea.Height / e.InheritedRowStyle.Font.Height) * + e.InheritedRowStyle.Font.Height; + + // Calculate the portion of the text area that needs painting. + RectangleF clip = textArea; + clip.Width -= this.dataGridView1.RowHeadersWidth + 1 - clip.X; + clip.X = this.dataGridView1.RowHeadersWidth + 1; + RectangleF oldClip = e.Graphics.ClipBounds; + e.Graphics.SetClip(clip); + + // Draw the content that spans multiple columns. + e.Graphics.DrawString( + text, e.InheritedRowStyle.Font, forebrush, textArea); + + e.Graphics.SetClip(oldClip); + } + // + } + finally + { + forebrush.Dispose(); + } + + if (this.dataGridView1.CurrentCellAddress.Y == e.RowIndex) + { + // Paint the focus rectangle. + e.DrawFocus(rowBounds, true); + } + } + // + + // + // Adjusts the padding when the user changes the row height so that + // the normal cell content is fully displayed and any extra + // height is used for the content that spans multiple columns. + void dataGridView1_RowHeightChanged(object sender, + DataGridViewRowEventArgs e) + { + // Calculate the new height of the normal cell content. + Int32 preferredNormalContentHeight = + e.Row.GetPreferredHeight(e.Row.Index, + DataGridViewAutoSizeRowMode.AllCellsExceptHeader, true) - + e.Row.DefaultCellStyle.Padding.Bottom; + + // Specify a new padding. + Padding newPadding = e.Row.DefaultCellStyle.Padding; + newPadding.Bottom = e.Row.Height - preferredNormalContentHeight; + e.Row.DefaultCellStyle.Padding = newPadding; + } + // +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/CS/DataGridViewSelectedCollections.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/CS/DataGridViewSelectedCollections.cs new file mode 100644 index 0000000000..8c62df6044 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/CS/DataGridViewSelectedCollections.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +class Form1 : Form +{ + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + private DataGridView dataGridView1 = new DataGridView(); + private Button selectedCellsButton = new Button(); + private Button selectedRowsButton = new Button(); + private Button selectedColumnsButton = new Button(); + + protected override void OnLoad(EventArgs e) + { + this.dataGridView1.Dock = DockStyle.Fill; + this.dataGridView1.ColumnCount = 5; + this.dataGridView1.RowCount = 5; + this.dataGridView1.ColumnHeaderMouseClick += + new DataGridViewCellMouseEventHandler( + dataGridView1_ColumnHeaderMouseClick); + this.dataGridView1.RowHeaderMouseClick += + new DataGridViewCellMouseEventHandler( + dataGridView1_RowHeaderMouseClick); + + selectedCellsButton.AutoSize = true; + selectedCellsButton.Text = "selected cells"; + selectedCellsButton.Click += + new EventHandler(selectedCellsButton_Click); + selectedRowsButton.AutoSize = true; + selectedRowsButton.Text = "selected rows"; + selectedRowsButton.Click += + new EventHandler(selectedRowsButton_Click); + selectedColumnsButton.AutoSize = true; + selectedColumnsButton.Text = "selected columns"; + selectedColumnsButton.Click += + new EventHandler(selectedColumnsButton_Click); + + FlowLayoutPanel panel = new FlowLayoutPanel(); + panel.Dock = DockStyle.Top; + panel.AutoSize = true; + panel.Controls.AddRange(new Control[] { + this.selectedCellsButton, this.selectedRowsButton, + this.selectedColumnsButton }); + + this.Controls.AddRange(new Control[] { dataGridView1, panel }); + this.Text = "DataGridView selected collections demo"; + + base.OnLoad(e); + } + + // + void dataGridView1_ColumnHeaderMouseClick( + object sender, DataGridViewCellMouseEventArgs e) + { + this.dataGridView1.SelectionMode = + DataGridViewSelectionMode.ColumnHeaderSelect; + this.dataGridView1.Columns[e.ColumnIndex].HeaderCell + .SortGlyphDirection = SortOrder.None; + this.dataGridView1.Columns[e.ColumnIndex].Selected = true; + } + + void dataGridView1_RowHeaderMouseClick( + object sender, DataGridViewCellMouseEventArgs e) + { + this.dataGridView1.SelectionMode = + DataGridViewSelectionMode.RowHeaderSelect; + this.dataGridView1.Rows[e.RowIndex].Selected = true; + } + // + + // + private void selectedCellsButton_Click(object sender, System.EventArgs e) + { + Int32 selectedCellCount = + dataGridView1.GetCellCount(DataGridViewElementStates.Selected); + if (selectedCellCount > 0) + { + if (dataGridView1.AreAllCellsSelected(true)) + { + MessageBox.Show("All cells are selected", "Selected Cells"); + } + else + { + System.Text.StringBuilder sb = + new System.Text.StringBuilder(); + + for (int i = 0; + i < selectedCellCount; i++) + { + sb.Append("Row: "); + sb.Append(dataGridView1.SelectedCells[i].RowIndex + .ToString()); + sb.Append(", Column: "); + sb.Append(dataGridView1.SelectedCells[i].ColumnIndex + .ToString()); + sb.Append(Environment.NewLine); + } + + sb.Append("Total: " + selectedCellCount.ToString()); + MessageBox.Show(sb.ToString(), "Selected Cells"); + } + } + } + // + + // + private void selectedRowsButton_Click(object sender, System.EventArgs e) + { + Int32 selectedRowCount = + dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected); + if (selectedRowCount > 0) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + + for (int i = 0; i < selectedRowCount; i++) + { + sb.Append("Row: "); + sb.Append(dataGridView1.SelectedRows[i].Index.ToString()); + sb.Append(Environment.NewLine); + } + + sb.Append("Total: " + selectedRowCount.ToString()); + MessageBox.Show(sb.ToString(), "Selected Rows"); + } + } + // + + // + private void selectedColumnsButton_Click(object sender, System.EventArgs e) + { + Int32 selectedColumnCount = dataGridView1.Columns + .GetColumnCount(DataGridViewElementStates.Selected); + if (selectedColumnCount > 0) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + + for (int i = 0; i < selectedColumnCount; i++) + { + sb.Append("Column: "); + sb.Append(dataGridView1.SelectedColumns[i].Index + .ToString()); + sb.Append(Environment.NewLine); + } + + sb.Append("Total: " + selectedColumnCount.ToString()); + MessageBox.Show(sb.ToString(), "Selected Columns"); + } + } + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs new file mode 100644 index 0000000000..9add705b67 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/CS/simpleunbound.cs @@ -0,0 +1,178 @@ +// +// +using System; +using System.Drawing; +using System.Windows.Forms; + +public class Form1 : System.Windows.Forms.Form +{ + private Panel buttonPanel = new Panel(); + private DataGridView songsDataGridView = new DataGridView(); + private Button addNewRowButton = new Button(); + private Button deleteRowButton = new Button(); + // + + // + public Form1() + { + this.Load += new EventHandler(Form1_Load); + } + + private void Form1_Load(System.Object sender, System.EventArgs e) + { + SetupLayout(); + SetupDataGridView(); + PopulateDataGridView(); + } + + private void songsDataGridView_CellFormatting(object sender, + System.Windows.Forms.DataGridViewCellFormattingEventArgs e) + { + if (e != null) + { + if (this.songsDataGridView.Columns[e.ColumnIndex].Name == "Release Date") + { + if (e.Value != null) + { + try + { + e.Value = DateTime.Parse(e.Value.ToString()) + .ToLongDateString(); + e.FormattingApplied = true; + } + catch (FormatException) + { + Console.WriteLine("{0} is not a valid date.", e.Value.ToString()); + } + } + } + } + } + + private void addNewRowButton_Click(object sender, EventArgs e) + { + this.songsDataGridView.Rows.Add(); + } + + private void deleteRowButton_Click(object sender, EventArgs e) + { + if (this.songsDataGridView.SelectedRows.Count > 0 && + this.songsDataGridView.SelectedRows[0].Index != + this.songsDataGridView.Rows.Count - 1) + { + this.songsDataGridView.Rows.RemoveAt( + this.songsDataGridView.SelectedRows[0].Index); + } + } + // + + // + private void SetupLayout() + { + this.Size = new Size(600, 500); + + addNewRowButton.Text = "Add Row"; + addNewRowButton.Location = new Point(10, 10); + addNewRowButton.Click += new EventHandler(addNewRowButton_Click); + + deleteRowButton.Text = "Delete Row"; + deleteRowButton.Location = new Point(100, 10); + deleteRowButton.Click += new EventHandler(deleteRowButton_Click); + + buttonPanel.Controls.Add(addNewRowButton); + buttonPanel.Controls.Add(deleteRowButton); + buttonPanel.Height = 50; + buttonPanel.Dock = DockStyle.Bottom; + + this.Controls.Add(this.buttonPanel); + } + // + + // + private void SetupDataGridView() + { + this.Controls.Add(songsDataGridView); + + songsDataGridView.ColumnCount = 5; + + songsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy; + songsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; + songsDataGridView.ColumnHeadersDefaultCellStyle.Font = + new Font(songsDataGridView.Font, FontStyle.Bold); + + songsDataGridView.Name = "songsDataGridView"; + songsDataGridView.Location = new Point(8, 8); + songsDataGridView.Size = new Size(500, 250); + songsDataGridView.AutoSizeRowsMode = + DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders; + songsDataGridView.ColumnHeadersBorderStyle = + DataGridViewHeaderBorderStyle.Single; + songsDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single; + songsDataGridView.GridColor = Color.Black; + songsDataGridView.RowHeadersVisible = false; + + songsDataGridView.Columns[0].Name = "Release Date"; + songsDataGridView.Columns[1].Name = "Track"; + songsDataGridView.Columns[2].Name = "Title"; + songsDataGridView.Columns[3].Name = "Artist"; + songsDataGridView.Columns[4].Name = "Album"; + songsDataGridView.Columns[4].DefaultCellStyle.Font = + new Font(songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic); + + songsDataGridView.SelectionMode = + DataGridViewSelectionMode.FullRowSelect; + songsDataGridView.MultiSelect = false; + songsDataGridView.Dock = DockStyle.Fill; + + songsDataGridView.CellFormatting += new + DataGridViewCellFormattingEventHandler( + songsDataGridView_CellFormatting); + } + // + + // + private void PopulateDataGridView() + { + + string[] row0 = { "11/22/1968", "29", "Revolution 9", + "Beatles", "The Beatles [White Album]" }; + string[] row1 = { "1960", "6", "Fools Rush In", + "Frank Sinatra", "Nice 'N' Easy" }; + string[] row2 = { "11/11/1971", "1", "One of These Days", + "Pink Floyd", "Meddle" }; + string[] row3 = { "1988", "7", "Where Is My Mind?", + "Pixies", "Surfer Rosa" }; + string[] row4 = { "5/1981", "9", "Can't Find My Mind", + "Cramps", "Psychedelic Jungle" }; + string[] row5 = { "6/10/2003", "13", + "Scatterbrain. (As Dead As Leaves.)", + "Radiohead", "Hail to the Thief" }; + string[] row6 = { "6/30/1992", "3", "Dress", "P J Harvey", "Dry" }; + + songsDataGridView.Rows.Add(row0); + songsDataGridView.Rows.Add(row1); + songsDataGridView.Rows.Add(row2); + songsDataGridView.Rows.Add(row3); + songsDataGridView.Rows.Add(row4); + songsDataGridView.Rows.Add(row5); + songsDataGridView.Rows.Add(row6); + + songsDataGridView.Columns[0].DisplayIndex = 3; + songsDataGridView.Columns[1].DisplayIndex = 4; + songsDataGridView.Columns[2].DisplayIndex = 0; + songsDataGridView.Columns[3].DisplayIndex = 1; + songsDataGridView.Columns[4].DisplayIndex = 2; + } + // + + // + + [STAThreadAttribute()] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs new file mode 100644 index 0000000000..360d80f568 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/CS/sizingscenarios.cs @@ -0,0 +1,84 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +public class Form1 : Form +{ + [STAThreadAttribute()] + public static void Main() + { + Application.Run(new Form1()); + } + + private DataGridView dataGridView1 = new DataGridView(); + + public Form1() + { + dataGridView1.Dock = DockStyle.Fill; + Controls.Add(dataGridView1); + Width *= 2; + Text = "DataGridView Sizing Scenarios"; + } + + protected override void OnLoad(EventArgs e) + { + // + DataGridViewTextBoxColumn idColumn = + new DataGridViewTextBoxColumn(); + idColumn.HeaderText = "ID"; + idColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; + idColumn.Resizable = DataGridViewTriState.False; + idColumn.ReadOnly = true; + idColumn.Width = 20; + // + + // + DataGridViewTextBoxColumn titleColumn = + new DataGridViewTextBoxColumn(); + titleColumn.HeaderText = "Title"; + titleColumn.AutoSizeMode = + DataGridViewAutoSizeColumnMode.AllCellsExceptHeader; + // + + // + dataGridView1.AutoSizeColumnsMode = + DataGridViewAutoSizeColumnsMode.Fill; + + DataGridViewTextBoxColumn subTitleColumn = + new DataGridViewTextBoxColumn(); + subTitleColumn.HeaderText = "Subtitle"; + subTitleColumn.MinimumWidth = 50; + subTitleColumn.FillWeight = 100; + + DataGridViewTextBoxColumn summaryColumn = + new DataGridViewTextBoxColumn(); + summaryColumn.HeaderText = "Summary"; + summaryColumn.MinimumWidth = 50; + summaryColumn.FillWeight = 200; + + DataGridViewTextBoxColumn contentColumn = + new DataGridViewTextBoxColumn(); + contentColumn.HeaderText = "Content"; + contentColumn.MinimumWidth = 50; + contentColumn.FillWeight = 300; + // + + // + dataGridView1.Columns.AddRange(new DataGridViewTextBoxColumn[] { + idColumn, titleColumn, subTitleColumn, + summaryColumn, contentColumn }); + dataGridView1.Rows.Add(new String[] { "1", + "A Short Title", "A Longer SubTitle", + "A short description of the main point.", + "The full contents of the topic, with detailed examples." }); + // + + base.OnLoad(e); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/CS/form1.cs new file mode 100644 index 0000000000..ff52db89e0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/CS/form1.cs @@ -0,0 +1,80 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Data.SqlClient; +using System.Windows.Forms; + +// This form demonstrates using a BindingNavigator to display +// rows from a database query sequentially. +public class Form1 : Form +{ + // This is the BindingNavigator that allows the user + // to navigate through the rows in a DataSet. + BindingNavigator customersBindingNavigator = new BindingNavigator(true); + + // This is the BindingSource that provides data for + // the Textbox control. + BindingSource customersBindingSource = new BindingSource(); + + // This is the TextBox control that displays the CompanyName + // field from the DataSet. + TextBox companyNameTextBox = new TextBox(); + + public Form1() + { + // Set up the BindingSource component. + this.customersBindingNavigator.BindingSource = this.customersBindingSource; + this.customersBindingNavigator.Dock = DockStyle.Top; + this.Controls.Add(this.customersBindingNavigator); + + // Set up the TextBox control for displaying company names. + this.companyNameTextBox.Dock = DockStyle.Bottom; + this.Controls.Add(this.companyNameTextBox); + + // Set up the form. + this.Size = new Size(800, 200); + this.Load += new EventHandler(Form1_Load); + } + + void Form1_Load(object sender, EventArgs e) + { + // Open a connection to the database. + // Replace the value of connectString with a valid + // connection string to a Northwind database accessible + // to your system. + string connectString = + "Integrated Security=SSPI;Persist Security Info=False;" + + "Initial Catalog=Northwind;Data Source=localhost"; + + using (SqlConnection connection = new SqlConnection(connectString)) + { + + SqlDataAdapter dataAdapter1 = + new SqlDataAdapter(new SqlCommand("Select * From Customers",connection)); + DataSet ds = new DataSet("Northwind Customers"); + ds.Tables.Add("Customers"); + dataAdapter1.Fill(ds.Tables["Customers"]); + + // Assign the DataSet as the DataSource for the BindingSource. + this.customersBindingSource.DataSource = ds.Tables["Customers"]; + + // Bind the CompanyName field to the TextBox control. + this.companyNameTextBox.DataBindings.Add( + new Binding("Text", + this.customersBindingSource, + "CompanyName", + true)); + } + } + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePicker/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePicker/CS/form1.cs new file mode 100644 index 0000000000..b5444b50ce --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePicker/CS/form1.cs @@ -0,0 +1,122 @@ +// This example demonstrates using the read-only fields DateTimePicker.MaxDateTime +// and DateTimePicker.MinDateTime. + +using System.Windows.Forms; + +public class Form1: + System.Windows.Forms.Form + +{ + #region " Windows Form Designer generated code " + + public Form1() : base() + { + + //This call is required by the Windows Form Designer. + InitializeComponent(); + InitializeDateTimePicker(); + + //Add any initialization after the InitializeComponent() call + } + + //Form overrides dispose to clean up the component list. + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + //Required by the Windows Form Designer + private System.ComponentModel.IContainer components; + + //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. + + internal System.Windows.Forms.ToolTip ToolTip1; + + [System.Diagnostics.DebuggerStepThrough] + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + + this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); + this.SuspendLayout(); + // + //DateTimePicker1 + // + + // + //Form1 + // + this.ClientSize = new System.Drawing.Size(292, 266); + + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + #endregion + + public static void Main() + { + Application.Run(new Form1()); + } + + // + + // Declare the DateTimePicker. + internal System.Windows.Forms.DateTimePicker DateTimePicker1; + + private void InitializeDateTimePicker() + { + // Construct the DateTimePicker. + this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker(); + + //Set size and location. + this.DateTimePicker1.Location = new System.Drawing.Point(40, 88); + this.DateTimePicker1.Size = new System.Drawing.Size(160, 21); + + // Set the alignment of the drop-down MonthCalendar to right. + this.DateTimePicker1.DropDownAlign = LeftRightAlignment.Right; + + // Set the Value property to 50 years before today. + DateTimePicker1.Value = System.DateTime.Now.AddYears(-50); + + //Set a custom format containing the string "of the year" + DateTimePicker1.Format = DateTimePickerFormat.Custom; + DateTimePicker1.CustomFormat = "MMM dd, 'of the year' yyyy "; + + // Add the DateTimePicker to the form. + this.Controls.Add(this.DateTimePicker1); + } + // + + // + + // When the calendar drops down, display a MessageBox indicating + // that DateTimePicker will not accept dates before MinDateTime or + // after MaxDateTime. Use a StringBuilder object to build the string + // for efficiency. + private void DateTimePicker1_DropDown(object sender, + System.EventArgs e) + { + + System.Text.StringBuilder messageBuilder = + new System.Text.StringBuilder(); + messageBuilder.Append("Choose a date after: "); + messageBuilder.Append + (DateTimePicker.MinDateTime.ToShortDateString()); + messageBuilder.Append(" and a date before: "); + messageBuilder.Append + (DateTimePicker.MaxDateTime.ToShortDateString()); + MessageBox.Show(messageBuilder.ToString()); + } + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/CS/Form1.cs new file mode 100644 index 0000000000..d5a64a57aa --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/CS/Form1.cs @@ -0,0 +1,43 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace TimePickerApplication +{ + public class Form1 : Form + { + public Form1() + { + InitializeTimePicker(); + } +// + private DateTimePicker timePicker; + + private void InitializeTimePicker() + { + timePicker = new DateTimePicker(); + // + timePicker.Format = DateTimePickerFormat.Time; + // + // + timePicker.ShowUpDown = true; + // + timePicker.Location = new Point(10, 10); + timePicker.Width = 100; + Controls.Add(timePicker); + } +// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/imarqueewidget.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/imarqueewidget.cs new file mode 100644 index 0000000000..d8ffb968b5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/imarqueewidget.cs @@ -0,0 +1,35 @@ +// +using System; + +namespace MarqueeControlLibrary +{ + // + // + // This interface defines the contract for any class that is to + // be used in constructing a MarqueeControl. + public interface IMarqueeWidget + { + // + // This method starts the animation. If the control can + // contain other classes that implement IMarqueeWidget as + // children, the control should call StartMarquee on all + // its IMarqueeWidget child controls. + void StartMarquee(); + + // This method stops the animation. If the control can + // contain other classes that implement IMarqueeWidget as + // children, the control should call StopMarquee on all + // its IMarqueeWidget child controls. + void StopMarquee(); + + // This method specifies the refresh rate for the animation, + // in milliseconds. + int UpdatePeriod + { + get; + set; + } + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs new file mode 100644 index 0000000000..c8b91b279e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/lightshapeselectioncontrol.cs @@ -0,0 +1,208 @@ +// +// +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.Design; +// + +namespace MarqueeControlLibrary +{ + // + // This control provides the custom UI for the LightShape property + // of the MarqueeBorder. It is used by the LightShapeEditor. + public class LightShapeSelectionControl : System.Windows.Forms.UserControl + { + // + private MarqueeLightShape lightShapeValue = MarqueeLightShape.Square; + // + private IWindowsFormsEditorService editorService = null; + private System.Windows.Forms.Panel squarePanel; + private System.Windows.Forms.Panel circlePanel; + + // Required designer variable. + private System.ComponentModel.Container components = null; + + // + // This constructor takes a MarqueeLightShape value from the + // design-time environment, which will be used to display + // the initial state. + public LightShapeSelectionControl( + MarqueeLightShape lightShape, + IWindowsFormsEditorService editorService ) + { + // This call is required by the designer. + InitializeComponent(); + + // Cache the light shape value provided by the + // design-time environment. + this.lightShapeValue = lightShape; + + // Cache the reference to the editor service. + this.editorService = editorService; + + // Handle the Click event for the two panels. + this.squarePanel.Click += new EventHandler(squarePanel_Click); + this.circlePanel.Click += new EventHandler(circlePanel_Click); + } + // + + // + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + // Be sure to unhook event handlers + // to prevent "lapsed listener" leaks. + this.squarePanel.Click -= + new EventHandler(squarePanel_Click); + this.circlePanel.Click -= + new EventHandler(circlePanel_Click); + + if(components != null) + { + components.Dispose(); + } + } + base.Dispose( disposing ); + } + // + + // + // LightShape is the property for which this control provides + // a custom user interface in the Properties window. + public MarqueeLightShape LightShape + { + get + { + return this.lightShapeValue; + } + + set + { + if( this.lightShapeValue != value ) + { + this.lightShapeValue = value; + } + } + } + // + + // + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint (e); + + using( + Graphics gSquare = this.squarePanel.CreateGraphics(), + gCircle = this.circlePanel.CreateGraphics() ) + { + // Draw a filled square in the client area of + // the squarePanel control. + gSquare.FillRectangle( + Brushes.Red, + 0, + 0, + this.squarePanel.Width, + this.squarePanel.Height + ); + + // If the Square option has been selected, draw a + // border inside the squarePanel. + if( this.lightShapeValue == MarqueeLightShape.Square ) + { + gSquare.DrawRectangle( + Pens.Black, + 0, + 0, + this.squarePanel.Width-1, + this.squarePanel.Height-1); + } + + // Draw a filled circle in the client area of + // the circlePanel control. + gCircle.Clear( this.circlePanel.BackColor ); + gCircle.FillEllipse( + Brushes.Blue, + 0, + 0, + this.circlePanel.Width, + this.circlePanel.Height + ); + + // If the Circle option has been selected, draw a + // border inside the circlePanel. + if( this.lightShapeValue == MarqueeLightShape.Circle ) + { + gCircle.DrawRectangle( + Pens.Black, + 0, + 0, + this.circlePanel.Width-1, + this.circlePanel.Height-1); + } + } + } + // + + // + private void squarePanel_Click(object sender, EventArgs e) + { + this.lightShapeValue = MarqueeLightShape.Square; + + this.Invalidate( false ); + + this.editorService.CloseDropDown(); + } + + private void circlePanel_Click(object sender, EventArgs e) + { + this.lightShapeValue = MarqueeLightShape.Circle; + + this.Invalidate( false ); + + this.editorService.CloseDropDown(); + } + // + + #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() + { + this.squarePanel = new System.Windows.Forms.Panel(); + this.circlePanel = new System.Windows.Forms.Panel(); + this.SuspendLayout(); +// +// squarePanel +// + this.squarePanel.Location = new System.Drawing.Point(8, 10); + this.squarePanel.Name = "squarePanel"; + this.squarePanel.Size = new System.Drawing.Size(60, 60); + this.squarePanel.TabIndex = 2; +// +// circlePanel +// + this.circlePanel.Location = new System.Drawing.Point(80, 10); + this.circlePanel.Name = "circlePanel"; + this.circlePanel.Size = new System.Drawing.Size(60, 60); + this.circlePanel.TabIndex = 3; +// +// LightShapeSelectionControl +// + this.Controls.Add(this.squarePanel); + this.Controls.Add(this.circlePanel); + this.Name = "LightShapeSelectionControl"; + this.Size = new System.Drawing.Size(150, 80); + this.ResumeLayout(false); + } + #endregion + + } + // +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/makefile new file mode 100644 index 0000000000..5de30ceb64 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/makefile @@ -0,0 +1,5 @@ +MarqueeControlLibrary.dll: IMarqueeWidget.cs LightShapeSelectionControl.cs MarqueeBorder.cs MarqueeControl.cs MarqueeText.cs MarqueeControlRootDesigner.cs MarqueeBorderDesigner.cs + csc /t:library /out:MarqueeControlLibrary.dll IMarqueeWidget.cs LightShapeSelectionControl.cs MarqueeBorder.cs MarqueeControl.cs MarqueeText.cs MarqueeControlRootDesigner.cs MarqueeBorderDesigner.cs + +clean: + del *.dll *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs new file mode 100644 index 0000000000..8be87a5ddd --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborder.cs @@ -0,0 +1,607 @@ +// +// +using System; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Design; +using System.Threading; +using System.Windows.Forms; +using System.Windows.Forms.Design; +// + +namespace MarqueeControlLibrary +{ + // + // This defines the possible values for the MarqueeBorder + // control's SpinDirection property. + public enum MarqueeSpinDirection + { + CW, + CCW + } + + // + // This defines the possible values for the MarqueeBorder + // control's LightShape property. + public enum MarqueeLightShape + { + Square, + Circle + } + // + // + + // + [Designer(typeof(MarqueeControlLibrary.Design.MarqueeBorderDesigner ))] + [ToolboxItemFilter("MarqueeControlLibrary.MarqueeBorder", ToolboxItemFilterType.Require)] + public partial class MarqueeBorder : Panel, IMarqueeWidget + { + // + + // + public static int MaxLightSize = 10; + + // These fields back the public properties. + private int updatePeriodValue = 50; + private int lightSizeValue = 5; + private int lightPeriodValue = 3; + private int lightSpacingValue = 1; + private Color lightColorValue; + private Color darkColorValue; + private MarqueeSpinDirection spinDirectionValue = MarqueeSpinDirection.CW; + private MarqueeLightShape lightShapeValue = MarqueeLightShape.Square; + + // These brushes are used to paint the light and dark + // colors of the marquee lights. + private Brush lightBrush; + private Brush darkBrush; + + // This field tracks the progress of the "first" light as it + // "travels" around the marquee border. + private int currentOffset = 0; + + // This component updates the control asynchronously. + private System.ComponentModel.BackgroundWorker backgroundWorker1; + + public MarqueeBorder() + { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); + + // Initialize light and dark colors + // to the control's default values. + this.lightColorValue = this.ForeColor; + this.darkColorValue = this.BackColor; + this.lightBrush = new SolidBrush(this.lightColorValue); + this.darkBrush = new SolidBrush(this.darkColorValue); + + // The MarqueeBorder control manages its own padding, + // because it requires that any contained controls do + // not overlap any of the marquee lights. + int pad = 2 * (this.lightSizeValue + this.lightSpacingValue); + this.Padding = new Padding(pad, pad, pad, pad); + + SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + } + // + + /////////////////////////////////////////////////////////////////////// + #region IMarqueeWidget implementation + + // + public virtual void StartMarquee() + { + // The MarqueeBorder control may contain any number of + // controls that implement IMarqueeWidget, so find + // each IMarqueeWidget child and call its StartMarquee + // method. + foreach (Control cntrl in this.Controls) + { + if (cntrl is IMarqueeWidget) + { + IMarqueeWidget widget = cntrl as IMarqueeWidget; + widget.StartMarquee(); + } + } + + // Start the updating thread and pass it the UpdatePeriod. + this.backgroundWorker1.RunWorkerAsync(this.UpdatePeriod); + } + + public virtual void StopMarquee() + { + // The MarqueeBorder control may contain any number of + // controls that implement IMarqueeWidget, so find + // each IMarqueeWidget child and call its StopMarquee + // method. + foreach (Control cntrl in this.Controls) + { + if (cntrl is IMarqueeWidget) + { + IMarqueeWidget widget = cntrl as IMarqueeWidget; + widget.StopMarquee(); + } + } + + // Stop the updating thread. + this.backgroundWorker1.CancelAsync(); + } + + [Category("Marquee")] + [Browsable(true)] + public virtual int UpdatePeriod + { + get + { + return this.updatePeriodValue; + } + + set + { + if (value > 0) + { + this.updatePeriodValue = value; + } + else + { + throw new ArgumentOutOfRangeException("UpdatePeriod", "must be > 0"); + } + } + } + + // + + #endregion + + /////////////////////////////////////////////////////////////////////// + #region Public Properties + + // + [Category("Marquee")] + [Browsable(true)] + public int LightSize + { + get + { + return this.lightSizeValue; + } + + set + { + if (value > 0 && value <= MaxLightSize) + { + this.lightSizeValue = value; + this.DockPadding.All = 2 * value; + } + else + { + throw new ArgumentOutOfRangeException("LightSize", "must be > 0 and < MaxLightSize"); + } + } + } + + [Category("Marquee")] + [Browsable(true)] + public int LightPeriod + { + get + { + return this.lightPeriodValue; + } + + set + { + if (value > 0) + { + this.lightPeriodValue = value; + } + else + { + throw new ArgumentOutOfRangeException("LightPeriod", "must be > 0 "); + } + } + } + + [Category("Marquee")] + [Browsable(true)] + public Color LightColor + { + get + { + return this.lightColorValue; + } + + set + { + // The LightColor property is only changed if the + // client provides a different value. Comparing values + // from the ToArgb method is the recommended test for + // equality between Color structs. + if (this.lightColorValue.ToArgb() != value.ToArgb()) + { + this.lightColorValue = value; + this.lightBrush = new SolidBrush(value); + } + } + } + + [Category("Marquee")] + [Browsable(true)] + public Color DarkColor + { + get + { + return this.darkColorValue; + } + + set + { + // The DarkColor property is only changed if the + // client provides a different value. Comparing values + // from the ToArgb method is the recommended test for + // equality between Color structs. + if (this.darkColorValue.ToArgb() != value.ToArgb()) + { + this.darkColorValue = value; + this.darkBrush = new SolidBrush(value); + } + } + } + + [Category("Marquee")] + [Browsable(true)] + public int LightSpacing + { + get + { + return this.lightSpacingValue; + } + + set + { + if (value >= 0) + { + this.lightSpacingValue = value; + } + else + { + throw new ArgumentOutOfRangeException("LightSpacing", "must be >= 0"); + } + } + } + + [Category("Marquee")] + [Browsable(true)] + [EditorAttribute(typeof(LightShapeEditor), + typeof(System.Drawing.Design.UITypeEditor))] + public MarqueeLightShape LightShape + { + get + { + return this.lightShapeValue; + } + + set + { + this.lightShapeValue = value; + } + } + + [Category("Marquee")] + [Browsable(true)] + public MarqueeSpinDirection SpinDirection + { + get + { + return this.spinDirectionValue; + } + + set + { + this.spinDirectionValue = value; + } + } + + // + + #endregion + + /////////////////////////////////////////////////////////////////////// + #region Implementation + + // + protected override void OnLayout(LayoutEventArgs levent) + { + base.OnLayout(levent); + + // Repaint when the layout has changed. + this.Refresh(); + } + + // This method paints the lights around the border of the + // control. It paints the top row first, followed by the + // right side, the bottom row, and the left side. The color + // of each light is determined by the IsLit method and + // depends on the light's position relative to the value + // of currentOffset. + protected override void OnPaint(PaintEventArgs e) + { + Graphics g = e.Graphics; + g.Clear(this.BackColor); + + base.OnPaint(e); + + // If the control is large enough, draw some lights. + if (this.Width > MaxLightSize && + this.Height > MaxLightSize) + { + // The position of the next light will be incremented + // by this value, which is equal to the sum of the + // light size and the space between two lights. + int increment = + this.lightSizeValue + this.lightSpacingValue; + + // Compute the number of lights to be drawn along the + // horizontal edges of the control. + int horizontalLights = + (this.Width - increment) / increment; + + // Compute the number of lights to be drawn along the + // vertical edges of the control. + int verticalLights = + (this.Height - increment) / increment; + + // These local variables will be used to position and + // paint each light. + int xPos = 0; + int yPos = 0; + int lightCounter = 0; + Brush brush; + + // Draw the top row of lights. + for (int i = 0; i < horizontalLights; i++) + { + brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; + + DrawLight(g, brush, xPos, yPos); + + xPos += increment; + lightCounter++; + } + + // Draw the lights flush with the right edge of the control. + xPos = this.Width - this.lightSizeValue; + + // Draw the right column of lights. + for (int i = 0; i < verticalLights; i++) + { + brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; + + DrawLight(g, brush, xPos, yPos); + + yPos += increment; + lightCounter++; + } + + // Draw the lights flush with the bottom edge of the control. + yPos = this.Height - this.lightSizeValue; + + // Draw the bottom row of lights. + for (int i = 0; i < horizontalLights; i++) + { + brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; + + DrawLight(g, brush, xPos, yPos); + + xPos -= increment; + lightCounter++; + } + + // Draw the lights flush with the left edge of the control. + xPos = 0; + + // Draw the left column of lights. + for (int i = 0; i < verticalLights; i++) + { + brush = IsLit(lightCounter) ? this.lightBrush : this.darkBrush; + + DrawLight(g, brush, xPos, yPos); + + yPos -= increment; + lightCounter++; + } + } + } + // + + // + // This method determines if the marquee light at lightIndex + // should be lit. The currentOffset field specifies where + // the "first" light is located, and the "position" of the + // light given by lightIndex is computed relative to this + // offset. If this position modulo lightPeriodValue is zero, + // the light is considered to be on, and it will be painted + // with the control's lightBrush. + protected virtual bool IsLit(int lightIndex) + { + int directionFactor = + (this.spinDirectionValue == MarqueeSpinDirection.CW ? -1 : 1); + + return ( + (lightIndex + directionFactor * this.currentOffset) % this.lightPeriodValue == 0 + ); + } + + protected virtual void DrawLight( + Graphics g, + Brush brush, + int xPos, + int yPos) + { + switch (this.lightShapeValue) + { + case MarqueeLightShape.Square: + { + g.FillRectangle(brush, xPos, yPos, this.lightSizeValue, this.lightSizeValue); + break; + } + case MarqueeLightShape.Circle: + { + g.FillEllipse(brush, xPos, yPos, this.lightSizeValue, this.lightSizeValue); + break; + } + default: + { + Trace.Assert(false, "Unknown value for light shape."); + break; + } + } + } + // + + // + // This method is called in the worker thread's context, + // so it must not make any calls into the MarqueeBorder + // control. Instead, it communicates to the control using + // the ProgressChanged event. + // + // The only work done in this event handler is + // to sleep for the number of milliseconds specified + // by UpdatePeriod, then raise the ProgressChanged event. + private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) + { + BackgroundWorker worker = sender as BackgroundWorker; + + // This event handler will run until the client cancels + // the background task by calling CancelAsync. + while (!worker.CancellationPending) + { + // The Argument property of the DoWorkEventArgs + // object holds the value of UpdatePeriod, which + // was passed as the argument to the RunWorkerAsync + // method. + Thread.Sleep((int)e.Argument); + + // The DoWork eventhandler does not actually report + // progress; the ReportProgress event is used to + // periodically alert the control to update its state. + worker.ReportProgress(0); + } + } + + // The ProgressChanged event is raised by the DoWork method. + // This event handler does work that is internal to the + // control. In this case, the currentOffset is incremented, + // and the control is told to repaint itself. + private void backgroundWorker1_ProgressChanged( + object sender, + System.ComponentModel.ProgressChangedEventArgs e) + { + this.currentOffset++; + this.Refresh(); + } + // + + // + // + // This class demonstrates the use of a custom UITypeEditor. + // It allows the MarqueeBorder control's LightShape property + // to be changed at design time using a customized UI element + // that is invoked by the Properties window. The UI is provided + // by the LightShapeSelectionControl class. + internal class LightShapeEditor : UITypeEditor + { + // + + // + private IWindowsFormsEditorService editorService = null; + // + + // + public override UITypeEditorEditStyle GetEditStyle( + System.ComponentModel.ITypeDescriptorContext context) + { + return UITypeEditorEditStyle.DropDown; + } + // + + // + public override object EditValue( + ITypeDescriptorContext context, + IServiceProvider provider, + object value) + { + if (provider != null) + { + editorService = + provider.GetService( + typeof(IWindowsFormsEditorService)) + as IWindowsFormsEditorService; + } + + if (editorService != null) + { + LightShapeSelectionControl selectionControl = + new LightShapeSelectionControl( + (MarqueeLightShape)value, + editorService); + + editorService.DropDownControl(selectionControl); + + value = selectionControl.LightShape; + } + + return value; + } + // + + // + // This method indicates to the design environment that + // the type editor will paint additional content in the + // LightShape entry in the PropertyGrid. + public override bool GetPaintValueSupported( + ITypeDescriptorContext context) + { + return true; + } + + // This method paints a graphical representation of the + // selected value of the LightShpae property. + public override void PaintValue(PaintValueEventArgs e) + { + MarqueeLightShape shape = (MarqueeLightShape)e.Value; + using (Pen p = Pens.Black) + { + if (shape == MarqueeLightShape.Square) + { + e.Graphics.DrawRectangle(p, e.Bounds); + } + else + { + e.Graphics.DrawEllipse(p, e.Bounds); + } + } + } + // + } + // + + private void InitializeComponent() + { + this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); + +// +// backgroundWorker1 +// + this.backgroundWorker1.WorkerReportsProgress = true; + this.backgroundWorker1.WorkerSupportsCancellation = true; + this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged); + this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); + } + + #endregion + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs new file mode 100644 index 0000000000..11815acfa4 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueeborderdesigner.cs @@ -0,0 +1,90 @@ +// +// +using System; +using System.Collections; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Windows.Forms; +using System.Windows.Forms.Design; +// + +// +namespace MarqueeControlLibrary.Design +{ + [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] + public class MarqueeBorderDesigner : ParentControlDesigner + { + // + + public MarqueeBorderDesigner() + { + Trace.WriteLine("MarqueeBorderDesigner"); + } + + // + public bool Visible + { + get + { + return (bool)ShadowProperties["Visible"]; + } + set + { + this.ShadowProperties["Visible"] = value; + } + } + + public bool Enabled + { + get + { + return (bool)ShadowProperties["Enabled"]; + } + set + { + this.ShadowProperties["Enabled"] = value; + } + } + // + + // + protected override void PreFilterProperties(IDictionary properties) + { + base.PreFilterProperties(properties); + + if (properties.Contains("Padding")) + { + properties.Remove("Padding"); + } + + properties["Visible"] = TypeDescriptor.CreateProperty( + typeof(MarqueeBorderDesigner), + (PropertyDescriptor)properties["Visible"], + new Attribute[0]); + + properties["Enabled"] = TypeDescriptor.CreateProperty( + typeof(MarqueeBorderDesigner), + (PropertyDescriptor)properties["Enabled"], + new Attribute[0]); + } + // + + // + private void OnVerbRunTest(object sender, EventArgs e) + { + IMarqueeWidget widget = this.Control as IMarqueeWidget; + + widget.StartMarquee(); + } + + private void OnVerbStopTest(object sender, EventArgs e) + { + IMarqueeWidget widget = this.Control as IMarqueeWidget; + + widget.StopMarquee(); + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs new file mode 100644 index 0000000000..5ef6061fca --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrol.cs @@ -0,0 +1,115 @@ +// +// +using System; +using System.Collections; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.Design; +// + +namespace MarqueeControlLibrary +{ + // + [Designer( typeof( MarqueeControlLibrary.Design.MarqueeControlRootDesigner ), typeof( IRootDesigner ) )] + public class MarqueeControl : UserControl + { + // + + // Required designer variable. + private System.ComponentModel.Container components = null; + + // + public MarqueeControl() + { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); + + // Minimize flickering during animation by enabling + // double buffering. + SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + } + // + + /// + /// Clean up any resources being used. + /// + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if(components != null) + { + components.Dispose(); + } + } + base.Dispose( disposing ); + } + + // + public void Start() + { + // The MarqueeControl may contain any number of + // controls that implement IMarqueeWidget, so + // find each IMarqueeWidget child and call its + // StartMarquee method. + foreach( Control cntrl in this.Controls ) + { + if( cntrl is IMarqueeWidget ) + { + IMarqueeWidget widget = cntrl as IMarqueeWidget; + widget.StartMarquee(); + } + } + } + + public void Stop() + { + // The MarqueeControl may contain any number of + // controls that implement IMarqueeWidget, so find + // each IMarqueeWidget child and call its StopMarquee + // method. + foreach( Control cntrl in this.Controls ) + { + if( cntrl is IMarqueeWidget ) + { + IMarqueeWidget widget = cntrl as IMarqueeWidget; + widget.StopMarquee(); + } + } + } + // + + // + protected override void OnLayout(LayoutEventArgs levent) + { + base.OnLayout (levent); + + // Repaint all IMarqueeWidget children if the layout + // has changed. + foreach( Control cntrl in this.Controls ) + { + if( cntrl is IMarqueeWidget ) + { + Control control = cntrl as Control; + + control.PerformLayout(); + } + } + } + // + + #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(); + } + #endregion + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs new file mode 100644 index 0000000000..43e5880feb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueecontrolrootdesigner.cs @@ -0,0 +1,90 @@ +// +// +using System; +using System.Collections; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing.Design; +using System.Windows.Forms; +using System.Windows.Forms.Design; +// + +// +namespace MarqueeControlLibrary.Design +{ + [ToolboxItemFilter("MarqueeControlLibrary.MarqueeBorder", ToolboxItemFilterType.Require)] + [ToolboxItemFilter("MarqueeControlLibrary.MarqueeText", ToolboxItemFilterType.Require)] + [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] + public class MarqueeControlRootDesigner : DocumentDesigner + { + // + + // + public MarqueeControlRootDesigner() + { + Trace.WriteLine("MarqueeControlRootDesigner ctor"); + } + // + + // + public override void Initialize(IComponent component) + { + // + base.Initialize(component); + + IComponentChangeService cs = + GetService(typeof(IComponentChangeService)) + as IComponentChangeService; + + if (cs != null) + { + cs.ComponentChanged += + new ComponentChangedEventHandler(OnComponentChanged); + } + // + + // + this.Verbs.Add( + new DesignerVerb("Run Test", + new EventHandler(OnVerbRunTest)) + ); + + this.Verbs.Add( + new DesignerVerb("Stop Test", + new EventHandler(OnVerbStopTest)) + ); + // + } + // + + // + private void OnComponentChanged( + object sender, + ComponentChangedEventArgs e) + { + if (e.Component is IMarqueeWidget) + { + this.Control.Refresh(); + } + } + // + + // + private void OnVerbRunTest(object sender, EventArgs e) + { + MarqueeControl c = this.Control as MarqueeControl; + + c.Start(); + } + + private void OnVerbStopTest(object sender, EventArgs e) + { + MarqueeControl c = this.Control as MarqueeControl; + + c.Stop(); + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs new file mode 100644 index 0000000000..c8c3646570 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/CS/marqueetext.cs @@ -0,0 +1,223 @@ +// +// +using System; +using System.ComponentModel; +using System.ComponentModel.Design; +using System.Diagnostics; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; +using System.Windows.Forms.Design; +// + +namespace MarqueeControlLibrary +{ + // + [ToolboxItemFilter("MarqueeControlLibrary.MarqueeText", ToolboxItemFilterType.Require)] + public partial class MarqueeText : Label, IMarqueeWidget + { + // + + // + // When isLit is true, the text is painted in the light color; + // When isLit is false, the text is painted in the dark color. + // This value changes whenever the BackgroundWorker component + // raises the ProgressChanged event. + private bool isLit = true; + + // These fields back the public properties. + private int updatePeriodValue = 50; + private Color lightColorValue; + private Color darkColorValue; + + // These brushes are used to paint the light and dark + // colors of the text. + private Brush lightBrush; + private Brush darkBrush; + + // This component updates the control asynchronously. + private BackgroundWorker backgroundWorker1; + + public MarqueeText() + { + // This call is required by the Windows.Forms Form Designer. + InitializeComponent(); + + // Initialize light and dark colors + // to the control's default values. + this.lightColorValue = this.ForeColor; + this.darkColorValue = this.BackColor; + this.lightBrush = new SolidBrush(this.lightColorValue); + this.darkBrush = new SolidBrush(this.darkColorValue); + } + // + + /////////////////////////////////////////////////////////////////////// + #region IMarqueeWidget implementation + + // + public virtual void StartMarquee() + { + // Start the updating thread and pass it the UpdatePeriod. + this.backgroundWorker1.RunWorkerAsync(this.UpdatePeriod); + } + + public virtual void StopMarquee() + { + // Stop the updating thread. + this.backgroundWorker1.CancelAsync(); + } + + [Category("Marquee")] + [Browsable(true)] + public int UpdatePeriod + { + get + { + return this.updatePeriodValue; + } + + set + { + if (value > 0) + { + this.updatePeriodValue = value; + } + else + { + throw new ArgumentOutOfRangeException("UpdatePeriod", "must be > 0"); + } + } + } + // + + #endregion + + /////////////////////////////////////////////////////////////////////// + #region Public Properties + + // + [Category("Marquee")] + [Browsable(true)] + public Color LightColor + { + get + { + return this.lightColorValue; + } + set + { + // The LightColor property is only changed if the + // client provides a different value. Comparing values + // from the ToArgb method is the recommended test for + // equality between Color structs. + if (this.lightColorValue.ToArgb() != value.ToArgb()) + { + this.lightColorValue = value; + this.lightBrush = new SolidBrush(value); + } + } + } + + [Category("Marquee")] + [Browsable(true)] + public Color DarkColor + { + get + { + return this.darkColorValue; + } + set + { + // The DarkColor property is only changed if the + // client provides a different value. Comparing values + // from the ToArgb method is the recommended test for + // equality between Color structs. + if (this.darkColorValue.ToArgb() != value.ToArgb()) + { + this.darkColorValue = value; + this.darkBrush = new SolidBrush(value); + } + } + } + // + + #endregion + + /////////////////////////////////////////////////////////////////////// + #region Implementation + + // + protected override void OnPaint(PaintEventArgs e) + { + // The text is painted in the light or dark color, + // depending on the current value of isLit. + this.ForeColor = + this.isLit ? this.lightColorValue : this.darkColorValue; + + base.OnPaint(e); + } + // + + // + // This method is called in the worker thread's context, + // so it must not make any calls into the MarqueeText control. + // Instead, it communicates to the control using the + // ProgressChanged event. + // + // The only work done in this event handler is + // to sleep for the number of milliseconds specified + // by UpdatePeriod, then raise the ProgressChanged event. + private void backgroundWorker1_DoWork( + object sender, + System.ComponentModel.DoWorkEventArgs e) + { + BackgroundWorker worker = sender as BackgroundWorker; + + // This event handler will run until the client cancels + // the background task by calling CancelAsync. + while (!worker.CancellationPending) + { + // The Argument property of the DoWorkEventArgs + // object holds the value of UpdatePeriod, which + // was passed as the argument to the RunWorkerAsync + // method. + Thread.Sleep((int)e.Argument); + + // The DoWork eventhandler does not actually report + // progress; the ReportProgress event is used to + // periodically alert the control to update its state. + worker.ReportProgress(0); + } + } + + // The ProgressChanged event is raised by the DoWork method. + // This event handler does work that is internal to the + // control. In this case, the text is toggled between its + // light and dark state, and the control is told to + // repaint itself. + private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) + { + this.isLit = !this.isLit; + this.Refresh(); + } + + // + + private void InitializeComponent() + { + this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); + +// +// backgroundWorker1 +// + this.backgroundWorker1.WorkerReportsProgress = true; + this.backgroundWorker1.WorkerSupportsCancellation = true; + this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged); + this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); + } + + #endregion + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/CS/form1.cs new file mode 100644 index 0000000000..7b2e18f2cf --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/CS/form1.cs @@ -0,0 +1,37 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace DetermineModifierKey +{ + class Form1 : Form + { + TextBox TextBox1 = new TextBox(); + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + TextBox1.KeyPress += + new KeyPressEventHandler(TextBox1_KeyPress); + this.Controls.Add(TextBox1); + } + + // + public void TextBox1_KeyPress(object sender, KeyPressEventArgs e) + { + if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) + { + MessageBox.Show("Pressed " + Keys.Shift); + } + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs new file mode 100644 index 0000000000..7a11c86eeb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/CS/Form1.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; +// +using System.IO; +// +namespace ExplorerStyleInterface +{ + public class Form1 : Form + { + private SplitContainer splitContainer1; + private TreeView treeView1; + private ImageList imageList1; + private IContainer components; + private ColumnHeader nameColumn; + private ColumnHeader typeColumn; + private ColumnHeader modifiedColumn; + private ListView listView1; + + // + public Form1() + { + InitializeComponent(); + PopulateTreeView(); + } + // + // + void treeView1_NodeMouseClick(object sender, + TreeNodeMouseClickEventArgs e) + { + TreeNode newSelected = e.Node; + listView1.Items.Clear(); + DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag; + ListViewItem.ListViewSubItem[] subItems; + ListViewItem item = null; + + foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories()) + { + item = new ListViewItem(dir.Name, 0); + subItems = new ListViewItem.ListViewSubItem[] + {new ListViewItem.ListViewSubItem(item, "Directory"), + new ListViewItem.ListViewSubItem(item, + dir.LastAccessTime.ToShortDateString())}; + item.SubItems.AddRange(subItems); + listView1.Items.Add(item); + } + foreach (FileInfo file in nodeDirInfo.GetFiles()) + { + item = new ListViewItem(file.Name, 1); + subItems = new ListViewItem.ListViewSubItem[] + { new ListViewItem.ListViewSubItem(item, "File"), + new ListViewItem.ListViewSubItem(item, + file.LastAccessTime.ToShortDateString())}; + + item.SubItems.AddRange(subItems); + listView1.Items.Add(item); + } + + listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); + } + // + + // + private void PopulateTreeView() + { + TreeNode rootNode; + + DirectoryInfo info = new DirectoryInfo(@"../.."); + if (info.Exists) + { + rootNode = new TreeNode(info.Name); + rootNode.Tag = info; + GetDirectories(info.GetDirectories(), rootNode); + treeView1.Nodes.Add(rootNode); + } + } + + private void GetDirectories(DirectoryInfo[] subDirs, + TreeNode nodeToAddTo) + { + TreeNode aNode; + DirectoryInfo[] subSubDirs; + foreach (DirectoryInfo subDir in subDirs) + { + aNode = new TreeNode(subDir.Name, 0, 0); + aNode.Tag = subDir; + aNode.ImageKey = "folder"; + subSubDirs = subDir.GetDirectories(); + if (subSubDirs.Length != 0) + { + GetDirectories(subSubDirs, aNode); + } + nodeToAddTo.Nodes.Add(aNode); + } + } + // + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); + this.splitContainer1 = new System.Windows.Forms.SplitContainer(); + this.treeView1 = new System.Windows.Forms.TreeView(); + this.imageList1 = new System.Windows.Forms.ImageList(this.components); + this.listView1 = new System.Windows.Forms.ListView(); + this.nameColumn = new System.Windows.Forms.ColumnHeader(""); + this.typeColumn = new System.Windows.Forms.ColumnHeader(""); + this.modifiedColumn = new System.Windows.Forms.ColumnHeader(""); + this.splitContainer1.Panel1.SuspendLayout(); + this.splitContainer1.Panel2.SuspendLayout(); + this.splitContainer1.SuspendLayout(); + this.SuspendLayout(); + // + // splitContainer1 + // + this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; + this.splitContainer1.Location = new System.Drawing.Point(0, 0); + this.splitContainer1.Name = "splitContainer1"; + // + // Panel1 + // + this.splitContainer1.Panel1.Controls.Add(this.treeView1); + // + // Panel2 + // + this.splitContainer1.Panel2.Controls.Add(this.listView1); + this.splitContainer1.Size = new System.Drawing.Size(492, 466); + this.splitContainer1.SplitterDistance = 166; + this.splitContainer1.TabIndex = 0; + this.splitContainer1.Text = "splitContainer1"; + // + // treeView1 + // + this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill; + this.treeView1.ImageList = this.imageList1; + this.treeView1.Location = new System.Drawing.Point(0, 0); + this.treeView1.Name = "treeView1"; + this.treeView1.Size = new System.Drawing.Size(166, 466); + this.treeView1.TabIndex = 0; + // + this.treeView1.NodeMouseClick += + new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick); + // + + // imageList1 + // + this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); + this.imageList1.Images.SetKeyName(0, "FOLDER.ICO"); + this.imageList1.Images.SetKeyName(1, "DOC.ICO"); + // + // listView1 + // + this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.nameColumn, + this.typeColumn, + this.modifiedColumn}); + this.listView1.Dock = System.Windows.Forms.DockStyle.Fill; + this.listView1.Location = new System.Drawing.Point(0, 0); + this.listView1.Name = "listView1"; + this.listView1.Size = new System.Drawing.Size(322, 466); + this.listView1.SmallImageList = this.imageList1; + this.listView1.TabIndex = 0; + this.listView1.View = System.Windows.Forms.View.Details; + // + // nameColumn + // + this.nameColumn.Text = "Name"; + this.nameColumn.Width = 82; + // + // typeColumn + // + this.typeColumn.Text = "Type"; + this.typeColumn.Width = 78; + // + // modifiedColumn + // + this.modifiedColumn.Text = "Last Modified"; + this.modifiedColumn.Width = 109; + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(492, 466); + this.Controls.Add(this.splitContainer1); + this.Name = "Form1"; + this.splitContainer1.Panel1.ResumeLayout(false); + this.splitContainer1.Panel2.ResumeLayout(false); + this.splitContainer1.ResumeLayout(false); + this.ResumeLayout(false); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs new file mode 100644 index 0000000000..2920b879c8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/FirstControl.cs @@ -0,0 +1,84 @@ +// +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +namespace CustomWinControls +{ + // + public class FirstControl : Control + { + // + + public FirstControl() + { + } + + // + // ContentAlignment is an enumeration defined in the System.Drawing + // namespace that specifies the alignment of content on a drawing + // surface. + private ContentAlignment alignmentValue = ContentAlignment.MiddleLeft; + // + + // + [ + Category("Alignment"), + Description("Specifies the alignment of text.") + ] + // + // + // + public ContentAlignment TextAlignment + { + // + + get + { + return alignmentValue; + } + set + { + alignmentValue = value; + + // The Invalidate method invokes the OnPaint method described + // in step 3. + Invalidate(); + } + } + // + + // + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + StringFormat style = new StringFormat(); + style.Alignment = StringAlignment.Near; + switch (alignmentValue) + { + case ContentAlignment.MiddleLeft: + style.Alignment = StringAlignment.Near; + break; + case ContentAlignment.MiddleRight: + style.Alignment = StringAlignment.Far; + break; + case ContentAlignment.MiddleCenter: + style.Alignment = StringAlignment.Center; + break; + } + + // Call the DrawString method of the System.Drawing class to write + // text. Text and ClientRectangle are properties inherited from + // Control. + e.Graphics.DrawString( + Text, + Font, + new SolidBrush(ForeColor), + ClientRectangle, style); + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/SimpleForm.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/SimpleForm.cs new file mode 100644 index 0000000000..4bb6e4fda1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/SimpleForm.cs @@ -0,0 +1,67 @@ +// +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; + +namespace CustomWinControls +{ + + public class SimpleForm : System.Windows.Forms.Form + { + private FirstControl firstControl1; + + private System.ComponentModel.Container components = null; + + public SimpleForm() + { + InitializeComponent(); + } + + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose( disposing ); + } + + private void InitializeComponent() + { + this.firstControl1 = new FirstControl(); + this.SuspendLayout(); + + // + // firstControl1 + // + this.firstControl1.BackColor = System.Drawing.SystemColors.ControlDark; + this.firstControl1.Location = new System.Drawing.Point(96, 104); + this.firstControl1.Name = "firstControl1"; + this.firstControl1.Size = new System.Drawing.Size(75, 16); + this.firstControl1.TabIndex = 0; + this.firstControl1.Text = "Hello World"; + this.firstControl1.TextAlignment = System.Drawing.ContentAlignment.MiddleCenter; + + // + // SimpleForm + // + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.firstControl1); + this.Name = "SimpleForm"; + this.Text = "SimpleForm"; + this.ResumeLayout(false); + } + + [STAThread] + static void Main() + { + Application.Run(new SimpleForm()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/makefile new file mode 100644 index 0000000000..3c73599916 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/CS/makefile @@ -0,0 +1,8 @@ +SimpleForm.exe: SimpleForm.cs FirstControl.dll + csc /r:FirstControl.dll /t:exe /out:SimpleForm.exe SimpleForm.cs + +FirstControl.dll: FirstControl.cs + csc /t:library /out:FirstControl.dll FirstControl.cs + +clean: + del *.exe *.dll *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs new file mode 100644 index 0000000000..1e90772198 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBar.cs @@ -0,0 +1,511 @@ +// +namespace Microsoft.Samples.WinForms.Cs.FlashTrackBar { + using System; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Design; + using System.Windows.Forms; + using System.Diagnostics; + + [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] + public class FlashTrackBar : System.Windows.Forms.Control { + /// + /// Required designer variable. + /// + private System.ComponentModel.Container components; + + private const int LeftRightBorder = 10; + private int value = 0; + private int min = 0; + private int max = 100; + private bool showPercentage = false; + private bool showValue = false; + private bool allowUserEdit = true; + private bool showGradient = true; + private int dragValue = 0; + private bool dragging = false; + private Color startColor = Color.Red; + private Color endColor = Color.LimeGreen; + private EventHandler onValueChanged; + // + private Brush baseBackground = null; + // + private Brush backgroundDim = null; + private byte darkenBy = 200; + + public FlashTrackBar() { + // + // Required for Windows Form Designer support + // + InitializeComponent(); + + SetStyle(ControlStyles.Opaque, true); + SetStyle(ControlStyles.ResizeRedraw, true); + Debug.Assert(GetStyle(ControlStyles.ResizeRedraw), "Should be redraw!"); + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose(bool disposing) + { + if (disposing) { + if (components != null) { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + void InitializeComponent () { + this.components = new System.ComponentModel.Container (); + this.ForeColor = System.Drawing.Color.White; + this.BackColor = System.Drawing.Color.Black; + this.Size = new System.Drawing.Size(100, 23); + this.Text = "FlashTrackBar"; + } + + [ + Category("Flash"), + DefaultValue(true) + ] + public bool AllowUserEdit { + get { + return allowUserEdit; + } + set { + if (value != allowUserEdit) { + allowUserEdit = value; + if (!allowUserEdit) { + Capture = false; + dragging = false; + } + } + } + } + + [ + Category("Flash") + ] + public Color EndColor { + get { + return endColor; + } + set { + endColor = value; + if (baseBackground != null && showGradient) { + baseBackground.Dispose(); + baseBackground = null; + } + Invalidate(); + } + } + + public bool ShouldSerializeEndColor() { + return !(endColor == Color.LimeGreen); + } + + [ + Category("Flash"), + Editor(typeof(FlashTrackBarDarkenByEditor), typeof(UITypeEditor)), + DefaultValue((byte)200) + ] + public byte DarkenBy { + get { + return darkenBy; + } + set { + if (value != darkenBy) { + darkenBy = value; + if (backgroundDim != null) { + backgroundDim.Dispose(); + backgroundDim = null; + } + OptimizedInvalidate(Value, max); + } + } + } + + [ + Category("Flash"), + DefaultValue(100) + ] + public int Max { + get { + return max; + } + set { + if (max != value) { + max = value; + Invalidate(); + } + } + } + + [ + Category("Flash"), + DefaultValue(0) + ] + public int Min { + get { + return min; + } + set { + if (min != value) { + min = value; + Invalidate(); + } + } + } + + [ + Category("Flash") + ] + public Color StartColor { + get { + return startColor; + } + set { + startColor = value; + if (baseBackground != null && showGradient) { + baseBackground.Dispose(); + baseBackground = null; + } + Invalidate(); + } + } + + public bool ShouldSerializeStartColor() { + return !(startColor == Color.Red); + } + + [ + Category("Flash"), + RefreshProperties(RefreshProperties.Repaint), + DefaultValue(false) + ] + public bool ShowPercentage { + get { + return showPercentage; + } + set { + if (value != showPercentage) { + showPercentage = value; + if (showPercentage) { + showValue = false; + } + Invalidate(); + } + } + } + + [ + Category("Flash"), + RefreshProperties(RefreshProperties.Repaint), + DefaultValue(false) + ] + public bool ShowValue { + get { + return showValue; + } + set { + if (value != showValue) { + showValue = value; + if (showValue) { + showPercentage = false; + } + Invalidate(); + } + } + } + + [ + Category("Flash"), + DefaultValue(true) + ] + public bool ShowGradient { + get { + return showGradient; + } + set { + if (value != showGradient) { + showGradient = value; + if (baseBackground != null) { + baseBackground.Dispose(); + baseBackground = null; + } + Invalidate(); + } + } + } + + [ + Category("Flash"), + Editor(typeof(FlashTrackBarValueEditor), typeof(UITypeEditor)), + DefaultValue(0) + ] + public int Value { + get { + if (dragging) { + return dragValue; + } + return value; + } + set { + if (value != this.value) { + int old = this.value; + this.value = value; + OnValueChanged(EventArgs.Empty); + OptimizedInvalidate(old, this.value); + } + } + } + + // ValueChanged Event + [Description("Raised when the Value displayed changes")] + public event EventHandler ValueChanged { + add { + onValueChanged += value; + } + remove { + onValueChanged -= value; + } + } + + private void OptimizedInvalidate(int oldValue, int newValue) { + Rectangle client = ClientRectangle; + + float oldPercentValue = ((float)oldValue / ((float)Max - (float)Min)); + int oldNonDimLength = (int)(oldPercentValue * (float)client.Width); + + float newPercentValue = ((float)newValue / ((float)Max - (float)Min)); + int newNonDimLength = (int)(newPercentValue * (float)client.Width); + + int min = Math.Min(oldNonDimLength, newNonDimLength); + int max = Math.Max(oldNonDimLength, newNonDimLength); + + // + Rectangle invalid = new Rectangle( + client.X + min, + client.Y, + max - min, + client.Height); + + Invalidate(invalid); + // + + string oldToDisplay; + string newToDisplay; + + if (ShowPercentage) { + oldToDisplay = Convert.ToString((int)(oldPercentValue * 100f)) + "%"; + newToDisplay = Convert.ToString((int)(newPercentValue * 100f)) + "%"; + } + else if (ShowValue) { + oldToDisplay = Convert.ToString(oldValue); + newToDisplay = Convert.ToString(newValue); + } + else { + oldToDisplay = null; + newToDisplay = null; + } + + if (oldToDisplay != null && newToDisplay != null) { + Graphics g = CreateGraphics(); + SizeF oldFontSize = g.MeasureString(oldToDisplay, Font); + SizeF newFontSize = g.MeasureString(newToDisplay, Font); + RectangleF oldFontRect = new RectangleF(new PointF(0, 0), oldFontSize); + RectangleF newFontRect = new RectangleF(new PointF(0, 0), newFontSize); + oldFontRect.X = (client.Width - oldFontRect.Width) / 2; + oldFontRect.Y = (client.Height - oldFontRect.Height) / 2; + newFontRect.X = (client.Width - newFontRect.Width) / 2; + newFontRect.Y = (client.Height - newFontRect.Height) / 2; + + Invalidate(new Rectangle((int)oldFontRect.X, (int)oldFontRect.Y, (int)oldFontRect.Width, (int)oldFontRect.Height)); + Invalidate(new Rectangle((int)newFontRect.X, (int)newFontRect.Y, (int)newFontRect.Width, (int)newFontRect.Height)); + } + } + + // + protected override void OnMouseDown(MouseEventArgs e) { + base.OnMouseDown(e); + if (!allowUserEdit) { + return; + } + Capture = true; + dragging = true; + SetDragValue(new Point(e.X, e.Y)); + } + // + + // + protected override void OnMouseMove(MouseEventArgs e) { + base.OnMouseMove(e); + if (!allowUserEdit || !dragging) { + return; + } + SetDragValue(new Point(e.X, e.Y)); + } + // + + // + protected override void OnMouseUp(MouseEventArgs e) { + base.OnMouseUp(e); + if (!allowUserEdit || !dragging) { + return; + } + Capture = false; + dragging = false; + value = dragValue; + OnValueChanged(EventArgs.Empty); + } + // + + protected override void OnPaint(PaintEventArgs e) { + + // + base.OnPaint(e); + if (baseBackground == null) { + if (showGradient) { + baseBackground = new LinearGradientBrush(new Point(0, 0), + new Point(ClientSize.Width, 0), + StartColor, + EndColor); + } + else if (BackgroundImage != null) { + baseBackground = new TextureBrush(BackgroundImage); + } + else { + baseBackground = new SolidBrush(BackColor); + } + } + // + + backgroundDim ??= new SolidBrush(Color.FromArgb(DarkenBy, Color.Black)); + + Rectangle toDim = ClientRectangle; + float percentValue = ((float)Value / ((float)Max - (float)Min)); + int nonDimLength = (int)(percentValue * (float)toDim.Width); + toDim.X += nonDimLength; + toDim.Width -= nonDimLength; + + string text = Text; + string toDisplay = null; + RectangleF textRect = new RectangleF(); + + if (ShowPercentage || ShowValue || text.Length > 0) { + + if (ShowPercentage) { + toDisplay = Convert.ToString((int)(percentValue * 100f)) + "%"; + } + else if (ShowValue) { + toDisplay = Convert.ToString(Value); + } + else { + toDisplay = text; + } + + SizeF textSize = e.Graphics.MeasureString(toDisplay, Font); + textRect.Width = textSize.Width; + textRect.Height = textSize.Height; + textRect.X = (ClientRectangle.Width - textRect.Width) / 2; + textRect.Y = (ClientRectangle.Height - textRect.Height) / 2; + } + + e.Graphics.FillRectangle(baseBackground, ClientRectangle); + e.Graphics.FillRectangle(backgroundDim, toDim); + e.Graphics.Flush(); + if (toDisplay != null && toDisplay.Length > 0) { + e.Graphics.DrawString(toDisplay, Font, new SolidBrush(ForeColor), textRect); + } + } + + // + protected override void OnTextChanged(EventArgs e) { + base.OnTextChanged(e); + Invalidate(); + } + + protected override void OnBackColorChanged(EventArgs e) { + base.OnBackColorChanged(e); + if ((baseBackground != null) && (!showGradient)) { + baseBackground.Dispose(); + baseBackground = null; + } + } + // + + protected override void OnBackgroundImageChanged(EventArgs e) { + base.OnTextChanged(e); + if ((baseBackground != null) && (!showGradient)) { + baseBackground.Dispose(); + baseBackground = null; + } + } + + // + protected override void OnResize(EventArgs e) { + base.OnResize(e); + if (baseBackground != null) { + baseBackground.Dispose(); + baseBackground = null; + } + } + // + + protected virtual void OnValueChanged(EventArgs e) { + if (onValueChanged != null) { + onValueChanged.Invoke(this, e); + } + } + + private void SetDragValue(Point mouseLocation) { + + Rectangle client = ClientRectangle; + + if (client.Contains(mouseLocation)) { + float percentage = (float)mouseLocation.X / (float)ClientRectangle.Width; + int newDragValue = (int)(percentage * (float)(max - min)); + if (newDragValue != dragValue) { + int old = dragValue; + dragValue = newDragValue; + OptimizedInvalidate(old, dragValue); + } + } + else { + if (client.Y <= mouseLocation.Y && mouseLocation.Y <= client.Y + client.Height) { + if (mouseLocation.X <= client.X && mouseLocation.X > client.X - LeftRightBorder) { + int newDragValue = min; + if (newDragValue != dragValue) { + int old = dragValue; + dragValue = newDragValue; + OptimizedInvalidate(old, dragValue); + } + } + else if (mouseLocation.X >= client.X + client.Width && mouseLocation.X < client.X + client.Width + LeftRightBorder) { + int newDragValue = max; + if (newDragValue != dragValue) { + int old = dragValue; + dragValue = newDragValue; + OptimizedInvalidate(old, dragValue); + } + } + } + else { + if (dragValue != value) { + int old = dragValue; + dragValue = value; + OptimizedInvalidate(old, dragValue); + } + } + } + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarDarkenByEditor.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarDarkenByEditor.cs new file mode 100644 index 0000000000..b1a34aa07d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarDarkenByEditor.cs @@ -0,0 +1,23 @@ +// +namespace Microsoft.Samples.WinForms.Cs.FlashTrackBar { + using System; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Diagnostics; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Design; + using System.Windows.Forms; + using System.Windows.Forms.ComponentModel; + using System.Windows.Forms.Design; + + public class FlashTrackBarDarkenByEditor : FlashTrackBarValueEditor { + protected override void SetEditorProps(FlashTrackBar editingInstance, FlashTrackBar editor) { + base.SetEditorProps(editingInstance, editor); + editor.Min = 0; + editor.Max = byte.MaxValue; + } + } +} + +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarValueEditor.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarValueEditor.cs new file mode 100644 index 0000000000..8651f9b1e6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/FlashTrackBarValueEditor.cs @@ -0,0 +1,76 @@ +// +namespace Microsoft.Samples.WinForms.Cs.FlashTrackBar { + using System; + using System.ComponentModel; + using System.ComponentModel.Design; + using System.Diagnostics; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Design; + using System.Windows.Forms; + using System.Windows.Forms.ComponentModel; + using System.Windows.Forms.Design; + + [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")] + public class FlashTrackBarValueEditor : System.Drawing.Design.UITypeEditor { + + private IWindowsFormsEditorService edSvc = null; + + protected virtual void SetEditorProps(FlashTrackBar editingInstance, FlashTrackBar editor) { + editor.ShowValue = true; + editor.StartColor = Color.Navy; + editor.EndColor = Color.White; + editor.ForeColor = Color.White; + editor.Min = editingInstance.Min; + editor.Max = editingInstance.Max; + } + + public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { + + if (context != null + && context.Instance != null + && provider != null) { + + edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); + + if (edSvc != null) { + FlashTrackBar trackBar = new FlashTrackBar(); + trackBar.ValueChanged += new EventHandler(this.ValueChanged); + SetEditorProps((FlashTrackBar)context.Instance, trackBar); + bool asInt = true; + if (value is int) { + trackBar.Value = (int)value; + } + else if (value is byte) { + asInt = false; + trackBar.Value = (byte)value; + } + edSvc.DropDownControl(trackBar); + if (asInt) { + value = trackBar.Value; + } + else { + value = (byte)trackBar.Value; + } + } + } + + return value; + } + + public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { + if (context != null && context.Instance != null) { + return UITypeEditorEditStyle.DropDown; + } + return base.GetEditStyle(context); + } + + private void ValueChanged(object sender, EventArgs e) { + if (edSvc != null) { + edSvc.CloseDropDown(); + } + } + } +} + +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/HostApp.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/HostApp.cs new file mode 100644 index 0000000000..a3ce2d760f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/HostApp.cs @@ -0,0 +1,65 @@ +// +namespace Microsoft.Samples.WinForms.Cs.HostApp { + using System; + using System.ComponentModel; + using System.Drawing; + using System.Windows.Forms; + using Microsoft.Samples.WinForms.Cs.FlashTrackBar; + + public class HostApp : System.Windows.Forms.Form { + /// + /// Required designer variable. + /// + private System.ComponentModel.Container components; + protected internal Microsoft.Samples.WinForms.Cs.FlashTrackBar.FlashTrackBar flashTrackBar1; + + public HostApp() { + // + // Required for Windows Form Designer support + // + InitializeComponent(); + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose(bool disposing) + { + if (disposing) { + if (components != null) { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + this.components = new System.ComponentModel.Container (); + this.flashTrackBar1 = new Microsoft.Samples.WinForms.Cs.FlashTrackBar.FlashTrackBar (); + this.Text = "Control Example"; + this.ClientSize = new System.Drawing.Size (600, 450); + flashTrackBar1.BackColor = System.Drawing.Color.Black; + flashTrackBar1.Dock = System.Windows.Forms.DockStyle.Fill; + flashTrackBar1.TabIndex = 0; + flashTrackBar1.ForeColor = System.Drawing.Color.White; + flashTrackBar1.Text = "Drag the Mouse and say Wow!"; + flashTrackBar1.Value = 73; + flashTrackBar1.Size = new System.Drawing.Size (600, 450); + this.Controls.Add (this.flashTrackBar1); + } + + /// + /// The main entry point for the application. + /// + [STAThread] + public static void Main(string[] args) { + Application.Run(new HostApp()); + } + } +} + +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/makefile b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/makefile new file mode 100644 index 0000000000..157ea19aa6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/CS/makefile @@ -0,0 +1,5 @@ +FlashTrackBarText.exe: FlashTrackBar.cs FlashTrackBarDarkenByEditor.cs FlashTrackBarValueEditor.cs HostApp.cs + csc /t:exe /out:FlashTrackBar.exe FlashTrackBar.cs FlashTrackBarDarkenByEditor.cs FlashTrackBarValueEditor.cs HostApp.cs + +clean: + del *.exe *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/CS/FlpAnchorExampleForm.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/CS/FlpAnchorExampleForm.cs new file mode 100644 index 0000000000..2059586354 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/CS/FlpAnchorExampleForm.cs @@ -0,0 +1,223 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +public class Form1 : Form +{ + public Form1() + { + InitializeComponent(); + } + private FlowLayoutPanel flowLayoutPanel3; + private Label label2; + private Button button11; + private Button button12; + private Button button13; + private Button button14; + private Button button15; + private FlowLayoutPanel flowLayoutPanel1; + private Label label1; + private Button button1; + private Button button2; + private Button button3; + private Button button4; + private Button button5; + + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel(); + this.label2 = new System.Windows.Forms.Label(); + this.button11 = new System.Windows.Forms.Button(); + this.button12 = new System.Windows.Forms.Button(); + this.button13 = new System.Windows.Forms.Button(); + this.button14 = new System.Windows.Forms.Button(); + this.button15 = new System.Windows.Forms.Button(); + this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.label1 = new System.Windows.Forms.Label(); + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.button3 = new System.Windows.Forms.Button(); + this.button4 = new System.Windows.Forms.Button(); + this.button5 = new System.Windows.Forms.Button(); + this.flowLayoutPanel3.SuspendLayout(); + this.flowLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // flowLayoutPanel3 + // + this.flowLayoutPanel3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.flowLayoutPanel3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.flowLayoutPanel3.Controls.Add(this.label2); + this.flowLayoutPanel3.Controls.Add(this.button11); + this.flowLayoutPanel3.Controls.Add(this.button12); + this.flowLayoutPanel3.Controls.Add(this.button13); + this.flowLayoutPanel3.Controls.Add(this.button14); + this.flowLayoutPanel3.Controls.Add(this.button15); + this.flowLayoutPanel3.Location = new System.Drawing.Point(12, 12); + this.flowLayoutPanel3.Name = "flowLayoutPanel3"; + this.flowLayoutPanel3.Size = new System.Drawing.Size(631, 100); + this.flowLayoutPanel3.TabIndex = 2; + // + // label2 + // + this.label2.Anchor = System.Windows.Forms.AnchorStyles.None; + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(3, 28); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(138, 14); + this.label2.TabIndex = 10; + this.label2.Text = "FlowDirection=LeftToRight"; + // + // button11 + // + this.button11.Anchor = System.Windows.Forms.AnchorStyles.Bottom; + this.button11.AutoSize = true; + this.button11.Location = new System.Drawing.Point(147, 44); + this.button11.Name = "button11"; + this.button11.Size = new System.Drawing.Size(86, 23); + this.button11.TabIndex = 5; + this.button11.Text = "Anchor=Bottom"; + // + // button12 + // + this.button12.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); + this.button12.AutoSize = true; + this.button12.Location = new System.Drawing.Point(239, 3); + this.button12.Name = "button12"; + this.button12.Size = new System.Drawing.Size(111, 64); + this.button12.TabIndex = 6; + this.button12.Text = "Anchor=Top, Bottom"; + // + // button13 + // + this.button13.Anchor = System.Windows.Forms.AnchorStyles.None; + this.button13.BackColor = System.Drawing.SystemColors.GradientActiveCaption; + this.button13.Location = new System.Drawing.Point(356, 3); + this.button13.Name = "button13"; + this.button13.Size = new System.Drawing.Size(75, 64); + this.button13.TabIndex = 7; + // + // button14 + // + this.button14.Dock = System.Windows.Forms.DockStyle.Bottom; + this.button14.Location = new System.Drawing.Point(437, 44); + this.button14.Name = "button14"; + this.button14.TabIndex = 8; + this.button14.Text = "Dock=Bottom"; + // + // button15 + // + this.button15.Dock = System.Windows.Forms.DockStyle.Fill; + this.button15.Location = new System.Drawing.Point(518, 3); + this.button15.Name = "button15"; + this.button15.Size = new System.Drawing.Size(75, 64); + this.button15.TabIndex = 9; + this.button15.Text = "Dock=Fill"; + // + // flowLayoutPanel1 + // + this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.flowLayoutPanel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.flowLayoutPanel1.Controls.Add(this.label1); + this.flowLayoutPanel1.Controls.Add(this.button1); + this.flowLayoutPanel1.Controls.Add(this.button2); + this.flowLayoutPanel1.Controls.Add(this.button3); + this.flowLayoutPanel1.Controls.Add(this.button4); + this.flowLayoutPanel1.Controls.Add(this.button5); + this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; + this.flowLayoutPanel1.Location = new System.Drawing.Point(12, 118); + this.flowLayoutPanel1.Name = "flowLayoutPanel1"; + this.flowLayoutPanel1.Size = new System.Drawing.Size(200, 209); + this.flowLayoutPanel1.TabIndex = 3; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(3, 3); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(128, 14); + this.label1.TabIndex = 11; + this.label1.Text = "FlowDirection=TopDown"; + // + // button1 + // + this.button1.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.button1.Location = new System.Drawing.Point(74, 23); + this.button1.Name = "button1"; + this.button1.TabIndex = 5; + this.button1.Text = "Anchor=Right"; + // + // button2 + // + this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button2.Location = new System.Drawing.Point(3, 52); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(146, 23); + this.button2.TabIndex = 6; + this.button2.Text = "Anchor=Left, Right"; + // + // button3 + // + this.button3.BackColor = System.Drawing.SystemColors.GradientActiveCaption; + this.button3.Location = new System.Drawing.Point(3, 81); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(146, 23); + this.button3.TabIndex = 7; + // + // button4 + // + this.button4.Dock = System.Windows.Forms.DockStyle.Right; + this.button4.Location = new System.Drawing.Point(74, 110); + this.button4.Name = "button4"; + this.button4.TabIndex = 8; + this.button4.Text = "Dock=Right"; + // + // button5 + // + this.button5.Dock = System.Windows.Forms.DockStyle.Fill; + this.button5.Location = new System.Drawing.Point(3, 139); + this.button5.Name = "button5"; + this.button5.Size = new System.Drawing.Size(146, 23); + this.button5.TabIndex = 9; + this.button5.Text = "Dock=Fill"; + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(658, 341); + this.Controls.Add(this.flowLayoutPanel1); + this.Controls.Add(this.flowLayoutPanel3); + this.Name = "Form1"; + this.Text = "Form1"; + this.flowLayoutPanel3.ResumeLayout(false); + this.flowLayoutPanel3.PerformLayout(); + this.flowLayoutPanel1.ResumeLayout(false); + this.flowLayoutPanel1.PerformLayout(); + this.ResumeLayout(false); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel/CS/form1.cs new file mode 100644 index 0000000000..6b0baa3623 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel/CS/form1.cs @@ -0,0 +1,202 @@ +// + +// +using System; +using System.Windows.Forms; +// + +public class Form1 : System.Windows.Forms.Form +{ + // + private void wrapContentsCheckBox_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.FlowLayoutPanel1.WrapContents = + this.wrapContentsCheckBox.Checked; + } + // + + // + private void flowTopDownBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown; + } + + private void flowBottomUpBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.FlowLayoutPanel1.FlowDirection = FlowDirection.BottomUp; + } + + private void flowLeftToRight_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.FlowLayoutPanel1.FlowDirection = FlowDirection.LeftToRight; + } + + private void flowRightToLeftBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.FlowLayoutPanel1.FlowDirection = FlowDirection.RightToLeft; + } + // + +#region " Windows Form Designer generated code " + + public Form1() : base() + { + + //This call is required by the Windows Form Designer. + InitializeComponent(); + + //Add any initialization after the InitializeComponent() call + } + + //Form overrides dispose to clean up the component list. + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + private System.Windows.Forms.FlowLayoutPanel FlowLayoutPanel1; + private System.Windows.Forms.CheckBox wrapContentsCheckBox; + private System.Windows.Forms.RadioButton flowTopDownBtn; + private System.Windows.Forms.RadioButton flowBottomUpBtn; + private System.Windows.Forms.RadioButton flowLeftToRight; + private System.Windows.Forms.RadioButton flowRightToLeftBtn; + private System.Windows.Forms.Button Button1; + private System.Windows.Forms.Button Button2; + private System.Windows.Forms.Button Button3; + private System.Windows.Forms.Button Button4; + + //Required by the Windows Form Designer + private System.ComponentModel.IContainer components; + + //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. + [System.Diagnostics.DebuggerNonUserCode] + private void InitializeComponent() + { + this.FlowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.Button1 = new System.Windows.Forms.Button(); + this.Button2 = new System.Windows.Forms.Button(); + this.Button3 = new System.Windows.Forms.Button(); + this.Button4 = new System.Windows.Forms.Button(); + this.wrapContentsCheckBox = new System.Windows.Forms.CheckBox(); + this.flowTopDownBtn = new System.Windows.Forms.RadioButton(); + this.flowBottomUpBtn = new System.Windows.Forms.RadioButton(); + this.flowLeftToRight = new System.Windows.Forms.RadioButton(); + this.flowRightToLeftBtn = new System.Windows.Forms.RadioButton(); + this.FlowLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); +// +// FlowLayoutPanel1 +// + this.FlowLayoutPanel1.Controls.Add(this.Button1); + this.FlowLayoutPanel1.Controls.Add(this.Button2); + this.FlowLayoutPanel1.Controls.Add(this.Button3); + this.FlowLayoutPanel1.Controls.Add(this.Button4); + this.FlowLayoutPanel1.Location = new System.Drawing.Point(47, 55); + this.FlowLayoutPanel1.Name = "FlowLayoutPanel1"; + this.FlowLayoutPanel1.TabIndex = 0; +// +// Button1 +// + this.Button1.Location = new System.Drawing.Point(3, 3); + this.Button1.Name = "Button1"; + this.Button1.TabIndex = 0; + this.Button1.Text = "Button1"; +// +// Button2 +// + this.Button2.Location = new System.Drawing.Point(84, 3); + this.Button2.Name = "Button2"; + this.Button2.TabIndex = 1; + this.Button2.Text = "Button2"; +// +// Button3 +// + this.Button3.Location = new System.Drawing.Point(3, 32); + this.Button3.Name = "Button3"; + this.Button3.TabIndex = 2; + this.Button3.Text = "Button3"; +// +// Button4 +// + this.Button4.Location = new System.Drawing.Point(84, 32); + this.Button4.Name = "Button4"; + this.Button4.TabIndex = 3; + this.Button4.Text = "Button4"; +// +// wrapContentsCheckBox +// + this.wrapContentsCheckBox.Location = new System.Drawing.Point(46, 162); + this.wrapContentsCheckBox.Name = "wrapContentsCheckBox"; + this.wrapContentsCheckBox.TabIndex = 1; + this.wrapContentsCheckBox.Text = "Wrap Contents"; + this.wrapContentsCheckBox.CheckedChanged += new System.EventHandler(this.wrapContentsCheckBox_CheckedChanged); +// +// flowTopDownBtn +// + this.flowTopDownBtn.Location = new System.Drawing.Point(45, 193); + this.flowTopDownBtn.Name = "flowTopDownBtn"; + this.flowTopDownBtn.TabIndex = 2; + this.flowTopDownBtn.Text = "Flow TopDown"; + this.flowTopDownBtn.CheckedChanged += new System.EventHandler(this.flowTopDownBtn_CheckedChanged); +// +// flowBottomUpBtn +// + this.flowBottomUpBtn.Location = new System.Drawing.Point(44, 224); + this.flowBottomUpBtn.Name = "flowBottomUpBtn"; + this.flowBottomUpBtn.TabIndex = 3; + this.flowBottomUpBtn.Text = "Flow BottomUp"; + this.flowBottomUpBtn.CheckedChanged += new System.EventHandler(this.flowBottomUpBtn_CheckedChanged); +// +// flowLeftToRight +// + this.flowLeftToRight.Location = new System.Drawing.Point(156, 193); + this.flowLeftToRight.Name = "flowLeftToRight"; + this.flowLeftToRight.TabIndex = 4; + this.flowLeftToRight.Text = "Flow LeftToRight"; + this.flowLeftToRight.CheckedChanged += new System.EventHandler(this.flowLeftToRight_CheckedChanged); +// +// flowRightToLeftBtn +// + this.flowRightToLeftBtn.Location = new System.Drawing.Point(155, 224); + this.flowRightToLeftBtn.Name = "flowRightToLeftBtn"; + this.flowRightToLeftBtn.TabIndex = 5; + this.flowRightToLeftBtn.Text = "Flow RightToLeft"; + this.flowRightToLeftBtn.CheckedChanged += new System.EventHandler(this.flowRightToLeftBtn_CheckedChanged); +// +// Form1 +// + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.flowRightToLeftBtn); + this.Controls.Add(this.flowLeftToRight); + this.Controls.Add(this.flowBottomUpBtn); + this.Controls.Add(this.flowTopDownBtn); + this.Controls.Add(this.wrapContentsCheckBox); + this.Controls.Add(this.FlowLayoutPanel1); + this.Name = "Form1"; + this.Text = "Form1"; + this.FlowLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + } + +#endregion +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs new file mode 100644 index 0000000000..c182e0b201 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/CS/Form1.cs @@ -0,0 +1,39 @@ +// +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace FormWithButton +{ + public class Form1 : Form + { + // + public Button button1; + public Form1() + { + button1 = new Button(); + button1.Size = new Size(40, 40); + button1.Location = new Point(30, 30); + button1.Text = "Click me"; + this.Controls.Add(button1); + // + button1.Click += new EventHandler(button1_Click); + // + } + // + // + private void button1_Click(object sender, EventArgs e) + { + MessageBox.Show("Hello World"); + } + // + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/CS/Form1.cs new file mode 100644 index 0000000000..f65a74d8a6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/CS/Form1.cs @@ -0,0 +1,114 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace GenerateMemberExample +{ + public class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // + // The Modifiers property for button1 is "private". + private Button button1; + + // The Modifiers property for button2 is "protected". + protected Button button2; + + // button3 is not a member, because + // its GenerateMember property is false. + // + + /// + /// 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 + + // + private void InitializeComponent() + { + // button3 is declared in a local scope, because + // its GenerateMember property is false. + System.Windows.Forms.Button button3; + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + button3 = new System.Windows.Forms.Button(); + // + + 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"; + // + // button2 + // + this.button2.Location = new System.Drawing.Point(12, 41); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(75, 23); + this.button2.TabIndex = 1; + this.button2.Text = "button2"; + // + // button3 + // + button3.Location = new System.Drawing.Point(12, 70); + button3.Name = "button3"; + button3.Size = new System.Drawing.Size(75, 23); + button3.TabIndex = 2; + button3.Text = "button3"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(104, 109); + this.Controls.Add(button3); + this.Controls.Add(this.button2); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + + #endregion + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/AssemblyInfo.cs new file mode 100644 index 0000000000..7bec48f82d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/AssemblyInfo.cs @@ -0,0 +1,29 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("HtmlElementProjectCSharp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("MS")] +[assembly: AssemblyProduct("HtmlElementProjectCSharp")] +[assembly: AssemblyCopyright("Copyright @ MS 2004")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +/// Setting ComVisible to false makes the types in this assembly not visible +/// to COM componenets. If you need to access a type in this assembly from +/// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Form1.resx new file mode 100644 index 0000000000..25c2f26478 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Form1.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Resources.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Resources.cs new file mode 100644 index 0000000000..942068bd92 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Resources.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.40930.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace HtmlElementProjectCSharp.Configuration +{ + using System; + using System.IO; + using System.Resources; + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the Strongly Typed Resource Builder + // class via a tool like ResGen or Visual Studio.NET. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + class Resources + { + + private static System.Resources.ResourceManager _resMgr; + + private static System.Globalization.CultureInfo _resCulture; + + /*FamANDAssem*/ + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public static System.Resources.ResourceManager ResourceManager + { + get + { + if ((_resMgr == null)) + { + System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly); + _resMgr = temp; + } + return _resMgr; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] + public static System.Globalization.CultureInfo Culture + { + get + { + return _resCulture; + } + set + { + _resCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Resources.resx new file mode 100644 index 0000000000..3e18af958a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Settings.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Settings.cs new file mode 100644 index 0000000000..7a0b57b892 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Configuration/Settings.cs @@ -0,0 +1,42 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.40930.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace HtmlElementProjectCSharp.Configuration +{ + public partial class Settings : System.Configuration.ApplicationSettingsBase + { + private static Settings m_Value; + + private static object m_SyncObject = new object(); + + public static Settings Value + { + get + { + if ((Settings.m_Value == null)) + { + System.Threading.Monitor.Enter(Settings.m_SyncObject); + if ((Settings.m_Value == null)) + { + try + { + Settings.m_Value = new Settings(); + } + finally + { + System.Threading.Monitor.Exit(Settings.m_SyncObject); + } + } + } + return Settings.m_Value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.Designer.cs new file mode 100644 index 0000000000..a24c0898ca --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.Designer.cs @@ -0,0 +1,237 @@ +namespace HtmlElementProjectCSharp +{ + 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.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.PrintDOMButton = new System.Windows.Forms.Button(); + this.enableElementMoveButton = new System.Windows.Forms.Button(); + this.enableEditingButton = new System.Windows.Forms.Button(); + this.createLinkFromSelectionButton = new System.Windows.Forms.Button(); + this.CreateHtmlMenuButton = new System.Windows.Forms.Button(); + this.GetOffsetsButton = new System.Windows.Forms.Button(); + this.AddUrlToTooltipButton = new System.Windows.Forms.Button(); + this.AddDivMessageButton = new System.Windows.Forms.Button(); + this.submitFormButtom = new System.Windows.Forms.Button(); + this.button1 = new System.Windows.Forms.Button(); + this.AttachEventHandlerButton = new System.Windows.Forms.Button(); + this.webBrowser1 = new System.Windows.Forms.WebBrowser(); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.browserStatus = new System.Windows.Forms.ToolStripStatusLabel(); + this.button2 = new System.Windows.Forms.Button(); + this.flowLayoutPanel1.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // flowLayoutPanel1 + // + this.flowLayoutPanel1.Controls.Add(this.PrintDOMButton); + this.flowLayoutPanel1.Controls.Add(this.enableElementMoveButton); + this.flowLayoutPanel1.Controls.Add(this.enableEditingButton); + this.flowLayoutPanel1.Controls.Add(this.createLinkFromSelectionButton); + this.flowLayoutPanel1.Controls.Add(this.CreateHtmlMenuButton); + this.flowLayoutPanel1.Controls.Add(this.GetOffsetsButton); + this.flowLayoutPanel1.Controls.Add(this.AddUrlToTooltipButton); + this.flowLayoutPanel1.Controls.Add(this.AddDivMessageButton); + this.flowLayoutPanel1.Controls.Add(this.submitFormButtom); + this.flowLayoutPanel1.Controls.Add(this.button1); + this.flowLayoutPanel1.Controls.Add(this.AttachEventHandlerButton); + this.flowLayoutPanel1.Controls.Add(this.button2); + this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; + this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); + this.flowLayoutPanel1.Name = "flowLayoutPanel1"; + this.flowLayoutPanel1.Size = new System.Drawing.Size(754, 184); + this.flowLayoutPanel1.TabIndex = 0; + // + // PrintDOMButton + // + this.PrintDOMButton.Location = new System.Drawing.Point(3, 3); + this.PrintDOMButton.Name = "PrintDOMButton"; + this.PrintDOMButton.Size = new System.Drawing.Size(116, 23); + this.PrintDOMButton.TabIndex = 0; + this.PrintDOMButton.Text = "Print DOM"; + this.PrintDOMButton.Click += new System.EventHandler(this.PrintDOMButton_Click); + // + // enableElementMoveButton + // + this.enableElementMoveButton.Location = new System.Drawing.Point(125, 3); + this.enableElementMoveButton.Name = "enableElementMoveButton"; + this.enableElementMoveButton.Size = new System.Drawing.Size(159, 23); + this.enableElementMoveButton.TabIndex = 1; + this.enableElementMoveButton.Text = "EnableElementMove"; + this.enableElementMoveButton.Click += new System.EventHandler(this.enableElementMoveButton_Click); + // + // enableEditingButton + // + this.enableEditingButton.Location = new System.Drawing.Point(290, 3); + this.enableEditingButton.Name = "enableEditingButton"; + this.enableEditingButton.Size = new System.Drawing.Size(143, 23); + this.enableEditingButton.TabIndex = 2; + this.enableEditingButton.Text = "Enable Editing"; + this.enableEditingButton.Click += new System.EventHandler(this.enableEditingButton_Click); + // + // createLinkFromSelectionButton + // + this.createLinkFromSelectionButton.Location = new System.Drawing.Point(439, 3); + this.createLinkFromSelectionButton.Name = "createLinkFromSelectionButton"; + this.createLinkFromSelectionButton.Size = new System.Drawing.Size(183, 23); + this.createLinkFromSelectionButton.TabIndex = 3; + this.createLinkFromSelectionButton.Text = "Create Link from Selection"; + this.createLinkFromSelectionButton.Click += new System.EventHandler(this.createLinkFromSelectionButton_Click); + // + // CreateHtmlMenuButton + // + this.CreateHtmlMenuButton.Location = new System.Drawing.Point(3, 32); + this.CreateHtmlMenuButton.Name = "CreateHtmlMenuButton"; + this.CreateHtmlMenuButton.Size = new System.Drawing.Size(159, 23); + this.CreateHtmlMenuButton.TabIndex = 4; + this.CreateHtmlMenuButton.Text = "Create HTML Menu"; + this.CreateHtmlMenuButton.Click += new System.EventHandler(this.CreateHtmlMenuButton_Click); + // + // GetOffsetsButton + // + this.GetOffsetsButton.Location = new System.Drawing.Point(168, 32); + this.GetOffsetsButton.Name = "GetOffsetsButton"; + this.GetOffsetsButton.Size = new System.Drawing.Size(166, 23); + this.GetOffsetsButton.TabIndex = 5; + this.GetOffsetsButton.Text = "Get Offsets"; + this.GetOffsetsButton.Click += new System.EventHandler(this.GetOffsetsButton_Click); + // + // AddUrlToTooltipButton + // + this.AddUrlToTooltipButton.Location = new System.Drawing.Point(340, 32); + this.AddUrlToTooltipButton.Name = "AddUrlToTooltipButton"; + this.AddUrlToTooltipButton.Size = new System.Drawing.Size(215, 23); + this.AddUrlToTooltipButton.TabIndex = 6; + this.AddUrlToTooltipButton.Text = "Add Url to Tooltip"; + this.AddUrlToTooltipButton.Click += new System.EventHandler(this.AddUrlToTooltipButton_Click); + // + // AddDivMessageButton + // + this.AddDivMessageButton.Location = new System.Drawing.Point(561, 32); + this.AddDivMessageButton.Name = "AddDivMessageButton"; + this.AddDivMessageButton.Size = new System.Drawing.Size(160, 23); + this.AddDivMessageButton.TabIndex = 7; + this.AddDivMessageButton.Text = "Add DIV Message"; + this.AddDivMessageButton.Click += new System.EventHandler(this.AddDivMessageButton_Click); + // + // submitFormButtom + // + this.submitFormButtom.Location = new System.Drawing.Point(3, 61); + this.submitFormButtom.Name = "submitFormButtom"; + this.submitFormButtom.Size = new System.Drawing.Size(177, 23); + this.submitFormButtom.TabIndex = 8; + this.submitFormButtom.Text = "Submit Form"; + this.submitFormButtom.Click += new System.EventHandler(this.submitFormButtom_Click); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(186, 61); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(157, 23); + this.button1.TabIndex = 9; + this.button1.Text = "button1"; + // + // AttachEventHandlerButton + // + this.AttachEventHandlerButton.Location = new System.Drawing.Point(349, 61); + this.AttachEventHandlerButton.Name = "AttachEventHandlerButton"; + this.AttachEventHandlerButton.Size = new System.Drawing.Size(158, 23); + this.AttachEventHandlerButton.TabIndex = 10; + this.AttachEventHandlerButton.Text = "Attach Event Handler"; + this.AttachEventHandlerButton.Click += new System.EventHandler(this.AttachEventHandlerButton_Click); + // + // webBrowser1 + // + this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; + this.webBrowser1.Location = new System.Drawing.Point(0, 184); + this.webBrowser1.Name = "webBrowser1"; + this.webBrowser1.Size = new System.Drawing.Size(754, 344); + this.webBrowser1.Url = new System.Uri("c:\\userfiles\\jayallen\\HtmlElementProject\\TestCE.htm", System.UriKind.Absolute); + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.browserStatus}); + this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Table; + this.statusStrip1.Location = new System.Drawing.Point(0, 528); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Size = new System.Drawing.Size(754, 23); + this.statusStrip1.TabIndex = 1; + this.statusStrip1.Text = "statusStrip1"; + // + // browserStatus + // + this.browserStatus.Name = "browserStatus"; + this.browserStatus.Text = "toolStripStatusLabel1"; + // + // button2 + // + this.button2.Location = new System.Drawing.Point(513, 61); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(187, 23); + this.button2.TabIndex = 11; + this.button2.Text = "Key Down"; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(754, 551); + this.Controls.Add(this.webBrowser1); + this.Controls.Add(this.flowLayoutPanel1); + this.Controls.Add(this.statusStrip1); + this.Name = "Form1"; + this.Text = "Form1"; + this.flowLayoutPanel1.ResumeLayout(false); + this.statusStrip1.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; + private System.Windows.Forms.WebBrowser webBrowser1; + private System.Windows.Forms.Button PrintDOMButton; + private System.Windows.Forms.Button enableElementMoveButton; + private System.Windows.Forms.Button enableEditingButton; + private System.Windows.Forms.Button createLinkFromSelectionButton; + private System.Windows.Forms.Button CreateHtmlMenuButton; + private System.Windows.Forms.Button GetOffsetsButton; + private System.Windows.Forms.Button AddUrlToTooltipButton; + private System.Windows.Forms.Button AddDivMessageButton; + private System.Windows.Forms.Button submitFormButtom; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button AttachEventHandlerButton; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel browserStatus; + private System.Windows.Forms.Button button2; + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.cs new file mode 100644 index 0000000000..9c5cba2697 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.cs @@ -0,0 +1,517 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; +using System.Net; +using System.Text; + +namespace HtmlElementProjectCSharp +{ + partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + private void PrintDOMButton_Click(object sender, EventArgs e) + { + } + + // + private void PrintDomBegin() + { + if (webBrowser1.Document != null) + { + HtmlElementCollection elemColl = null; + HtmlDocument doc = webBrowser1.Document; + if (doc != null) + { + elemColl = doc.GetElementsByTagName("HTML"); + String str = PrintDom(elemColl, new System.Text.StringBuilder(), 0); + webBrowser1.DocumentText = str; + } + } + } + + private string PrintDom(HtmlElementCollection elemColl, System.Text.StringBuilder returnStr, Int32 depth) + { + System.Text.StringBuilder str = new System.Text.StringBuilder(); + + foreach (HtmlElement elem in elemColl) + { + string elemName; + + elemName = elem.GetAttribute("ID"); + if (elemName == null || elemName.Length == 0) + { + elemName = elem.GetAttribute("name"); + if (elemName == null || elemName.Length == 0) + { + elemName = ""; + } + } + + str.Append(' ', depth * 4); + str.Append(elemName + ": " + elem.TagName + "(Level " + depth + ")"); + returnStr.AppendLine(str.ToString()); + + if (elem.CanHaveChildren) + { + PrintDom(elem.Children, returnStr, depth + 1); + } + + str.Remove(0, str.Length); + } + + return(returnStr.ToString()); + } + // + + private void enableElementMoveButton_Click(object sender, EventArgs e) + { + EnableElementMove(); + } + + // + HtmlDocument doc; + HtmlElement moveElement; + + private void EnableElementMove() + { + if (webBrowser1 != null) + { + doc = webBrowser1.Document; + doc.Click += new HtmlElementEventHandler(doc_Click); + } + } + + void doc_Click(object sender, HtmlElementEventArgs e) + { + if (moveElement == null) + { + moveElement = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition); + } + else + { + HtmlElement targetElement = webBrowser1.Document.GetElementFromPoint(e.ClientMousePosition); + if (targetElement.CanHaveChildren) + { + targetElement.AppendChild(moveElement); + moveElement = null; + } + } + } + // + + private void enableEditingButton_Click(object sender, EventArgs e) + { + } + + // + private void EnableEditing() + { + if (webBrowser1.Document != null) + { + HtmlElement elem = webBrowser1.Document.GetElementById("div1"); + if (elem != null) + { + if (elem.ClientRectangle.Width < 200) + { + elem.SetAttribute("width", "200px"); + } + + if (elem.ClientRectangle.Height < 50) + { + elem.SetAttribute("height", "50px"); + } + + elem.SetAttribute("contentEditable", "true"); + //elem.SetFocus(); + } + } + } + // + + // + private void CreateHyperlinkFromSelection() + { + if (webBrowser1.Document != null) + { + + mshtml.IHTMLDocument2 iDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument; + + if (iDoc != null) + { + mshtml.IHTMLSelectionObject iSelect = iDoc.selection; + if (iSelect == null) + { + MessageBox.Show("Please select some text before using this command."); + return; + } + + mshtml.IHTMLTxtRange txtRange = (mshtml.IHTMLTxtRange)iSelect.createRange(); + + // Create the link. + if (txtRange.queryCommandEnabled("CreateLink")) + { + Object o = null; + txtRange.execCommand("CreateLink", true, o); + } + } + } + } + // + + private void createLinkFromSelectionButton_Click(object sender, EventArgs e) + { + CreateHyperlinkFromSelection(); + } + + // + private void CreateHtmlMenu() + { + HtmlElement elem = webBrowser1.Document.GetElementById("div1"); + + String htmlMenu = "
"; + htmlMenu += "
"; + htmlMenu += "+First Level
"; + htmlMenu += "
"; + + htmlMenu += "
"; + + elem.InnerHtml = htmlMenu; + + // Retrieve the menu cues and hook up an event handler for expanding and collapsing display of the + // child elements. + foreach (HtmlElement menuCueElem in elem.GetElementsByTagName("SPAN")) + { + if (menuCueElem.Id.EndsWith("cue")) + { + menuCueElem.Click += new HtmlElementEventHandler(Element_Click); + } + } + } + + private void Element_Click(Object sender, HtmlElementEventArgs e) + { + // !TODO: Need SetStyle() implemented per DCR. + } + //
+ + private void CreateHtmlMenuButton_Click(object sender, EventArgs e) + { + CreateHtmlMenu(); + } + + // + private void GetOffsets() + { + String str = ""; + HtmlDocument doc = webBrowser1.Document; + + foreach (HtmlElement elem in doc.GetElementsByTagName("SPAN")) + { + str += "OffsetParent for " + elem.Id + " is " + elem.OffsetParent.Id; + str += "; OffsetRectangle is " + elem.OffsetRectangle.ToString() + "\n"; + } + + MessageBox.Show(str); + } + // + + private void GetOffsetsButton_Click(object sender, EventArgs e) + { + GetOffsets(); + } + + // + private void AddUrlToTooltip() + { + if (webBrowser1.Document != null) + { + foreach (HtmlElement elem in webBrowser1.Document.GetElementsByTagName("IMG")) + { + if (elem.Parent.TagName.Equals("A")) + { + String altStr = elem.GetAttribute("ALT"); + if (!(altStr == null) && (altStr.Length != 0)) + { + elem.SetAttribute("ALT", altStr + " - points to " + elem.Parent.GetAttribute("HREF")); + } + else + { + elem.SetAttribute("ALT", "Points to " + elem.Parent.GetAttribute("HREF")); + } + } + } + } + } + // + + private void AddUrlToTooltipButton_Click(object sender, EventArgs e) + { + AddUrlToTooltip("http://www.adatum.com/"); + } + + // + private void AddUrlToTooltip(string url) + { + if (webBrowser1.Document != null) + { + HtmlElement elem = webBrowser1.Document.CreateElement("A"); + elem.SetAttribute("HREF", url); + elem.InnerText = "Visit our Web site for more details."; + + webBrowser1.Document.Body.AppendChild(elem); + } + } + // + + // + public void AddDivMessage() + { + Uri currentUri = new Uri(webBrowser1.Url.ToString()); + String hostName = null; + + // Ensure we have a host name, and not just an IP, against which to test. + if (!(currentUri.HostNameType == UriHostNameType.Dns)) + { + DnsPermission permit = new DnsPermission(System.Security.Permissions.PermissionState.Unrestricted); + permit.Assert(); + + IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(currentUri.Host); + hostName = hostEntry.HostName; + } else { + hostName = currentUri.Host; + } + + if (!hostName.Contains("adatum.com")) + { + AddTopPageMessage("You are viewing a web site other than ADatum.com. " + + "Please exercise caution, and ensure your Web surfing complies with all " + + "corporate regulations as laid out in the company handbook."); + } + } + + private void AddTopPageMessage(String message) + { + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + + // Do not insert the warning again if it already exists. + HtmlElementCollection returnedElems = doc.All.GetElementsByName("ADatumWarningDiv"); + if ((returnedElems != null) && (returnedElems.Count > 0)) + { + return; + } + + HtmlElement divElem = doc.CreateElement("DIV"); + divElem.Name = "ADatumWarningDiv"; + divElem.Style = "background-color:black;color:white;font-weight:bold;width:100%;"; + divElem.InnerText = message; + + divElem = doc.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, divElem); + } + } + // + + private void AddDivMessageButton_Click(object sender, EventArgs e) + { + AddDivMessage(); + } + + // + private void SubmitForm(String formName) + { + HtmlElementCollection elems = null; + HtmlElement elem = null; + + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + elems = doc.All.GetElementsByName(formName); + if (elems != null && elems.Count > 0) + { + elem = elems[0]; + if (elem.TagName.Equals("FORM")) + { + elem.InvokeMember("Submit"); + } + } + } + } + // + + private void submitFormButtom_Click(object sender, EventArgs e) + { + SubmitForm("form1"); + } + + // + private void ShiftRows(String tableName) + { + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + HtmlElementCollection elems = doc.All.GetElementsByName(tableName); + if (elems != null && elems.Count > 0) + { + HtmlElement elem = elems[0]; + + // Prepare the arguments. + Object[] args = new Object[2]; + args[0] = (Object)"-1"; + args[1] = (Object)"0"; + + elem.InvokeMember("moveRow", args); + } + } + } + // + + // + private void ScrollToElement(String elemName) + { + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + HtmlElementCollection elems = doc.All.GetElementsByName(elemName); + if (elems != null && elems.Count > 0) + { + HtmlElement elem = elems[0]; + + elem.ScrollIntoView(true); + } + } + } + // + + // + private void InsertImageFooter() + { + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + HtmlElement elem = doc.CreateElement("IMG"); + elem.SetAttribute("SRC", "http://www.adatum.com/images/footer-banner.jpg"); + + doc.Body.AppendChild(elem); + } + } + // + + // + HtmlElement bodyElement = null; + + private void SetBody() + { + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + bodyElement = doc.Body; + //bodyElement.Error += new HtmlElementEventHandler(HandleError); + } + } + + private void HandleError(Object sender, HtmlElementEventArgs e) + { + //System.Diagnostics.EventLog.WriteEntry("Custom Application", "Scripting error occurred: " & _ + //e. + } + // + + // + HtmlElement targetFormElement; + + private void HandleFormFocus() + { + if (webBrowser1.Document != null) + { + HtmlDocument doc = webBrowser1.Document; + if (doc.Forms.Count > 0) + { + HtmlElement targetForm = doc.Forms[0]; + HtmlElementCollection searchCollection = targetForm.All.GetElementsByName("text1"); + if (searchCollection.Count == 1) + { + targetFormElement = searchCollection[0]; + } + } + } + } + + private void TargetFormElement_Focus(Object sender, HtmlElementEventArgs e) + { + HtmlElement textElement = e.FromElement; + String elementText = textElement.GetAttribute("value"); + + // Check that this value is at least five characters long. + if (elementText.Length < 5) + { + e.ReturnValue = true; + MessageBox.Show("The entry in the current field must be at least five characters long."); + } + } + // + + private void AttachEventHandlerButton_Click(object sender, EventArgs e) + { + AttachCopyHandler(); + } + + // + private void AttachCopyHandler() + { + if (webBrowser1.Document != null) { + HtmlElement div = webBrowser1.Document.GetElementById("Div1"); + div.AttachEventHandler("oncopy", new EventHandler(HtmlElement_OnCopy)); + } + } + + private void HtmlElement_OnCopy(Object sender, EventArgs e) + { + browserStatus.Text = "Selection copied. Selection is: " + Clipboard.GetText(); + } + // + + private void button2_Click(object sender, EventArgs e) + { + ScrollList(); + } + + // + HtmlElement elem = null; + int lastKeystrokeOn = 0; + StringBuilder keystrokes; + + private void ScrollList() + { + + if (webBrowser1.Document != null) + { + keystrokes = new StringBuilder(); + + elem = webBrowser1.Document.GetElementById("text1"); + elem.KeyDown += new HtmlElementEventHandler(elem_KeyDown); + } + } + + void elem_KeyDown(object sender, HtmlElementEventArgs e) + { + Char c = (char)e.KeyPressedCode; + + if (Char.IsLetterOrDigit(c)) + { + lastKeystrokeOn++; + } + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.resx new file mode 100644 index 0000000000..ab569afbfa --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/HtmlElementProjectCSharp.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/HtmlElementProjectCSharp.csproj new file mode 100644 index 0000000000..9a54fecb51 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/HtmlElementProjectCSharp.csproj @@ -0,0 +1,68 @@ + + + Debug + AnyCPU + 8.0.41123 + 2.0 + {E1E9986E-85CE-45A4-8612-97A0F831688B} + WinExe + HtmlElementProjectCSharp + HtmlElementProjectCSharp + 4 + + + true + full + false + .\bin\Debug\ + DEBUG;TRACE + + + pdbonly + true + .\bin\Release\ + TRACE + + + + + + + + + + + + + Form + + + Form1.cs + + + + + ResXFileCodeGenerator + Resources.cs + Designer + + + Form1.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.cs + + + True + Settings.settings + True + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Program.cs new file mode 100644 index 0000000000..279df160c0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/CS/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace HtmlElementProjectCSharp +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs new file mode 100644 index 0000000000..ac647948e0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/CS/form1.cs @@ -0,0 +1,156 @@ +// This sample compiles a set of miscellaneous code snippets that demonstrate +// different levels of user input control. + +// +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace KeyboardInput +{ +[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] + class Form1 : Form + { + // The following Windows message value is defined in Winuser.h. + private int WM_KEYDOWN = 0x100; + CustomTextBox CustomTextBox1 = new CustomTextBox(); + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + this.AutoSize = true; + this.Controls.Add(CustomTextBox1); + CustomTextBox1.KeyPress += + new KeyPressEventHandler(CustomTextBox1_KeyPress); + } + + // + // Consume and modify several character keys. + void CustomTextBox1_KeyPress(object sender, KeyPressEventArgs e) + { + switch (e.KeyChar) + { + // + // Consume 'A' and 'a'. + case (char)65: + case (char)97: + MessageBox.Show("Control.KeyPress: '" + + e.KeyChar.ToString() + "' consumed."); + e.Handled = true; + break; + // + + // + // Detect 'B', modify it to 'A', and forward the key. + case (char)66: + MessageBox.Show("Control.KeyPress: '" + + e.KeyChar.ToString() + "' replaced by 'A'."); + e.KeyChar = (char)65; + e.Handled = false; + break; + + // Detect 'b', modify it to 'a', and forward the key. + case (char)98: + MessageBox.Show("Control.KeyPress: '" + + e.KeyChar.ToString() + "' replaced by 'a'."); + e.KeyChar = (char)97; + e.Handled = false; + break; + // + } + } + // + } +[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] + public class CustomTextBox : TextBox + { + // The following Windows message value is defined in Winuser.h. + private int WM_KEYDOWN = 0x100; + + public CustomTextBox() + { + this.Size = new Size(100, 100); + this.AutoSize = false; + } + + // + // + // Detect F1 through F9 during preprocessing and modify F3. + public override bool PreProcessMessage(ref Message m) + { + if (m.Msg == WM_KEYDOWN) + { + Keys keyCode = (Keys)m.WParam & Keys.KeyCode; + + // Detect F1 through F9. + switch (keyCode) + { + case Keys.F1: + case Keys.F2: + case Keys.F3: + case Keys.F4: + case Keys.F5: + case Keys.F6: + case Keys.F7: + case Keys.F8: + case Keys.F9: + + MessageBox.Show("Control.PreProcessMessage: '" + + keyCode.ToString() + "' pressed."); + + // Replace F3 with F1, so that ProcessKeyMessage will + // receive F1 instead of F3. + if (keyCode == Keys.F3) + { + m.WParam = (IntPtr)Keys.F1; + MessageBox.Show("Control.PreProcessMessage: '" + + keyCode.ToString() + "' replaced by F1."); + } + break; + } + } + + // Send all other messages to the base method. + return base.PreProcessMessage(ref m); + } + // + + // Detect F1 through F9 during processing. + protected override bool ProcessKeyMessage(ref Message m) + { + if (m.Msg == WM_KEYDOWN) + { + Keys keyCode = (Keys)m.WParam & Keys.KeyCode; + + // Detect F1 through F9. + switch (keyCode) + { + case Keys.F1: + case Keys.F2: + case Keys.F3: + case Keys.F4: + case Keys.F5: + case Keys.F6: + case Keys.F7: + case Keys.F8: + case Keys.F9: + + MessageBox.Show("Control.ProcessKeyMessage: '" + + keyCode.ToString() + "' pressed."); + break; + } + } + + // Send all messages to the base method. + return base.ProcessKeyMessage(ref m); + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/CS/form1.cs new file mode 100644 index 0000000000..b759064d0e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/CS/form1.cs @@ -0,0 +1,89 @@ +// This sample compiles a set of miscellaneous code snippets that demonstrate +// different levels of user input control. + +// +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace KeyboardInputForm +{ + class Form1 : Form + { + TextBox TextBox1 = new TextBox(); + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + this.AutoSize = true; + + FlowLayoutPanel panel = new FlowLayoutPanel(); + panel.AutoSize = true; + panel.FlowDirection = FlowDirection.TopDown; + panel.Controls.Add(TextBox1); + this.Controls.Add(panel); + + this.KeyPreview = true; + this.KeyPress += + new KeyPressEventHandler(Form1_KeyPress); + TextBox1.KeyPress += + new KeyPressEventHandler(TextBox1_KeyPress); + } + + // + // Detect all numeric characters at the form level and consume 1, + // 4, and 7. Note that 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.ToString() + "' pressed."); + + switch (e.KeyChar) + { + case (char)49: + case (char)52: + case (char)55: + MessageBox.Show("Form.KeyPress: '" + + e.KeyChar.ToString() + "' consumed."); + e.Handled = true; + break; + } + } + } + // + + // + // Detect all numeric characters at the TextBox level and consume + // 2, 5, and 8. + void TextBox1_KeyPress(object sender, KeyPressEventArgs e) + { + if (e.KeyChar >= 48 && e.KeyChar <= 57) + { + MessageBox.Show("Control.KeyPress: '" + + e.KeyChar.ToString() + "' pressed."); + + switch (e.KeyChar) + { + case (char)50: + case (char)53: + case (char)56: + MessageBox.Show("Control.KeyPress: '" + + e.KeyChar.ToString() + "' consumed."); + e.Handled = true; + break; + } + } + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/CS/Form1.cs new file mode 100644 index 0000000000..f384090a90 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/CS/Form1.cs @@ -0,0 +1,308 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using KeyedCollectionsEx; + +namespace KeyedCollectionsEx +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + ShowShippingOptions(); + + // + this.BackgroundImage = imageList1.Images["logo.gif"]; + // + } + + private void ShowShippingOptions() + { + // + tabControl1.SelectedTab = tabControl1.TabPages["shippingOptions"]; + // + } + + private void button1_Click(object sender, EventArgs e) + { + // + OrderForm OrderForm1 = new OrderForm(); + OrderForm1.Show(); + OrderForm1.Controls.Find("textBox1", true)[0].Focus(); + // + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.ImageList imageList1; + private System.Windows.Forms.TabControl tabControl1; + private System.Windows.Forms.TabPage products; + private System.Windows.Forms.TabPage shippingOptions; + private void InitializeComponent() + { + + this.button1 = new System.Windows.Forms.Button(); + imageList1 = new ImageList(); + this.tabControl1 = new System.Windows.Forms.TabControl(); + this.products = new System.Windows.Forms.TabPage(); + this.shippingOptions = new System.Windows.Forms.TabPage(); + this.tabControl1.SuspendLayout(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(66, 218); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "Show Order Form"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // imageList1 + // + this.imageList1.TransparentColor = System.Drawing.Color.Transparent; + this.imageList1.Images.SetKeyName(0, "Order.GIF"); + this.imageList1.Images.SetKeyName(1, "Logo.GIF"); + // + // tabControl1 + // + this.tabControl1.Controls.Add(this.products); + this.tabControl1.Controls.Add(this.shippingOptions); + this.tabControl1.Location = new System.Drawing.Point(12, 12); + this.tabControl1.Name = "tabControl1"; + this.tabControl1.SelectedIndex = 0; + this.tabControl1.Size = new System.Drawing.Size(264, 175); + this.tabControl1.TabIndex = 1; + // + // products + // + this.products.Location = new System.Drawing.Point(4, 22); + this.products.Name = "products"; + this.products.Padding = new System.Windows.Forms.Padding(3); + this.products.Size = new System.Drawing.Size(256, 149); + this.products.TabIndex = 0; + this.products.Text = "Products"; + this.products.UseVisualStyleBackColor = true; + // + // shippingOptions + // + this.shippingOptions.Location = new System.Drawing.Point(4, 22); + this.shippingOptions.Name = "shippingOptions"; + this.shippingOptions.Padding = new System.Windows.Forms.Padding(3); + this.shippingOptions.Size = new System.Drawing.Size(192, 74); + this.shippingOptions.TabIndex = 1; + this.shippingOptions.Text = "Shipping Options"; + this.shippingOptions.UseVisualStyleBackColor = true; + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.tabControl1); + this.Controls.Add(this.button1); + this.Name = "Form1"; + this.tabControl1.ResumeLayout(false); + this.ResumeLayout(false); + } + } + + public class OrderForm : Form + { + public OrderForm() + { + InitializeComponent(); + } + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.TextBox textBox4; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.TextBox textBox3; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox textBox2; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.CheckBox checkBox1; + private System.Windows.Forms.Panel panel2; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.ListView listView1; + private System.Windows.Forms.ImageList imageList1; + + private void InitializeComponent() + { + + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OrderForm)); + this.panel1 = new System.Windows.Forms.Panel(); + this.label5 = new System.Windows.Forms.Label(); + this.checkBox1 = new System.Windows.Forms.CheckBox(); + this.label4 = new System.Windows.Forms.Label(); + this.textBox4 = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.textBox3 = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.textBox1 = new System.Windows.Forms.TextBox(); + imageList1 = new ImageList(); + this.panel2 = new System.Windows.Forms.Panel(); + this.listView1 = new System.Windows.Forms.ListView(); + this.label6 = new System.Windows.Forms.Label(); + this.panel1.SuspendLayout(); + this.panel2.SuspendLayout(); + this.SuspendLayout(); + // + // panel1 + // + this.panel1.Controls.Add(this.label5); + this.panel1.Controls.Add(this.checkBox1); + this.panel1.Controls.Add(this.label4); + this.panel1.Controls.Add(this.textBox4); + this.panel1.Controls.Add(this.label3); + this.panel1.Controls.Add(this.textBox3); + this.panel1.Controls.Add(this.label2); + this.panel1.Controls.Add(this.label1); + this.panel1.Controls.Add(this.textBox2); + this.panel1.Controls.Add(this.textBox1); + this.panel1.Location = new System.Drawing.Point(3, 69); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(287, 198); + this.panel1.TabIndex = 1; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(6, 4); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(89, 13); + this.label5.TabIndex = 9; + this.label5.Text = "Billing Information"; + // + // checkBox1 + // + this.checkBox1.AutoSize = true; + this.checkBox1.Location = new System.Drawing.Point(150, 4); + this.checkBox1.Name = "checkBox1"; + this.checkBox1.Size = new System.Drawing.Size(127, 17); + this.checkBox1.TabIndex = 8; + this.checkBox1.Text = "Ship to same address"; + this.checkBox1.UseVisualStyleBackColor = true; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(6, 167); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(76, 13); + this.label4.TabIndex = 7; + this.label4.Text = "City, State, Zip"; + // + // textBox4 + // + this.textBox4.Location = new System.Drawing.Point(6, 105); + this.textBox4.Name = "textBox4"; + this.textBox4.Size = new System.Drawing.Size(187, 20); + this.textBox4.TabIndex = 6; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(3, 128); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(76, 13); + this.label3.TabIndex = 5; + this.label3.Text = "Address, line 2"; + // + // textBox3 + // + this.textBox3.Location = new System.Drawing.Point(6, 144); + this.textBox3.Name = "textBox3"; + this.textBox3.Size = new System.Drawing.Size(187, 20); + this.textBox3.TabIndex = 4; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(3, 89); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(76, 13); + this.label2.TabIndex = 3; + this.label2.Text = "Address, line 1"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(6, 50); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(35, 13); + this.label1.TabIndex = 2; + this.label1.Text = "Name"; + // + // textBox2 + // + this.textBox2.Location = new System.Drawing.Point(6, 66); + this.textBox2.Name = "textBox2"; + this.textBox2.Size = new System.Drawing.Size(187, 20); + this.textBox2.TabIndex = 1; + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(3, 27); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(190, 20); + this.textBox1.TabIndex = 0; + // + // panel2 + // + this.panel2.Controls.Add(this.label6); + this.panel2.Controls.Add(this.listView1); + this.panel2.Location = new System.Drawing.Point(3, 2); + this.panel2.Name = "panel2"; + this.panel2.Size = new System.Drawing.Size(287, 61); + this.panel2.TabIndex = 0; + // + // listView1 + // + this.listView1.Location = new System.Drawing.Point(3, 23); + this.listView1.Name = "listView1"; + this.listView1.Size = new System.Drawing.Size(274, 35); + this.listView1.TabIndex = 0; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(3, 7); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(46, 13); + this.label6.TabIndex = 1; + this.label6.Text = "Item List"; + + // + // OrderForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.panel2); + this.Controls.Add(this.panel1); + this.Name = "OrderForm"; + this.Text = "Order Form"; + this.panel1.ResumeLayout(false); + this.panel1.PerformLayout(); + this.panel2.ResumeLayout(false); + this.panel2.PerformLayout(); + this.ResumeLayout(false); + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/CS/DemoFlowLayout.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/CS/DemoFlowLayout.cs new file mode 100644 index 0000000000..246e9d2206 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/CS/DemoFlowLayout.cs @@ -0,0 +1,88 @@ +// +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +using System.Windows.Forms.Layout; + +// +// This class demonstrates a simple custom layout panel. +// It overrides the LayoutEngine property of the Panel +// control to provide a custom layout engine. +public class DemoFlowPanel : Panel +{ + private DemoFlowLayout layoutEngine; + + public DemoFlowPanel() + { + } + + public override LayoutEngine LayoutEngine + { + get + { + layoutEngine ??= new DemoFlowLayout(); + + return layoutEngine; + } + } +} +// + +// +// This class demonstrates a simple custom layout engine. +public class DemoFlowLayout : LayoutEngine +{ + // + public override bool Layout( + object container, + LayoutEventArgs layoutEventArgs) + { + Control parent = container as Control; + + // Use DisplayRectangle so that parent.Padding is honored. + Rectangle parentDisplayRectangle = parent.DisplayRectangle; + Point nextControlLocation = parentDisplayRectangle.Location; + + foreach (Control c in parent.Controls) + { + // Only apply layout to visible controls. + if (!c.Visible) + { + continue; + } + + // Respect the margin of the control: + // shift over the left and the top. + nextControlLocation.Offset(c.Margin.Left, c.Margin.Top); + + // Set the location of the control. + c.Location = nextControlLocation; + + // Set the autosized controls to their + // autosized heights. + if (c.AutoSize) + { + c.Size = c.GetPreferredSize(parentDisplayRectangle.Size); + } + + // Move X back to the display rectangle origin. + nextControlLocation.X = parentDisplayRectangle.X; + + // Increment Y by the height of the control + // and the bottom margin. + nextControlLocation.Y += c.Height + c.Margin.Bottom; + } + + // Optional: Return whether or not the container's + // parent should perform layout as a result of this + // layout. Some layout engines return the value of + // the container's AutoSize property. + + return false; + } + // +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs new file mode 100644 index 0000000000..a269e38ba2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/CS/Class1.cs @@ -0,0 +1,87 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; + +public class Form1 : Form +{ + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + // 4c2a90ee-bbbe-4ff6-9170-1b06c195c918 + // How to: Manually Manage Buffered Graphics + + public void Method11() + { + // + BufferedGraphicsContext myContext; + myContext = BufferedGraphicsManager.Current; + // + } + public void Method12() + { + // + BufferedGraphicsContext myContext; + myContext = new BufferedGraphicsContext(); + // Insert code to create graphics here. + // On a non-default BufferedGraphicsContext instance, you should always + // call Dispose when finished. + myContext.Dispose(); + // + } + // 5192295e-bd8e-45f7-8bd6-5c4f6bd21e61 + // How to: Manually Render Buffered Graphics + + public void Method21() + { + // + // This example assumes the existence of a form called Form1. + BufferedGraphicsContext currentContext; + BufferedGraphics myBuffer; + // Gets a reference to the current BufferedGraphicsContext + currentContext = BufferedGraphicsManager.Current; + // Creates a BufferedGraphics instance associated with Form1, and with + // dimensions the same size as the drawing surface of Form1. + myBuffer = currentContext.Allocate(this.CreateGraphics(), + this.DisplayRectangle); + // + + // + // Draws an ellipse to the graphics buffer. + myBuffer.Graphics.DrawEllipse(Pens.Blue, this.DisplayRectangle); + // + + // + // This example assumes the existence of a BufferedGraphics instance + // called myBuffer. + // Renders the contents of the buffer to the drawing surface associated + // with the buffer. + myBuffer.Render(); + // Renders the contents of the buffer to the specified drawing surface. + myBuffer.Render(this.CreateGraphics()); + // + + // + myBuffer.Dispose(); + // + } + // 91083d3a-653f-4f15-a467-0f37b2aa39d6 + // How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls + + public void Method31() + { + // + DoubleBuffered = true; + // + } + public void Method32() + { + // + SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CS/listviewinsertionmarkexample.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CS/listviewinsertionmarkexample.cs new file mode 100644 index 0000000000..abed927185 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CS/listviewinsertionmarkexample.cs @@ -0,0 +1,151 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +public class ListViewInsertionMarkExample : Form +{ + private ListView myListView; + + // + public ListViewInsertionMarkExample() + { + // Initialize myListView. + myListView = new ListView(); + myListView.Dock = DockStyle.Fill; + myListView.View = View.LargeIcon; + myListView.MultiSelect = false; + myListView.ListViewItemSorter = new ListViewIndexComparer(); + + // Initialize the insertion mark. + myListView.InsertionMark.Color = Color.Green; + + // Add items to myListView. + myListView.Items.Add("zero"); + myListView.Items.Add("one"); + myListView.Items.Add("two"); + myListView.Items.Add("three"); + myListView.Items.Add("four"); + myListView.Items.Add("five"); + + // Initialize the drag-and-drop operation when running + // under Windows XP or a later operating system. + if (OSFeature.Feature.IsPresent(OSFeature.Themes)) + { + myListView.AllowDrop = true; + myListView.ItemDrag += new ItemDragEventHandler(myListView_ItemDrag); + myListView.DragEnter += new DragEventHandler(myListView_DragEnter); + myListView.DragOver += new DragEventHandler(myListView_DragOver); + myListView.DragLeave += new EventHandler(myListView_DragLeave); + myListView.DragDrop += new DragEventHandler(myListView_DragDrop); + } + + // Initialize the form. + this.Text = "ListView Insertion Mark Example"; + this.Controls.Add(myListView); + } + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new ListViewInsertionMarkExample()); + } + + // Starts the drag-and-drop operation when an item is dragged. + private void myListView_ItemDrag(object sender, ItemDragEventArgs e) + { + myListView.DoDragDrop(e.Item, DragDropEffects.Move); + } + + // Sets the target drop effect. + private void myListView_DragEnter(object sender, DragEventArgs e) + { + e.Effect = e.AllowedEffect; + } + + // + // Moves the insertion mark as the item is dragged. + private void myListView_DragOver(object sender, DragEventArgs e) + { + // Retrieve the client coordinates of the mouse pointer. + Point targetPoint = + myListView.PointToClient(new Point(e.X, e.Y)); + + // Retrieve the index of the item closest to the mouse pointer. + int targetIndex = myListView.InsertionMark.NearestIndex(targetPoint); + + // Confirm that the mouse pointer is not over the dragged item. + if (targetIndex > -1) + { + // Determine whether the mouse pointer is to the left or + // the right of the midpoint of the closest item and set + // the InsertionMark.AppearsAfterItem property accordingly. + Rectangle itemBounds = myListView.GetItemRect(targetIndex); + if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) ) + { + myListView.InsertionMark.AppearsAfterItem = true; + } + else + { + myListView.InsertionMark.AppearsAfterItem = false; + } + } + + // Set the location of the insertion mark. If the mouse is + // over the dragged item, the targetIndex value is -1 and + // the insertion mark disappears. + myListView.InsertionMark.Index = targetIndex; + } + // + + // Removes the insertion mark when the mouse leaves the control. + private void myListView_DragLeave(object sender, EventArgs e) + { + myListView.InsertionMark.Index = -1; + } + + // Moves the item to the location of the insertion mark. + private void myListView_DragDrop(object sender, DragEventArgs e) + { + // Retrieve the index of the insertion mark; + int targetIndex = myListView.InsertionMark.Index; + + // If the insertion mark is not visible, exit the method. + if (targetIndex == -1) + { + return; + } + + // If the insertion mark is to the right of the item with + // the corresponding index, increment the target index. + if (myListView.InsertionMark.AppearsAfterItem) + { + targetIndex++; + } + + // Retrieve the dragged item. + ListViewItem draggedItem = + (ListViewItem)e.Data.GetData(typeof(ListViewItem)); + + // Insert a copy of the dragged item at the target index. + // A copy must be inserted before the original item is removed + // to preserve item index values. + myListView.Items.Insert( + targetIndex, (ListViewItem)draggedItem.Clone()); + + // Remove the original copy of the dragged item. + myListView.Items.Remove(draggedItem); + } + + // Sorts ListViewItem objects by index. + private class ListViewIndexComparer : System.Collections.IComparer + { + public int Compare(object x, object y) + { + return ((ListViewItem)x).Index - ((ListViewItem)y).Index; + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/CS/form1.cs new file mode 100644 index 0000000000..00c5504029 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/CS/form1.cs @@ -0,0 +1,117 @@ +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; +using System.Data; + +/// +/// Summary description for Form1. +/// +public class Form1 : System.Windows.Forms.Form +{ + private System.Windows.Forms.ListView listView1; + private System.Windows.Forms.Button button1; + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + public Form1() + { + // + // Required for Windows Form Designer support + // + InitializeComponent(); + + // + // TODO: Add any constructor code after InitializeComponent call + // + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose( bool disposing ) + { + if( disposing ) + { + if (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() + { + System.Windows.Forms.ListViewItem listViewItem11 = new System.Windows.Forms.ListViewItem("one"); + System.Windows.Forms.ListViewItem listViewItem12 = new System.Windows.Forms.ListViewItem("two"); + System.Windows.Forms.ListViewItem listViewItem13 = new System.Windows.Forms.ListViewItem("three"); + + this.listView1 = new System.Windows.Forms.ListView(); + this.button1 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + +// +// listView1 +// + this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] { + listViewItem11, listViewItem12, listViewItem13 + }); + this.listView1.Location = new System.Drawing.Point(5, 40); + this.listView1.Name = "listView1"; + this.listView1.Size = new System.Drawing.Size(278, 207); + this.listView1.TabIndex = 0; + +// +// button1 +// + this.button1.Location = new System.Drawing.Point(175, 10); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(100, 22); + this.button1.TabIndex = 1; + this.button1.Text = "button1"; + this.button1.Click += new System.EventHandler(this.button1_Click); + +// +// Form1 +// + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.button1); + this.Controls.Add(this.listView1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + } + #endregion + + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public void DemonstrateSelection() + { + // + this.listView1.Items[0].Focused = true; + this.listView1.Items[0].Selected = true; + // + } + + private void button1_Click(object sender, System.EventArgs e) + { + DemonstrateSelection(); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CS/listviewtilingexample.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CS/listviewtilingexample.cs new file mode 100644 index 0000000000..a8d99cdb66 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/CS/listviewtilingexample.cs @@ -0,0 +1,84 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +public class ListViewTilingExample : Form +{ + private ImageList myImageList; + + public ListViewTilingExample() + { + // Initialize myListView. + ListView myListView = new ListView(); + myListView.Dock = DockStyle.Fill; + myListView.View = View.Tile; + + // Initialize the tile size. + myListView.TileSize = new Size(400, 45); + + // Initialize the item icons. + myImageList = new ImageList(); + using (Icon myIcon = new Icon("book.ico")) + { + myImageList.Images.Add(myIcon); + } + myImageList.ImageSize = new Size(32, 32); + myListView.LargeImageList = myImageList; + + // Add column headers so the subitems will appear. + myListView.Columns.AddRange(new ColumnHeader[] + {new ColumnHeader(), new ColumnHeader(), new ColumnHeader()}); + + // Create items and add them to myListView. + ListViewItem item0 = new ListViewItem( new string[] + {"Programming Windows", + "Petzold, Charles", + "1998"}, 0 ); + ListViewItem item1 = new ListViewItem( new string[] + {"Code: The Hidden Language of Computer Hardware and Software", + "Petzold, Charles", + "2000"}, 0 ); + ListViewItem item2 = new ListViewItem( new string[] + {"Programming Windows with C#", + "Petzold, Charles", + "2001"}, 0 ); + ListViewItem item3 = new ListViewItem( new string[] + {"Coding Techniques for Microsoft Visual Basic .NET", + "Connell, John", + "2001"}, 0 ); + ListViewItem item4 = new ListViewItem( new string[] + {"C# for Java Developers", + "Jones, Allen & Freeman, Adam", + "2002"}, 0 ); + ListViewItem item5 = new ListViewItem( new string[] + {"Microsoft .NET XML Web Services Step by Step", + "Jones, Allen & Freeman, Adam", + "2002"}, 0 ); + myListView.Items.AddRange( + new ListViewItem[] {item0, item1, item2, item3, item4, item5}); + + // Initialize the form. + this.Controls.Add(myListView); + this.Size = new System.Drawing.Size(430, 330); + this.Text = "ListView Tiling Example"; + } + + // Clean up any resources being used. + protected override void Dispose(bool disposing) + { + if (disposing) + { + myImageList.Dispose(); + } + base.Dispose(disposing); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new ListViewTilingExample()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/CS/form1.cs new file mode 100644 index 0000000000..086e5fc92c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/CS/form1.cs @@ -0,0 +1,166 @@ +#region Using directives + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +#endregion + +namespace ListViewFindItemWithTextHowTo +{ + class Form1 : Form + { + public Form1() + { + InitializeComponent(); + + //InitializeTextSearchListView(); + InitializeLocationSearchListView(); + } + + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + 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() + { + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(292, 266); + this.Name = "Form1"; + this.Text = "Form1"; + } + + #endregion + + // + private ListView textListView = new ListView(); + private TextBox searchBox = new TextBox(); + private void InitializeTextSearchListView() + { + searchBox.Location = new Point(10, 60); + textListView.Scrollable = true; + textListView.Width = 80; + textListView.Height = 50; + + // Set the View to list to use the FindItemWithText method. + textListView.View = View.List; + + // Populate the ListViewWithItems + textListView.Items.AddRange(new ListViewItem[]{ + new ListViewItem("Amy Alberts"), + new ListViewItem("Amy Recker"), + new ListViewItem("Erin Hagens"), + new ListViewItem("Barry Johnson"), + new ListViewItem("Jay Hamlin"), + new ListViewItem("Brian Valentine"), + new ListViewItem("Brian Welker"), + new ListViewItem("Daniel Weisman") }); + + // Handle the TextChanged to get the text for our search. + searchBox.TextChanged += new EventHandler(searchBox_TextChanged); + + // Add the controls to the form. + this.Controls.Add(textListView); + this.Controls.Add(searchBox); + } + + // + private void searchBox_TextChanged(object sender, EventArgs e) + { + // Call FindItemWithText with the contents of the textbox. + ListViewItem foundItem = + textListView.FindItemWithText(searchBox.Text, false, 0, true); + if (foundItem != null) + { + textListView.TopItem = foundItem; + } + } + // + // + + // + ListView iconListView = new ListView(); + TextBox previousItemBox = new TextBox(); + + private void InitializeLocationSearchListView() + { + previousItemBox.Location = new Point(150, 20); + + // Create an image list for the icon ListView. + iconListView.LargeImageList = new ImageList(); + iconListView.Height = 400; + + // Add an image to the ListView large icon list. + iconListView.LargeImageList.Images.Add( + new Bitmap(typeof(Control), "Edit.bmp")); + + // Set the view to large icon and add some items with the image + // in the image list. + iconListView.View = View.LargeIcon; + iconListView.Items.AddRange(new ListViewItem[]{ + new ListViewItem("Amy Alberts", 0), + new ListViewItem("Amy Recker", 0), + new ListViewItem("Erin Hagens", 0), + new ListViewItem("Barry Johnson", 0), + new ListViewItem("Jay Hamlin", 0), + new ListViewItem("Brian Valentine", 0), + new ListViewItem("Brian Welker", 0), + new ListViewItem("Daniel Weisman", 0) }); + this.Controls.Add(iconListView); + this.Controls.Add(previousItemBox); + + // Handle the MouseDown event to capture user input. + iconListView.MouseDown += + new MouseEventHandler(iconListView_MouseDown); + //iconListView.MouseWheel += new MouseEventHandler(iconListView_MouseWheel); + } + + // + void iconListView_MouseDown(object sender, MouseEventArgs e) + { + + // Find the an item above where the user clicked. + ListViewItem foundItem = + iconListView.FindNearestItem(SearchDirectionHint.Up, e.X, e.Y); + + // Display the results in a textbox.. + if (foundItem != null) + previousItemBox.Text = foundItem.Text; + else + previousItemBox.Text = "No item found"; + } + // + // + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs new file mode 100644 index 0000000000..e54fc617a1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/CS/Class1.cs @@ -0,0 +1,118 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; +using System.Xml; + +public class Form1 : Form +{ + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + ListView listView1 = new ListView(); + ImageList imageList1 = new ImageList(); + // 1b35a80a-edd8-495f-a807-a28c4aae52c6 + // How to: Add and Remove Items with the Windows Forms ListView Control + + public void Method11() + { + // + // Adds a new item with ImageIndex 3 + listView1.Items.Add("List item text", 3); + + // + } + public void Method12() + { + // + // Removes the first item in the list. + listView1.Items.RemoveAt(0); + // Clears all the items. + listView1.Items.Clear(); + + // + } + // 610416a1-8da4-436c-af19-5f19e654769b + // How to: Group Items in a Windows Forms ListView Control + + public void Method21() + { + // + // Adds a new group that has a left-aligned header + listView1.Groups.Add(new ListViewGroup("List item text", + HorizontalAlignment.Left)); + // + } + public void Method22() + { + // + // Removes the first group in the collection. + listView1.Groups.RemoveAt(0); + // Clears all groups. + listView1.Groups.Clear(); + // + } + public void Method23() + { + // + // Adds the first item to the first group + listView1.Items[0].Group = listView1.Groups[0]; + // + } + // 79174274-12ee-4a5d-80db-6ec02976d010 + // How to: Add Columns to the Windows Forms ListView Control + + public void Method31() + { + // + // Set to details view. + listView1.View = View.Details; + // Add a column with width 20 and left alignment. + listView1.Columns.Add("File type", 20, HorizontalAlignment.Left); + + // + } + // 9d577542-8595-429b-99e5-078770ec9d35 + // How to: Display Icons for the Windows Forms ListView Control + + public void Method41() + { + // + listView1.SmallImageList = imageList1; + + // + } + public void Method42() + { + // + // Sets the first list item to display the 4th image. + listView1.Items[0].ImageIndex = 3; + + // + } + // c20e67a3-2d94-413d-9fcf-ecbd0fe251da + // How to: Enable Tile View in a Windows Forms ListView Control + + public void Method51() + { + // + listView1.View = View.Tile; + // + } + // e465f044-cde7-4fd9-a687-788a73a0f554 + // How to: Display Subitems in Columns with the Windows Forms ListView Control + + public void Method61() + { + // + // Adds two subitems to the first list item. + listView1.Items[0].SubItems.Add("John Smith"); + listView1.Items[0].SubItems.Add("Accounting"); + + // + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/CS/Form1.cs new file mode 100644 index 0000000000..c9afcd047c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/CS/Form1.cs @@ -0,0 +1,99 @@ +// + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.SqlClient; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace NavigatingData +{ + public partial class Form1 : Form + { + private Button nextButton; + private Button findButton; + private BindingSource customersBindingSource; + private DataGridView customersDataGridView; + + public Form1() + { + this.customersDataGridView = new DataGridView(); + this.nextButton = new Button(); + this.findButton = new Button(); + this.customersBindingSource = new BindingSource(); + + this.customersDataGridView.Location = new Point(23, 62); + this.customersDataGridView.Size = new Size(240, 150); + this.nextButton.Location = new Point(23, 22); + this.nextButton.Size = new Size(75, 23); + this.nextButton.Text = "Next"; + this.findButton.Location = new Point(122, 22); + this.findButton.Size = new Size(75, 23); + this.findButton.Text = "Find ANTON"; + this.ClientSize = new Size(292, 266); + this.Controls.Add(this.findButton); + this.Controls.Add(this.nextButton); + this.Controls.Add(this.customersDataGridView); + nextButton.Click += new EventHandler(nextButton_Click); + findButton.Click += new EventHandler(findButton_Click); + this.Load += new EventHandler(Form1_Load); + this.customersBindingSource.PositionChanged += new EventHandler(customersBindingSource_PositionChanged); + } + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + // + void findButton_Click(object sender, EventArgs e) + { + int foundIndex = customersBindingSource.Find("CustomerID", "ANTON"); + customersBindingSource.Position = foundIndex; + } + // + + // + void customersBindingSource_PositionChanged(object sender, EventArgs e) + { + if (customersBindingSource.Position == customersBindingSource.Count - 1) + nextButton.Enabled = false; + else + nextButton.Enabled = true; + } + // + + // + private void nextButton_Click(object sender, System.EventArgs e) + { + this.customersBindingSource.MoveNext(); + } + // + + // + private void Form1_Load(object sender, EventArgs e) + { + // Create the connection string, data adapter, data table and data view. + SqlConnection connectionString = + new SqlConnection("Initial Catalog=Northwind;" + + "Data Source=localhost;Integrated Security=SSPI;"); + SqlDataAdapter customersDataAdapter = + new SqlDataAdapter("Select * from Customers", connectionString); + + DataTable customerTable = new DataTable(); + + // Fill the table with the contents of the customer table. + customersDataAdapter.Fill(customerTable); + DataView customerView = new DataView(customerTable); + + // Set data source for customersBindingSource. + customersBindingSource.DataSource = customerView; + customersDataGridView.DataSource = customersBindingSource; + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Padding/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Padding/CS/Form1.cs new file mode 100644 index 0000000000..03f624ef88 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Padding/CS/Form1.cs @@ -0,0 +1,105 @@ +// +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace MarginAndPadding +{ + public class Form1 : Form + { + private Panel panel1; + private RichTextBox richTextBox1; + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + // + // This code example demonstrates using the Padding property to + // create a border around a RichTextBox control. + public Form1() + { + InitializeComponent(); + + this.panel1.BackColor = System.Drawing.Color.Blue; + this.panel1.Padding = new System.Windows.Forms.Padding(5); + this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; + + this.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; + this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; + } + // + + /// + /// 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.panel1 = new System.Windows.Forms.Panel(); + this.richTextBox1 = new System.Windows.Forms.RichTextBox(); + this.panel1.SuspendLayout(); + this.SuspendLayout(); + // + // panel1 + // + this.panel1.Controls.Add(this.richTextBox1); + this.panel1.Location = new System.Drawing.Point(20, 20); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(491, 313); + this.panel1.TabIndex = 0; + // + // richTextBox1 + // + this.richTextBox1.Location = new System.Drawing.Point(5, 5); + this.richTextBox1.Name = "richTextBox1"; + this.richTextBox1.Size = new System.Drawing.Size(481, 303); + this.richTextBox1.TabIndex = 0; + this.richTextBox1.Text = ""; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(531, 353); + this.Controls.Add(this.panel1); + this.Name = "Form1"; + this.Padding = new System.Windows.Forms.Padding(20); + this.Text = "Form1"; + this.panel1.ResumeLayout(false); + this.ResumeLayout(false); + } + + #endregion + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.PictureBox.LoadAsync/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.PictureBox.LoadAsync/CS/Form1.cs new file mode 100644 index 0000000000..b5fe64d50c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.PictureBox.LoadAsync/CS/Form1.cs @@ -0,0 +1,153 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace PictureBoxLoadAsync +{ + public class Form1 : Form + { + private Button loadButton; + private Button cancelLoadButton; + private PictureBox pictureBox1; + + // + public Form1() + { + InitializeComponent(); + + this.pictureBox1.LoadCompleted += + new System.ComponentModel.AsyncCompletedEventHandler(this.pictureBox1_LoadCompleted); + } + // + + // + private void loadButton_Click(object sender, EventArgs e) + { + // Replace with a real url. + pictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg"); + } + // + + // + private void cancelLoadButton_Click(object sender, EventArgs e) + { + pictureBox1.CancelAsync(); + } + // + + // + private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e) + { + if (e.Error != null) + { + MessageBox.Show(e.Error.Message, "Load Error"); + } + else if (e.Cancelled) + { + MessageBox.Show("Load canceled", "Canceled"); + } + else + { + MessageBox.Show("Load completed", "Completed"); + } + } + // + + /// + /// 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.pictureBox1 = new System.Windows.Forms.PictureBox(); + this.loadButton = new System.Windows.Forms.Button(); + this.cancelLoadButton = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox1 + // + this.pictureBox1.BackColor = System.Drawing.SystemColors.ControlDark; + this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top; + this.pictureBox1.Location = new System.Drawing.Point(10, 10); + this.pictureBox1.Margin = new System.Windows.Forms.Padding(10); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size(323, 300); + this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; + this.pictureBox1.TabIndex = 0; + this.pictureBox1.TabStop = false; + // + // loadButton + // + this.loadButton.Location = new System.Drawing.Point(88, 323); + this.loadButton.Name = "loadButton"; + this.loadButton.Size = new System.Drawing.Size(75, 23); + this.loadButton.TabIndex = 1; + this.loadButton.Text = "Load"; + this.loadButton.Click += new System.EventHandler(this.loadButton_Click); + // + // cancelLoadButton + // + this.cancelLoadButton.Location = new System.Drawing.Point(170, 323); + this.cancelLoadButton.Name = "cancelLoadButton"; + this.cancelLoadButton.Size = new System.Drawing.Size(75, 23); + this.cancelLoadButton.TabIndex = 2; + this.cancelLoadButton.Text = "Cancel"; + this.cancelLoadButton.Click += new System.EventHandler(this.cancelLoadButton_Click); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(343, 364); + this.Controls.Add(this.cancelLoadButton); + this.Controls.Add(this.loadButton); + this.Controls.Add(this.pictureBox1); + this.Name = "Form1"; + this.Padding = new System.Windows.Forms.Padding(10); + this.Text = "Form1"; + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); + this.ResumeLayout(false); + } + + #endregion + + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/CS/form1.cs new file mode 100644 index 0000000000..cf85726c4a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/CS/form1.cs @@ -0,0 +1,79 @@ +// +using System; +using System.Runtime.InteropServices; +using System.Drawing; +using System.Windows.Forms; + +namespace SimulateKeyPress +{ + class Form1 : Form + { + private Button button1 = new Button(); + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + button1.Location = new Point(10, 10); + button1.TabIndex = 0; + button1.Text = "Click to automate Calculator"; + button1.AutoSize = true; + button1.Click += new EventHandler(button1_Click); + + this.DoubleClick += new EventHandler(Form1_DoubleClick); + this.Controls.Add(button1); + } + + // + // Get a handle to an application window. + [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindow(string lpClassName, + string lpWindowName); + + // Activate an application window. + [DllImport("USER32.DLL")] + public static extern bool SetForegroundWindow(IntPtr hWnd); + + // Send a series of key presses to the Calculator application. + private void button1_Click(object sender, EventArgs e) + { + // Get a handle to the Calculator application. The window class + // and window name were obtained using the Spy++ tool. + IntPtr calculatorHandle = FindWindow("CalcFrame","Calculator"); + + // Verify that Calculator is a running process. + if (calculatorHandle == IntPtr.Zero) + { + MessageBox.Show("Calculator is not running."); + return; + } + + // Make Calculator the foreground application and send it + // a set of calculations. + SetForegroundWindow(calculatorHandle); + SendKeys.SendWait("111"); + SendKeys.SendWait("*"); + SendKeys.SendWait("11"); + SendKeys.SendWait("="); + } + // + + // + // Send a key to the button when the user double-clicks anywhere + // on the form. + private void Form1_DoubleClick(object sender, EventArgs e) + { + // Send the enter key to the button, which raises the click + // event for the button. This works because the tab stop of + // the button is 0. + SendKeys.Send("{ENTER}"); + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/CS/form1.cs new file mode 100644 index 0000000000..8f4f853371 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/CS/form1.cs @@ -0,0 +1,144 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace SingleVersusDoubleClick +{ + class Form1 : Form + { + private Rectangle hitTestRectangle = new Rectangle(); + private Rectangle doubleClickRectangle = new Rectangle(); + private TextBox textBox1 = new TextBox(); + private Timer doubleClickTimer = new Timer(); + private ProgressBar doubleClickBar = new ProgressBar(); + private Label label1 = new Label(); + private Label label2 = new Label(); + private bool isFirstClick = true; + private bool isDoubleClick = false; + private int milliseconds = 0; + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + label1.Location = new Point(30, 5); + label1.Size = new Size(100, 15); + label1.Text = "Hit test rectangle:"; + + label2.Location = new Point(30, 70); + label2.Size = new Size(100, 15); + label2.Text = "Double click timer:"; + + hitTestRectangle.Location = new Point(30, 20); + hitTestRectangle.Size = new Size(100, 40); + + doubleClickTimer.Interval = 100; + doubleClickTimer.Tick += + new EventHandler(doubleClickTimer_Tick); + + doubleClickBar.Location = new Point(30, 85); + doubleClickBar.Minimum = 0; + doubleClickBar.Maximum = SystemInformation.DoubleClickTime; + + textBox1.Location = new Point(30, 120); + textBox1.Size = new Size(200, 100); + textBox1.AutoSize = false; + textBox1.Multiline = true; + + this.Paint += new PaintEventHandler(Form1_Paint); + this.MouseDown += new MouseEventHandler(Form1_MouseDown); + this.Controls.AddRange(new Control[] { doubleClickBar, textBox1, + label1, label2 }); + } + + // + // Detect a valid single click or double click. + void Form1_MouseDown(object sender, MouseEventArgs e) + { + // Verify that the mouse click is in the main hit + // test rectangle. + if (!hitTestRectangle.Contains(e.Location)) + { + return; + } + + // This is the first mouse click. + if (isFirstClick) + { + isFirstClick = false; + + // Determine the location and size of the double click + // rectangle area to draw around the cursor point. + doubleClickRectangle = new Rectangle( + e.X - (SystemInformation.DoubleClickSize.Width / 2), + e.Y - (SystemInformation.DoubleClickSize.Height / 2), + SystemInformation.DoubleClickSize.Width, + SystemInformation.DoubleClickSize.Height); + Invalidate(); + + // Start the double click timer. + doubleClickTimer.Start(); + } + + // This is the second mouse click. + else + { + // Verify that the mouse click is within the double click + // rectangle and is within the system-defined double + // click period. + if (doubleClickRectangle.Contains(e.Location) && + milliseconds < SystemInformation.DoubleClickTime) + { + isDoubleClick = true; + } + } + } + // + + void doubleClickTimer_Tick(object sender, EventArgs e) + { + milliseconds += 100; + doubleClickBar.Increment(100); + + // The timer has reached the double click time limit. + if (milliseconds >= SystemInformation.DoubleClickTime) + { + doubleClickTimer.Stop(); + + if (isDoubleClick) + { + textBox1.AppendText("Perform double click action"); + textBox1.AppendText(Environment.NewLine); + } + else + { + textBox1.AppendText("Perform single click action"); + textBox1.AppendText(Environment.NewLine); + } + + // Allow the MouseDown event handler to process clicks again. + isFirstClick = true; + isDoubleClick = false; + milliseconds = 0; + doubleClickBar.Value = 0; + } + } + + // Paint the hit test and double click rectangles. + void Form1_Paint(object sender, PaintEventArgs e) + { + // Draw the border of the main hit test rectangle. + e.Graphics.DrawRectangle(Pens.Black, hitTestRectangle); + + // Fill in the double click rectangle. + e.Graphics.FillRectangle(Brushes.Blue, doubleClickRectangle); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Sound/CS/soundtestform.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Sound/CS/soundtestform.cs new file mode 100644 index 0000000000..59dc8014c8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.Sound/CS/soundtestform.cs @@ -0,0 +1,383 @@ +// + +using System; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Media; +using System.Windows.Forms; + +namespace SoundApiExample +{ + public class SoundTestForm : System.Windows.Forms.Form + { + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox filepathTextbox; + private System.Windows.Forms.Button playOnceSyncButton; + private System.Windows.Forms.Button playOnceAsyncButton; + private System.Windows.Forms.Button playLoopAsyncButton; + private System.Windows.Forms.Button selectFileButton; + + private System.Windows.Forms.Button stopButton; + private System.Windows.Forms.StatusBar statusBar; + private System.Windows.Forms.Button loadSyncButton; + private System.Windows.Forms.Button loadAsyncButton; + private SoundPlayer player; + + public SoundTestForm() + { + // Initialize Forms Designer generated code. + InitializeComponent(); + + // Disable playback controls until a valid .wav file + // is selected. + EnablePlaybackControls(false); + + // Set up the status bar and other controls. + InitializeControls(); + + // Set up the SoundPlayer object. + InitializeSound(); + } + + // Sets up the status bar and other controls. + private void InitializeControls() + { + // Set up the status bar. + StatusBarPanel panel = new StatusBarPanel(); + panel.BorderStyle = StatusBarPanelBorderStyle.Sunken; + panel.Text = "Ready."; + panel.AutoSize = StatusBarPanelAutoSize.Spring; + this.statusBar.ShowPanels = true; + this.statusBar.Panels.Add(panel); + } + + // Sets up the SoundPlayer object. + private void InitializeSound() + { + // Create an instance of the SoundPlayer class. + player = new SoundPlayer(); + + // Listen for the LoadCompleted event. + player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted); + + // Listen for the SoundLocationChanged event. + player.SoundLocationChanged += new EventHandler(player_LocationChanged); + } + + private void selectFileButton_Click(object sender, + System.EventArgs e) + { + // Create a new OpenFileDialog. + OpenFileDialog dlg = new OpenFileDialog(); + + // Make sure the dialog checks for existence of the + // selected file. + dlg.CheckFileExists = true; + + // Allow selection of .wav files only. + dlg.Filter = "WAV files (*.wav)|*.wav"; + dlg.DefaultExt = ".wav"; + + // Activate the file selection dialog. + if (dlg.ShowDialog() == DialogResult.OK) + { + // Get the selected file's path from the dialog. + this.filepathTextbox.Text = dlg.FileName; + + // Assign the selected file's path to + // the SoundPlayer object. + player.SoundLocation = filepathTextbox.Text; + } + } + + // Convenience method for setting message text in + // the status bar. + private void ReportStatus(string statusMessage) + { + // If the caller passed in a message... + if (!string.IsNullOrEmpty(statusMessage)) + { + // ...post the caller's message to the status bar. + this.statusBar.Panels[0].Text = statusMessage; + } + } + + // Enables and disables play controls. + private void EnablePlaybackControls(bool enabled) + { + this.playOnceSyncButton.Enabled = enabled; + this.playOnceAsyncButton.Enabled = enabled; + this.playLoopAsyncButton.Enabled = enabled; + this.stopButton.Enabled = enabled; + } + + private void filepathTextbox_TextChanged(object sender, + EventArgs e) + { + // Disable playback controls until the new .wav is loaded. + EnablePlaybackControls(false); + } + + private void loadSyncButton_Click(object sender, + System.EventArgs e) + { + // Disable playback controls until the .wav is + // successfully loaded. The LoadCompleted event + // handler will enable them. + EnablePlaybackControls(false); + + // + try + { + // Assign the selected file's path to + // the SoundPlayer object. + player.SoundLocation = filepathTextbox.Text; + + // Load the .wav file. + player.Load(); + } + catch (Exception ex) + { + ReportStatus(ex.Message); + } + // + } + + private void loadAsyncButton_Click(System.Object sender, + System.EventArgs e) + { + // Disable playback controls until the .wav is + // successfully loaded. The LoadCompleted event + // handler will enable them. + EnablePlaybackControls(false); + + // + try + { + // Assign the selected file's path to + // the SoundPlayer object. + player.SoundLocation = this.filepathTextbox.Text; + + // Load the .wav file. + player.LoadAsync(); + } + catch (Exception ex) + { + ReportStatus(ex.Message); + } + // + } + + // Synchronously plays the selected .wav file once. + // If the file is large, UI response will be visibly + // affected. + private void playOnceSyncButton_Click(object sender, + System.EventArgs e) + { + // + ReportStatus("Playing .wav file synchronously."); + player.PlaySync(); + ReportStatus("Finished playing .wav file synchronously."); + // + } + + // Asynchronously plays the selected .wav file once. + private void playOnceAsyncButton_Click(object sender, + System.EventArgs e) + { + // + ReportStatus("Playing .wav file asynchronously."); + player.Play(); + // + } + + // Asynchronously plays the selected .wav file until the user + // clicks the Stop button. + private void playLoopAsyncButton_Click(object sender, + System.EventArgs e) + { + // + ReportStatus("Looping .wav file asynchronously."); + player.PlayLooping(); + // + } + + // Stops the currently playing .wav file, if any. + private void stopButton_Click(System.Object sender, + System.EventArgs e) + { + // + player.Stop(); + ReportStatus("Stopped by user."); + // + } + + // + // Handler for the LoadCompleted event. + private void player_LoadCompleted(object sender, + AsyncCompletedEventArgs e) + { + string message = String.Format("LoadCompleted: {0}", + this.filepathTextbox.Text); + ReportStatus(message); + EnablePlaybackControls(true); + } + // + + // + // Handler for the SoundLocationChanged event. + private void player_LocationChanged(object sender, EventArgs e) + { + string message = String.Format("SoundLocationChanged: {0}", + player.SoundLocation); + ReportStatus(message); + } + // + + // + private void playSoundFromResource(object sender, EventArgs e) + { + System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); + System.IO.Stream s = a.GetManifestResourceStream(".chimes.wav"); + SoundPlayer player = new SoundPlayer(s); + player.Play(); + } + // + + #region Windows Form Designer generated code + private void InitializeComponent() + { + this.filepathTextbox = new System.Windows.Forms.TextBox(); + this.selectFileButton = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.loadSyncButton = new System.Windows.Forms.Button(); + this.playOnceSyncButton = new System.Windows.Forms.Button(); + this.playOnceAsyncButton = new System.Windows.Forms.Button(); + this.stopButton = new System.Windows.Forms.Button(); + this.playLoopAsyncButton = new System.Windows.Forms.Button(); + this.statusBar = new System.Windows.Forms.StatusBar(); + this.loadAsyncButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // filepathTextbox + // + this.filepathTextbox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); + this.filepathTextbox.Location = new System.Drawing.Point(7, 25); + this.filepathTextbox.Name = "filepathTextbox"; + this.filepathTextbox.Size = new System.Drawing.Size(263, 20); + this.filepathTextbox.TabIndex = 1; + this.filepathTextbox.Text = ""; + this.filepathTextbox.TextChanged += new System.EventHandler(this.filepathTextbox_TextChanged); + // + // selectFileButton + // + this.selectFileButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.selectFileButton.Location = new System.Drawing.Point(276, 25); + this.selectFileButton.Name = "selectFileButton"; + this.selectFileButton.Size = new System.Drawing.Size(23, 21); + this.selectFileButton.TabIndex = 2; + this.selectFileButton.Text = "..."; + this.selectFileButton.Click += new System.EventHandler(this.selectFileButton_Click); + // + // label1 + // + this.label1.Location = new System.Drawing.Point(7, 7); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(145, 17); + this.label1.TabIndex = 3; + this.label1.Text = ".wav path or URL:"; + // + // loadSyncButton + // + this.loadSyncButton.Location = new System.Drawing.Point(7, 53); + this.loadSyncButton.Name = "loadSyncButton"; + this.loadSyncButton.Size = new System.Drawing.Size(142, 23); + this.loadSyncButton.TabIndex = 4; + this.loadSyncButton.Text = "Load Synchronously"; + this.loadSyncButton.Click += new System.EventHandler(this.loadSyncButton_Click); + // + // playOnceSyncButton + // + this.playOnceSyncButton.Location = new System.Drawing.Point(7, 86); + this.playOnceSyncButton.Name = "playOnceSyncButton"; + this.playOnceSyncButton.Size = new System.Drawing.Size(142, 23); + this.playOnceSyncButton.TabIndex = 5; + this.playOnceSyncButton.Text = "Play Once Synchronously"; + this.playOnceSyncButton.Click += new System.EventHandler(this.playOnceSyncButton_Click); + // + // playOnceAsyncButton + // + this.playOnceAsyncButton.Location = new System.Drawing.Point(149, 86); + this.playOnceAsyncButton.Name = "playOnceAsyncButton"; + this.playOnceAsyncButton.Size = new System.Drawing.Size(147, 23); + this.playOnceAsyncButton.TabIndex = 6; + this.playOnceAsyncButton.Text = "Play Once Asynchronously"; + this.playOnceAsyncButton.Click += new System.EventHandler(this.playOnceAsyncButton_Click); + // + // stopButton + // + this.stopButton.Location = new System.Drawing.Point(149, 109); + this.stopButton.Name = "stopButton"; + this.stopButton.Size = new System.Drawing.Size(147, 23); + this.stopButton.TabIndex = 7; + this.stopButton.Text = "Stop"; + this.stopButton.Click += new System.EventHandler(this.stopButton_Click); + // + // playLoopAsyncButton + // + this.playLoopAsyncButton.Location = new System.Drawing.Point(7, 109); + this.playLoopAsyncButton.Name = "playLoopAsyncButton"; + this.playLoopAsyncButton.Size = new System.Drawing.Size(142, 23); + this.playLoopAsyncButton.TabIndex = 8; + this.playLoopAsyncButton.Text = "Loop Asynchronously"; + this.playLoopAsyncButton.Click += new System.EventHandler(this.playLoopAsyncButton_Click); + // + // statusBar + // + this.statusBar.Location = new System.Drawing.Point(0, 146); + this.statusBar.Name = "statusBar"; + this.statusBar.Size = new System.Drawing.Size(306, 22); + this.statusBar.SizingGrip = false; + this.statusBar.TabIndex = 9; + this.statusBar.Text = "(no status)"; + // + // loadAsyncButton + // + this.loadAsyncButton.Location = new System.Drawing.Point(149, 53); + this.loadAsyncButton.Name = "loadAsyncButton"; + this.loadAsyncButton.Size = new System.Drawing.Size(147, 23); + this.loadAsyncButton.TabIndex = 10; + this.loadAsyncButton.Text = "Load Asynchronously"; + this.loadAsyncButton.Click += new System.EventHandler(this.loadAsyncButton_Click); + // + // SoundTestForm + // + this.ClientSize = new System.Drawing.Size(306, 168); + this.Controls.Add(this.loadAsyncButton); + this.Controls.Add(this.statusBar); + this.Controls.Add(this.playLoopAsyncButton); + this.Controls.Add(this.stopButton); + this.Controls.Add(this.playOnceAsyncButton); + this.Controls.Add(this.playOnceSyncButton); + this.Controls.Add(this.loadSyncButton); + this.Controls.Add(this.label1); + this.Controls.Add(this.selectFileButton); + this.Controls.Add(this.filepathTextbox); + this.MinimumSize = new System.Drawing.Size(310, 165); + this.Name = "SoundTestForm"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; + this.Text = "Sound API Test Form"; + this.ResumeLayout(false); + } + #endregion + + [STAThread] + static void Main() + { + Application.Run(new SoundTestForm()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/CS/TlpAnchorExampleForm.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/CS/TlpAnchorExampleForm.cs new file mode 100644 index 0000000000..10da402888 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/CS/TlpAnchorExampleForm.cs @@ -0,0 +1,269 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Windows.Forms; + +public class Form1 : Form +{ + public Form1() + { + InitializeComponent(); + } + + private System.ComponentModel.IContainer components = null; + + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button3; + private System.Windows.Forms.Button button4; + private System.Windows.Forms.Button button5; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; + private System.Windows.Forms.Button button6; + private System.Windows.Forms.Button button7; + private System.Windows.Forms.Button button8; + private System.Windows.Forms.Button button9; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; + private System.Windows.Forms.Button button10; + private System.Windows.Forms.Button button11; + private System.Windows.Forms.Button button12; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.button3 = new System.Windows.Forms.Button(); + this.button4 = new System.Windows.Forms.Button(); + this.button5 = new System.Windows.Forms.Button(); + this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + this.button6 = new System.Windows.Forms.Button(); + this.button7 = new System.Windows.Forms.Button(); + this.button8 = new System.Windows.Forms.Button(); + this.button9 = new System.Windows.Forms.Button(); + this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); + this.button10 = new System.Windows.Forms.Button(); + this.button11 = new System.Windows.Forms.Button(); + this.button12 = new System.Windows.Forms.Button(); + this.tableLayoutPanel1.SuspendLayout(); + this.tableLayoutPanel2.SuspendLayout(); + this.tableLayoutPanel3.SuspendLayout(); + this.SuspendLayout(); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel1.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; + this.tableLayoutPanel1.ColumnCount = 5; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.Controls.Add(this.button1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.button2, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.button3, 2, 0); + this.tableLayoutPanel1.Controls.Add(this.button4, 3, 0); + this.tableLayoutPanel1.Controls.Add(this.button5, 4, 0); + this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 12); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 1; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(731, 100); + this.tableLayoutPanel1.TabIndex = 0; + // + // button1 + // + this.button1.Anchor = System.Windows.Forms.AnchorStyles.None; + this.button1.AutoSize = true; + this.button1.Location = new System.Drawing.Point(34, 38); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(79, 23); + this.button1.TabIndex = 0; + this.button1.Text = "Anchor=None"; + // + // button2 + // + this.button2.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.button2.AutoSize = true; + this.button2.Location = new System.Drawing.Point(150, 38); + this.button2.Name = "button2"; + this.button2.TabIndex = 1; + this.button2.Text = "Anchor=Left"; + // + // button3 + // + this.button3.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.button3.AutoSize = true; + this.button3.Location = new System.Drawing.Point(328, 4); + this.button3.Name = "button3"; + this.button3.TabIndex = 2; + this.button3.Text = "Anchor=Top"; + // + // button4 + // + this.button4.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.button4.AutoSize = true; + this.button4.Location = new System.Drawing.Point(503, 38); + this.button4.Name = "button4"; + this.button4.Size = new System.Drawing.Size(78, 23); + this.button4.TabIndex = 3; + this.button4.Text = "Anchor=Right"; + // + // button5 + // + this.button5.Anchor = System.Windows.Forms.AnchorStyles.Bottom; + this.button5.AutoSize = true; + this.button5.Location = new System.Drawing.Point(614, 73); + this.button5.Name = "button5"; + this.button5.Size = new System.Drawing.Size(86, 23); + this.button5.TabIndex = 4; + this.button5.Text = "Anchor=Bottom"; + // + // tableLayoutPanel2 + // + this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel2.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; + this.tableLayoutPanel2.ColumnCount = 4; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); + this.tableLayoutPanel2.Controls.Add(this.button6, 0, 0); + this.tableLayoutPanel2.Controls.Add(this.button7, 1, 0); + this.tableLayoutPanel2.Controls.Add(this.button8, 2, 0); + this.tableLayoutPanel2.Controls.Add(this.button9, 3, 0); + this.tableLayoutPanel2.Location = new System.Drawing.Point(12, 118); + this.tableLayoutPanel2.Name = "tableLayoutPanel2"; + this.tableLayoutPanel2.RowCount = 1; + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel2.Size = new System.Drawing.Size(731, 100); + this.tableLayoutPanel2.TabIndex = 1; + // + // button6 + // + this.button6.AutoSize = true; + this.button6.Location = new System.Drawing.Point(4, 4); + this.button6.Name = "button6"; + this.button6.TabIndex = 0; + this.button6.Text = "Top, Left"; + // + // button7 + // + this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.button7.AutoSize = true; + this.button7.Location = new System.Drawing.Point(286, 4); + this.button7.Name = "button7"; + this.button7.TabIndex = 1; + this.button7.Text = "Top, Right"; + // + // button8 + // + this.button8.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.button8.AutoSize = true; + this.button8.Location = new System.Drawing.Point(466, 73); + this.button8.Name = "button8"; + this.button8.Size = new System.Drawing.Size(77, 23); + this.button8.TabIndex = 2; + this.button8.Text = "Bottom, Right"; + // + // button9 + // + this.button9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.button9.AutoSize = true; + this.button9.Location = new System.Drawing.Point(550, 73); + this.button9.Name = "button9"; + this.button9.TabIndex = 3; + this.button9.Text = "Bottom, Left"; + // + // tableLayoutPanel3 + // + this.tableLayoutPanel3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel3.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; + this.tableLayoutPanel3.ColumnCount = 3; + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); + this.tableLayoutPanel3.Controls.Add(this.button10, 0, 0); + this.tableLayoutPanel3.Controls.Add(this.button11, 1, 0); + this.tableLayoutPanel3.Controls.Add(this.button12, 2, 0); + this.tableLayoutPanel3.Location = new System.Drawing.Point(12, 225); + this.tableLayoutPanel3.Name = "tableLayoutPanel3"; + this.tableLayoutPanel3.RowCount = 1; + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel3.Size = new System.Drawing.Size(731, 100); + this.tableLayoutPanel3.TabIndex = 2; + // + // button10 + // + this.button10.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button10.Location = new System.Drawing.Point(4, 39); + this.button10.Name = "button10"; + this.button10.Size = new System.Drawing.Size(236, 23); + this.button10.TabIndex = 0; + this.button10.Text = "Left, Right"; + // + // button11 + // + this.button11.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom))); + this.button11.Location = new System.Drawing.Point(327, 4); + this.button11.Name = "button11"; + this.button11.Size = new System.Drawing.Size(75, 93); + this.button11.TabIndex = 1; + this.button11.Text = "Top, Bottom"; + // + // button12 + // + this.button12.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.button12.Location = new System.Drawing.Point(490, 4); + this.button12.Name = "button12"; + this.button12.Size = new System.Drawing.Size(237, 93); + this.button12.TabIndex = 2; + this.button12.Text = "Top, Bottom, Left, Right"; + // + // Form1 + // + this.AutoSize = true; + this.ClientSize = new System.Drawing.Size(755, 338); + this.Controls.Add(this.tableLayoutPanel3); + this.Controls.Add(this.tableLayoutPanel2); + this.Controls.Add(this.tableLayoutPanel1); + this.Name = "Form1"; + this.Text = "Form1"; + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); + this.tableLayoutPanel2.ResumeLayout(false); + this.tableLayoutPanel2.PerformLayout(); + this.tableLayoutPanel3.ResumeLayout(false); + this.ResumeLayout(false); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} + +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/CS/basicdataentryform.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/CS/basicdataentryform.cs new file mode 100644 index 0000000000..251e875d0e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/CS/basicdataentryform.cs @@ -0,0 +1,347 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +// This form demonstrates how to build a form layout that adjusts well +// when the user resizes the form. It also demonstrates a layout that +// responds well to localization. +class BasicDataEntryForm : System.Windows.Forms.Form +{ + public BasicDataEntryForm() + { + InitializeComponent(); + } + + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + public override string ToString() + { + return "Basic Data Entry Form"; + } + + private void okBtn_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void cancelBtn_Click(object sender, EventArgs e) + { + this.Close(); + } + + private void InitializeComponent() + { + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.label4 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.label6 = new System.Windows.Forms.Label(); + this.label9 = new System.Windows.Forms.Label(); + this.textBox2 = new System.Windows.Forms.TextBox(); + this.textBox3 = new System.Windows.Forms.TextBox(); + this.textBox4 = new System.Windows.Forms.TextBox(); + this.textBox5 = new System.Windows.Forms.TextBox(); + this.maskedTextBox1 = new System.Windows.Forms.MaskedTextBox(); + this.maskedTextBox2 = new System.Windows.Forms.MaskedTextBox(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.label7 = new System.Windows.Forms.Label(); + this.label8 = new System.Windows.Forms.Label(); + this.richTextBox1 = new System.Windows.Forms.RichTextBox(); + this.cancelBtn = new System.Windows.Forms.Button(); + this.okBtn = new System.Windows.Forms.Button(); + this.tableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); +// +// tableLayoutPanel1 +// + this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel1.ColumnCount = 4; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.label2, 2, 0); + this.tableLayoutPanel1.Controls.Add(this.label3, 0, 1); + this.tableLayoutPanel1.Controls.Add(this.label4, 0, 2); + this.tableLayoutPanel1.Controls.Add(this.label5, 0, 3); + this.tableLayoutPanel1.Controls.Add(this.label6, 2, 3); + this.tableLayoutPanel1.Controls.Add(this.label9, 2, 4); + this.tableLayoutPanel1.Controls.Add(this.textBox2, 1, 1); + this.tableLayoutPanel1.Controls.Add(this.textBox3, 1, 2); + this.tableLayoutPanel1.Controls.Add(this.textBox4, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.textBox5, 3, 0); + this.tableLayoutPanel1.Controls.Add(this.maskedTextBox1, 1, 4); + this.tableLayoutPanel1.Controls.Add(this.maskedTextBox2, 3, 4); + this.tableLayoutPanel1.Controls.Add(this.comboBox1, 3, 3); + this.tableLayoutPanel1.Controls.Add(this.textBox1, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.label7, 0, 5); + this.tableLayoutPanel1.Controls.Add(this.label8, 0, 4); + this.tableLayoutPanel1.Controls.Add(this.richTextBox1, 1, 5); + this.tableLayoutPanel1.Location = new System.Drawing.Point(13, 13); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 6; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(623, 286); + this.tableLayoutPanel1.TabIndex = 0; +// +// label1 +// + this.label1.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(3, 7); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(59, 14); + this.label1.TabIndex = 20; + this.label1.Text = "First Name"; +// +// label2 +// + this.label2.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(323, 7); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(59, 14); + this.label2.TabIndex = 21; + this.label2.Text = "Last Name"; +// +// label3 +// + this.label3.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(10, 35); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(52, 14); + this.label3.TabIndex = 22; + this.label3.Text = "Address1"; +// +// label4 +// + this.label4.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(7, 63); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(55, 14); + this.label4.TabIndex = 23; + this.label4.Text = "Address 2"; +// +// label5 +// + this.label5.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(38, 91); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(24, 14); + this.label5.TabIndex = 24; + this.label5.Text = "City"; +// +// label6 +// + this.label6.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(351, 91); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(31, 14); + this.label6.TabIndex = 25; + this.label6.Text = "State"; +// +// label9 +// + this.label9.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(326, 119); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(56, 14); + this.label9.TabIndex = 33; + this.label9.Text = "Phone (H)"; +// +// textBox2 +// + this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel1.SetColumnSpan(this.textBox2, 3); + this.textBox2.Location = new System.Drawing.Point(68, 32); + this.textBox2.Name = "textBox2"; + this.textBox2.Size = new System.Drawing.Size(552, 20); + this.textBox2.TabIndex = 2; +// +// textBox3 +// + this.textBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel1.SetColumnSpan(this.textBox3, 3); + this.textBox3.Location = new System.Drawing.Point(68, 60); + this.textBox3.Name = "textBox3"; + this.textBox3.Size = new System.Drawing.Size(552, 20); + this.textBox3.TabIndex = 3; +// +// textBox4 +// + this.textBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.textBox4.Location = new System.Drawing.Point(68, 88); + this.textBox4.Name = "textBox4"; + this.textBox4.Size = new System.Drawing.Size(249, 20); + this.textBox4.TabIndex = 4; +// +// textBox5 +// + this.textBox5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.textBox5.Location = new System.Drawing.Point(388, 4); + this.textBox5.Name = "textBox5"; + this.textBox5.Size = new System.Drawing.Size(232, 20); + this.textBox5.TabIndex = 1; +// +// maskedTextBox1 +// + this.maskedTextBox1.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.maskedTextBox1.Location = new System.Drawing.Point(68, 116); + this.maskedTextBox1.Mask = "(999)000-0000"; + this.maskedTextBox1.Name = "maskedTextBox1"; + this.maskedTextBox1.TabIndex = 6; +// +// maskedTextBox2 +// + this.maskedTextBox2.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.maskedTextBox2.Location = new System.Drawing.Point(388, 116); + this.maskedTextBox2.Mask = "(999)000-0000"; + this.maskedTextBox2.Name = "maskedTextBox2"; + this.maskedTextBox2.TabIndex = 7; +// +// comboBox1 +// + this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Items.AddRange(new object[] { + "AK - Alaska", + "WA - Washington"}); + this.comboBox1.Location = new System.Drawing.Point(388, 87); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(100, 21); + this.comboBox1.TabIndex = 5; +// +// textBox1 +// + this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.textBox1.Location = new System.Drawing.Point(68, 4); + this.textBox1.Name = "textBox1"; + this.textBox1.Size = new System.Drawing.Size(249, 20); + this.textBox1.TabIndex = 0; +// +// label7 +// + this.label7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(28, 143); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(34, 14); + this.label7.TabIndex = 26; + this.label7.Text = "Notes"; +// +// label8 +// + this.label8.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(4, 119); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(58, 14); + this.label8.TabIndex = 32; + this.label8.Text = "Phone (W)"; +// +// richTextBox1 +// + this.tableLayoutPanel1.SetColumnSpan(this.richTextBox1, 3); + this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; + this.richTextBox1.Location = new System.Drawing.Point(68, 143); + this.richTextBox1.Name = "richTextBox1"; + this.richTextBox1.Size = new System.Drawing.Size(552, 140); + this.richTextBox1.TabIndex = 8; + this.richTextBox1.Text = ""; +// +// cancelBtn +// + this.cancelBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelBtn.Location = new System.Drawing.Point(558, 306); + this.cancelBtn.Name = "cancelBtn"; + this.cancelBtn.TabIndex = 1; + this.cancelBtn.Text = "Cancel"; + this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click); +// +// okBtn +// + this.okBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.okBtn.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okBtn.Location = new System.Drawing.Point(476, 306); + this.okBtn.Name = "okBtn"; + this.okBtn.TabIndex = 0; + this.okBtn.Text = "OK"; + this.okBtn.Click += new System.EventHandler(this.okBtn_Click); +// +// BasicDataEntryForm +// + this.ClientSize = new System.Drawing.Size(642, 338); + this.Controls.Add(this.okBtn); + this.Controls.Add(this.cancelBtn); + this.Controls.Add(this.tableLayoutPanel1); + this.Name = "BasicDataEntryForm"; + this.Padding = new System.Windows.Forms.Padding(9); + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "Basic Data Entry"; + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); + this.ResumeLayout(false); + } + + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.Label label9; + private System.Windows.Forms.Button cancelBtn; + private System.Windows.Forms.Button okBtn; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.TextBox textBox2; + private System.Windows.Forms.TextBox textBox3; + private System.Windows.Forms.TextBox textBox4; + private System.Windows.Forms.TextBox textBox5; + private System.Windows.Forms.MaskedTextBox maskedTextBox1; + private System.Windows.Forms.MaskedTextBox maskedTextBox2; + private System.Windows.Forms.ComboBox comboBox1; + private System.Windows.Forms.RichTextBox richTextBox1; + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new BasicDataEntryForm()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/CS/localizableform.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/CS/localizableform.cs new file mode 100644 index 0000000000..f2230b947b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/CS/localizableform.cs @@ -0,0 +1,260 @@ +//--------------------------------------------------------------------- +// This file is part of the Microsoft .NET Framework SDK Code Samples. +// +// Copyright (C) Microsoft Corporation. All rights reserved. +// +//This source code is intended only as a supplement to Microsoft +//Development Tools and/or on-line documentation. See these other +//materials for detailed information regarding Microsoft code samples. +// +//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY +//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A +//PARTICULAR PURPOSE. +//--------------------------------------------------------------------- + +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace TableLayoutPanelSample +{ + public class LocalizableForm : Form + { + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.ListView listView1; + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.Button button3; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; + private System.Windows.Forms.Button button4; + private System.Windows.Forms.Button button5; + private System.Windows.Forms.Button button6; + private System.Windows.Forms.Label label1; + + private System.ComponentModel.IContainer components = null; + + public LocalizableForm() + { + InitializeComponent(); + } + + private void AddText(object sender, EventArgs e) + { + ((Button)sender).Text += "x"; + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + System.Windows.Forms.ListViewGroup listViewGroup16 = new System.Windows.Forms.ListViewGroup("First Group", System.Windows.Forms.HorizontalAlignment.Left); + System.Windows.Forms.ListViewGroup listViewGroup17 = new System.Windows.Forms.ListViewGroup("Second Group", System.Windows.Forms.HorizontalAlignment.Left); + System.Windows.Forms.ListViewGroup listViewGroup18 = new System.Windows.Forms.ListViewGroup("Third Group", System.Windows.Forms.HorizontalAlignment.Left); + System.Windows.Forms.ListViewItem listViewItem26 = new System.Windows.Forms.ListViewItem("Item 1"); + System.Windows.Forms.ListViewItem listViewItem27 = new System.Windows.Forms.ListViewItem("Item 2"); + System.Windows.Forms.ListViewItem listViewItem28 = new System.Windows.Forms.ListViewItem("Item 3"); + System.Windows.Forms.ListViewItem listViewItem29 = new System.Windows.Forms.ListViewItem("Item 4"); + System.Windows.Forms.ListViewItem listViewItem30 = new System.Windows.Forms.ListViewItem("Item 5"); + this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.listView1 = new System.Windows.Forms.ListView(); + this.panel1 = new System.Windows.Forms.Panel(); + this.button3 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.button1 = new System.Windows.Forms.Button(); + this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + this.button4 = new System.Windows.Forms.Button(); + this.button5 = new System.Windows.Forms.Button(); + this.button6 = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.tableLayoutPanel1.SuspendLayout(); + this.panel1.SuspendLayout(); + this.tableLayoutPanel2.SuspendLayout(); + this.SuspendLayout(); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel1.Controls.Add(this.listView1, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 0); + this.tableLayoutPanel1.Location = new System.Drawing.Point(2, 52); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 1; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(524, 270); + this.tableLayoutPanel1.TabIndex = 1; + // + // listView1 + // + this.listView1.Dock = System.Windows.Forms.DockStyle.Fill; + listViewGroup16.Header = "First Group"; + listViewGroup16.Name = null; + listViewGroup17.Header = "Second Group"; + listViewGroup17.Name = null; + listViewGroup18.Header = "Third Group"; + listViewGroup18.Name = null; + this.listView1.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] { + listViewGroup16, + listViewGroup17, + listViewGroup18}); + //this.listView1.IsBackgroundImageTiled = false; + listViewItem26.Group = listViewGroup16; + listViewItem27.Group = listViewGroup16; + listViewItem28.Group = listViewGroup17; + listViewItem29.Group = listViewGroup17; + listViewItem30.Group = listViewGroup18; + this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] { + listViewItem26, + listViewItem27, + listViewItem28, + listViewItem29, + listViewItem30}); + this.listView1.Location = new System.Drawing.Point(90, 3); + this.listView1.Name = "listView1"; + this.listView1.Size = new System.Drawing.Size(431, 264); + this.listView1.TabIndex = 1; + // + // panel1 + // + this.panel1.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.panel1.AutoSize = true; + this.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; + this.panel1.Controls.Add(this.button3); + this.panel1.Controls.Add(this.button2); + this.panel1.Controls.Add(this.button1); + this.panel1.Location = new System.Drawing.Point(3, 3); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(81, 86); + this.panel1.TabIndex = 2; + // + // button3 + // + this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button3.AutoSize = true; + this.button3.Location = new System.Drawing.Point(3, 60); + this.button3.Name = "button3"; + this.button3.TabIndex = 2; + this.button3.Text = "Add Text"; + this.button3.Click += new System.EventHandler(this.AddText); + // + // button2 + // + this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button2.AutoSize = true; + this.button2.Location = new System.Drawing.Point(3, 31); + this.button2.Name = "button2"; + this.button2.TabIndex = 1; + this.button2.Text = "Add Text"; + this.button2.Click += new System.EventHandler(this.AddText); + // + // button1 + // + this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button1.AutoSize = true; + this.button1.Location = new System.Drawing.Point(3, 2); + this.button1.Name = "button1"; + this.button1.TabIndex = 0; + this.button1.Text = "Add Text"; + this.button1.Click += new System.EventHandler(this.AddText); + // + // tableLayoutPanel2 + // + this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel2.AutoSize = true; + this.tableLayoutPanel2.ColumnCount = 3; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); + this.tableLayoutPanel2.Controls.Add(this.button4, 0, 0); + this.tableLayoutPanel2.Controls.Add(this.button5, 1, 0); + this.tableLayoutPanel2.Controls.Add(this.button6, 2, 0); + this.tableLayoutPanel2.Location = new System.Drawing.Point(284, 328); + this.tableLayoutPanel2.Name = "tableLayoutPanel2"; + this.tableLayoutPanel2.RowCount = 1; + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.tableLayoutPanel2.Size = new System.Drawing.Size(243, 34); + this.tableLayoutPanel2.TabIndex = 2; + // + // button4 + // + this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button4.AutoSize = true; + this.button4.Location = new System.Drawing.Point(3, 5); + this.button4.Name = "button4"; + this.button4.TabIndex = 0; + this.button4.Text = "Add Text"; + this.button4.Click += new System.EventHandler(this.AddText); + // + // button5 + // + this.button5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button5.AutoSize = true; + this.button5.Location = new System.Drawing.Point(84, 5); + this.button5.Name = "button5"; + this.button5.TabIndex = 1; + this.button5.Text = "Add Text"; + this.button5.Click += new System.EventHandler(this.AddText); + // + // button6 + // + this.button6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.button6.AutoSize = true; + this.button6.Location = new System.Drawing.Point(165, 5); + this.button6.Name = "button6"; + this.button6.TabIndex = 2; + this.button6.Text = "Add Text"; + this.button6.Click += new System.EventHandler(this.AddText); + // + // label1 + // + this.label1.Location = new System.Drawing.Point(8, 7); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(518, 40); + this.label1.TabIndex = 3; + this.label1.Text = "Click on any button to add text to the button. This simulates localizing strings," + + " and provides a good demonstration of how the dialog will automatically adjust w" + + "hen those longer strings are added to the UI."; + // + // LocalizableForm + // + this.ClientSize = new System.Drawing.Size(539, 374); + this.Controls.Add(this.label1); + this.Controls.Add(this.tableLayoutPanel2); + this.Controls.Add(this.tableLayoutPanel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Name = "LocalizableForm"; + this.Text = "Localizable Dialog"; + this.tableLayoutPanel1.ResumeLayout(false); + this.tableLayoutPanel1.PerformLayout(); + this.panel1.ResumeLayout(false); + this.panel1.PerformLayout(); + this.tableLayoutPanel2.ResumeLayout(false); + this.tableLayoutPanel2.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new LocalizableForm()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel/CS/form1.cs new file mode 100644 index 0000000000..ad6c601e86 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel/CS/form1.cs @@ -0,0 +1,800 @@ +// +using System; +using System.Collections; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.Layout; +using System.Diagnostics; + +public class Form1 : System.Windows.Forms.Form +{ + private System.Windows.Forms.TableLayoutPanel TableLayoutPanel1; + private System.Windows.Forms.Button Button1; + private System.Windows.Forms.Button Button2; + private System.Windows.Forms.Button Button3; + private System.Windows.Forms.Button Button4; + private System.Windows.Forms.Button enumerateChildrenBtn; + private System.Windows.Forms.Button testGrowStyleBtn; + private System.Windows.Forms.Button getColumnBtn; + private System.Windows.Forms.Button getcontrolFromPosBtn; + private System.Windows.Forms.Button getRowBtn; + private System.Windows.Forms.Button swapControlsBtn; + private System.Windows.Forms.RadioButton borderStyleNoneRadioBtn; + private System.Windows.Forms.RadioButton borderStyleOutsetRadioBtn; + private System.Windows.Forms.RadioButton borderStyleInsetRadioBtn; + private System.Windows.Forms.RadioButton growStyleNoneBtn; + private System.Windows.Forms.RadioButton growStyleAddRowBtn; + private System.Windows.Forms.RadioButton growStyleAddColumnBtn; + private System.Windows.Forms.Button toggleColumnStylesBtn; + private DemoTableLayoutPanel DemoTableLayoutPanel1; + private System.Windows.Forms.Button Button12; + private System.Windows.Forms.Button Button10; + private System.Windows.Forms.Button Button11; + private System.Windows.Forms.Button toggleRowStylesBtn; + private System.Windows.Forms.Button toggleSpanBtn; + private System.Windows.Forms.Button swapRowsBtn; + private System.Windows.Forms.Button toggleMarginsBtn; + private System.Windows.Forms.Button togglePaddingBtn; + + //Required by the Windows Form Designer + private System.ComponentModel.Container components; + + TableLayoutPanelGrowStyle tlpGrowStyle = TableLayoutPanelGrowStyle.AddRows; + + public Form1() + { + //This call is required by the Windows Form Designer. + InitializeComponent(); + } + + //Form overrides dispose to clean up the component list. + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + // + private void enumerateChildrenBtn_Click( + System.Object sender, + System.EventArgs e) + { + foreach ( Control c in this.TableLayoutPanel1.Controls ) + { + Trace.WriteLine(c.ToString()); + } + } + // + + // + private void getColumnBtn_Click( + System.Object sender, + System.EventArgs e) + { + foreach ( Control c in this.TableLayoutPanel1.Controls ) + { + Trace.WriteLine(this.TableLayoutPanel1.GetColumn(c)); + } + } + // + + // + private void getRowBtn_Click( + System.Object sender, + System.EventArgs e) + { + foreach ( Control c in this.TableLayoutPanel1.Controls ) + { + Trace.WriteLine(this.TableLayoutPanel1.GetRow(c)); + } + } + // + + // + private void getcontrolFromPosBtn_Click( + System.Object sender, + System.EventArgs e) + { + int i = 0; + int j = 0; + Trace.WriteLine(this.TableLayoutPanel1.ColumnCount); + Trace.WriteLine(this.TableLayoutPanel1.RowCount); + + for(i=0; i<=this.TableLayoutPanel1.ColumnCount; i++) + { + for(j=0; j<=this.TableLayoutPanel1.RowCount; j++) + { + Control c = this.TableLayoutPanel1.GetControlFromPosition(i, j); + + if( c != null ) + { + Trace.WriteLine(c.ToString()); + } + } + } + } + // + + // + private void swapControlsBtn_Click( + System.Object sender, + System.EventArgs e) + { + Control c1 = this.TableLayoutPanel1.GetControlFromPosition(0, 0); + Control c2 = this.TableLayoutPanel1.GetControlFromPosition(0, 1); + + if( c1 != null && c2 != null ) + { + this.TableLayoutPanel1.SetColumn(c2, 0); + this.TableLayoutPanel1.SetColumn(c1, 1); + } + } + // + + // + private void swapRowsBtn_Click( + System.Object sender, + System.EventArgs e) + { + + Control c1 = this.TableLayoutPanel1.GetControlFromPosition(0, 0); + Control c2 = this.TableLayoutPanel1.GetControlFromPosition(1, 0); + + if ( c1 !=null && c2 != null ) + { + this.TableLayoutPanel1.SetRow(c2, 0); + this.TableLayoutPanel1.SetRow(c1, 1); + } + } + // + + // + private void borderStyleOutsetRadioBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.TableLayoutPanel1.CellBorderStyle = + TableLayoutPanelCellBorderStyle.Outset; + } + + private void borderStyleNoneRadioBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.TableLayoutPanel1.CellBorderStyle = + TableLayoutPanelCellBorderStyle.None; + } + + private void borderStyleInsetRadioBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.TableLayoutPanel1.CellBorderStyle = + TableLayoutPanelCellBorderStyle.Inset; + } + // + + // + private void growStyleNoneBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.tlpGrowStyle = TableLayoutPanelGrowStyle.FixedSize; + } + + private void growStyleAddRowBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.tlpGrowStyle = TableLayoutPanelGrowStyle.AddRows; + } + + private void growStyleAddColumnBtn_CheckedChanged( + System.Object sender, + System.EventArgs e) + { + this.tlpGrowStyle = TableLayoutPanelGrowStyle.AddColumns; + } + + private void testGrowStyleBtn_Click( + System.Object sender, + System.EventArgs e) + { + this.TableLayoutPanel1.GrowStyle = this.tlpGrowStyle; + + try + { + this.TableLayoutPanel1.Controls.Add(new Button()); + } + catch(ArgumentException ex) + { + Trace.WriteLine(ex.Message); + } + } + // + + // + private void toggleColumnStylesBtn_Click( + System.Object sender, + System.EventArgs e) + { + TableLayoutColumnStyleCollection styles = + this.TableLayoutPanel1.ColumnStyles; + + foreach( ColumnStyle style in styles ) + { + if( style.SizeType == SizeType.Absolute ) + { + style.SizeType = SizeType.AutoSize; + } + else if( style.SizeType == SizeType.AutoSize ) + { + style.SizeType = SizeType.Percent; + + // Set the column width to be a percentage + // of the TableLayoutPanel control's width. + style.Width = 33; + } + else + { + // Set the column width to 50 pixels. + style.SizeType = SizeType.Absolute; + style.Width = 50; + } + } + } + // + + // + private void toggleRowStylesBtn_Click( + System.Object sender, + System.EventArgs e) + { + TableLayoutRowStyleCollection styles = + this.TableLayoutPanel1.RowStyles; + + foreach( RowStyle style in styles ) + { + if (style.SizeType==SizeType.Absolute) + { + style.SizeType = SizeType.AutoSize; + } + else if(style.SizeType==SizeType.AutoSize) + { + style.SizeType = SizeType.Percent; + + // Set the row height to be a percentage + // of the TableLayoutPanel control's height. + style.Height = 33; + } + else + { + + // Set the row height to 50 pixels. + style.SizeType = SizeType.Absolute; + style.Height = 50; + } + } + } + // + + // + private void TableLayoutPanel1_PaintCell( + object sender, + System.Windows.Forms.PaintEventArgs e) + { + Graphics g = e.Graphics; + + g.FillEllipse( + Brushes.ForestGreen, + new Rectangle( + e.ClipRectangle.X+2, + e.ClipRectangle.Y+2, + e.ClipRectangle.Width-4, + e.ClipRectangle.Height-4)); + + g.DrawRectangle(Pens.Red, new Rectangle(e.ClipRectangle.X+2, e.ClipRectangle.Y+2, e.ClipRectangle.Width-4, e.ClipRectangle.Height-4)); + } + // + + // + private void toggleSpanBtn_Click( + System.Object sender, + System.EventArgs e) + { + Control c = this.TableLayoutPanel1.GetControlFromPosition(0, 0); + + if ( c != null ) + { + int xSpan = this.TableLayoutPanel1.GetColumnSpan(c); + int ySpan = this.TableLayoutPanel1.GetRowSpan(c); + + if (xSpan>1) + { + xSpan = 1; + ySpan = 1; + } + else + { + xSpan = 2; + ySpan = 2; + } + + this.TableLayoutPanel1.SetColumnSpan(c, xSpan); + this.TableLayoutPanel1.SetRowSpan(c, ySpan); + } + } + // + + // + private void toggleMarginsBtn_Click( + System.Object sender, + System.EventArgs e) + { + foreach( Control c in this.TableLayoutPanel1.Controls ) + { + if (c.Margin.All>5) + { + Padding m = c.Margin; + m.All = 5; + c.Margin = m; + } + else + { + + Padding m = c.Margin; + m.All = 10; + c.Margin = m; + } + } + } + // + + // + private void togglePaddingBtn_Click( + System.Object sender, + System.EventArgs e) + { + if (this.TableLayoutPanel1.Padding.All>5) + { + Padding p = this.TableLayoutPanel1.Padding; + p.All = 5; + this.TableLayoutPanel1.Padding = p; + } + else + { + Padding p = this.TableLayoutPanel1.Padding; + p.All = 10; + this.TableLayoutPanel1.Padding = p; + } + } + // + + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.Run(new Form1()); + } + + #region Windows Form Designer generated code + + //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 void InitializeComponent() + { + this.TableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); + this.Button1 = new System.Windows.Forms.Button(); + this.Button2 = new System.Windows.Forms.Button(); + this.Button3 = new System.Windows.Forms.Button(); + this.Button4 = new System.Windows.Forms.Button(); + this.enumerateChildrenBtn = new System.Windows.Forms.Button(); + this.testGrowStyleBtn = new System.Windows.Forms.Button(); + this.getColumnBtn = new System.Windows.Forms.Button(); + this.getcontrolFromPosBtn = new System.Windows.Forms.Button(); + this.getRowBtn = new System.Windows.Forms.Button(); + this.swapControlsBtn = new System.Windows.Forms.Button(); + this.borderStyleNoneRadioBtn = new System.Windows.Forms.RadioButton(); + this.borderStyleOutsetRadioBtn = new System.Windows.Forms.RadioButton(); + this.borderStyleInsetRadioBtn = new System.Windows.Forms.RadioButton(); + this.growStyleNoneBtn = new System.Windows.Forms.RadioButton(); + this.growStyleAddRowBtn = new System.Windows.Forms.RadioButton(); + this.growStyleAddColumnBtn = new System.Windows.Forms.RadioButton(); + this.toggleColumnStylesBtn = new System.Windows.Forms.Button(); + this.DemoTableLayoutPanel1 = new DemoTableLayoutPanel(); + this.Button12 = new System.Windows.Forms.Button(); + this.Button10 = new System.Windows.Forms.Button(); + this.Button11 = new System.Windows.Forms.Button(); + this.toggleRowStylesBtn = new System.Windows.Forms.Button(); + this.toggleSpanBtn = new System.Windows.Forms.Button(); + this.swapRowsBtn = new System.Windows.Forms.Button(); + this.toggleMarginsBtn = new System.Windows.Forms.Button(); + this.togglePaddingBtn = new System.Windows.Forms.Button(); + this.TableLayoutPanel1.SuspendLayout(); + this.DemoTableLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); +// +// TableLayoutPanel1 +// + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); + this.TableLayoutPanel1.Controls.Add(this.Button1, 0, 0); + this.TableLayoutPanel1.Controls.Add(this.Button2, 1, 0); + this.TableLayoutPanel1.Controls.Add(this.Button3, 0, 0); + this.TableLayoutPanel1.Controls.Add(this.Button4, 0, 0); + this.TableLayoutPanel1.Location = new System.Drawing.Point(123, 24); + this.TableLayoutPanel1.Name = "TableLayoutPanel1"; + this.TableLayoutPanel1.RowCount = 4; + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.TableLayoutPanel1.Size = new System.Drawing.Size(286, 230); + this.TableLayoutPanel1.TabIndex = 0; +// +// Button1 +// + this.Button1.Anchor = System.Windows.Forms.AnchorStyles.None; + this.Button1.Location = new System.Drawing.Point(105, 68); + this.Button1.Name = "Button1"; + this.Button1.TabIndex = 1; + this.Button1.Text = "Button1"; +// +// Button2 +// + this.Button2.Anchor = System.Windows.Forms.AnchorStyles.None; + this.Button2.Location = new System.Drawing.Point(105, 150); + this.Button2.Name = "Button2"; + this.Button2.TabIndex = 2; + this.Button2.Text = "Button2"; +// +// Button3 +// + this.Button3.Anchor = System.Windows.Forms.AnchorStyles.None; + this.Button3.Location = new System.Drawing.Point(105, 3); + this.Button3.Name = "Button3"; + this.Button3.TabIndex = 3; + this.Button3.Text = "Button3"; +// +// Button4 +// + this.Button4.Anchor = System.Windows.Forms.AnchorStyles.None; + this.TableLayoutPanel1.SetColumnSpan(this.Button4, 3); + this.Button4.Location = new System.Drawing.Point(26, 32); + this.Button4.Name = "Button4"; + this.Button4.Size = new System.Drawing.Size(234, 30); + this.Button4.TabIndex = 4; + this.Button4.Text = "Button4"; +// +// enumerateChildrenBtn +// + this.enumerateChildrenBtn.AutoSize = true; + this.enumerateChildrenBtn.Location = new System.Drawing.Point(629, 274); + this.enumerateChildrenBtn.Name = "enumerateChildrenBtn"; + this.enumerateChildrenBtn.Size = new System.Drawing.Size(105, 23); + this.enumerateChildrenBtn.TabIndex = 1; + this.enumerateChildrenBtn.Text = "Enumerate Children"; + this.enumerateChildrenBtn.Click += new System.EventHandler(this.enumerateChildrenBtn_Click); +// +// testGrowStyleBtn +// + this.testGrowStyleBtn.AutoSize = true; + this.testGrowStyleBtn.Location = new System.Drawing.Point(67, 274); + this.testGrowStyleBtn.Name = "testGrowStyleBtn"; + this.testGrowStyleBtn.Size = new System.Drawing.Size(88, 23); + this.testGrowStyleBtn.TabIndex = 2; + this.testGrowStyleBtn.Text = "Test GrowStyle"; + this.testGrowStyleBtn.Click += new System.EventHandler(this.testGrowStyleBtn_Click); +// +// getColumnBtn +// + this.getColumnBtn.Location = new System.Drawing.Point(165, 274); + this.getColumnBtn.Name = "getColumnBtn"; + this.getColumnBtn.TabIndex = 3; + this.getColumnBtn.Text = "GetColumn"; + this.getColumnBtn.Click += new System.EventHandler(this.getColumnBtn_Click); +// +// getcontrolFromPosBtn +// + this.getcontrolFromPosBtn.AutoSize = true; + this.getcontrolFromPosBtn.Location = new System.Drawing.Point(329, 274); + this.getcontrolFromPosBtn.Name = "getcontrolFromPosBtn"; + this.getcontrolFromPosBtn.Size = new System.Drawing.Size(123, 23); + this.getcontrolFromPosBtn.TabIndex = 4; + this.getcontrolFromPosBtn.Text = "GetControlFromPosition"; + this.getcontrolFromPosBtn.Click += new System.EventHandler(this.getcontrolFromPosBtn_Click); +// +// getRowBtn +// + this.getRowBtn.Location = new System.Drawing.Point(247, 274); + this.getRowBtn.Name = "getRowBtn"; + this.getRowBtn.TabIndex = 5; + this.getRowBtn.Text = "GetRow"; + this.getRowBtn.Click += new System.EventHandler(this.getRowBtn_Click); +// +// swapControlsBtn +// + this.swapControlsBtn.AutoSize = true; + this.swapControlsBtn.Location = new System.Drawing.Point(459, 274); + this.swapControlsBtn.Name = "swapControlsBtn"; + this.swapControlsBtn.Size = new System.Drawing.Size(81, 23); + this.swapControlsBtn.TabIndex = 6; + this.swapControlsBtn.Text = "Swap Controls"; + this.swapControlsBtn.Click += new System.EventHandler(this.swapControlsBtn_Click); +// +// borderStyleNoneRadioBtn +// + this.borderStyleNoneRadioBtn.Location = new System.Drawing.Point(35, 26); + this.borderStyleNoneRadioBtn.Name = "borderStyleNoneRadioBtn"; + this.borderStyleNoneRadioBtn.Size = new System.Drawing.Size(52, 30); + this.borderStyleNoneRadioBtn.TabIndex = 8; + this.borderStyleNoneRadioBtn.Text = "None"; + this.borderStyleNoneRadioBtn.Click += new System.EventHandler(this.borderStyleNoneRadioBtn_CheckedChanged); +// +// borderStyleOutsetRadioBtn +// + this.borderStyleOutsetRadioBtn.AutoSize = true; + this.borderStyleOutsetRadioBtn.Location = new System.Drawing.Point(35, 62); + this.borderStyleOutsetRadioBtn.Name = "borderStyleOutsetRadioBtn"; + this.borderStyleOutsetRadioBtn.Size = new System.Drawing.Size(52, 25); + this.borderStyleOutsetRadioBtn.TabIndex = 9; + this.borderStyleOutsetRadioBtn.Text = "Outset"; + this.borderStyleOutsetRadioBtn.Click += new System.EventHandler(this.borderStyleOutsetRadioBtn_CheckedChanged); +// +// borderStyleInsetRadioBtn +// + this.borderStyleInsetRadioBtn.Location = new System.Drawing.Point(35, 92); + this.borderStyleInsetRadioBtn.Name = "borderStyleInsetRadioBtn"; + this.borderStyleInsetRadioBtn.Size = new System.Drawing.Size(52, 25); + this.borderStyleInsetRadioBtn.TabIndex = 10; + this.borderStyleInsetRadioBtn.Text = "Inset"; + this.borderStyleInsetRadioBtn.Click += new System.EventHandler(this.borderStyleInsetRadioBtn_CheckedChanged); +// +// growStyleNoneBtn +// + this.growStyleNoneBtn.AutoSize = true; + this.growStyleNoneBtn.Location = new System.Drawing.Point(67, 304); + this.growStyleNoneBtn.Name = "growStyleNoneBtn"; + this.growStyleNoneBtn.TabIndex = 13; + this.growStyleNoneBtn.Text = "Fixed"; + this.growStyleNoneBtn.Click += new System.EventHandler(this.growStyleNoneBtn_CheckedChanged); +// +// growStyleAddRowBtn +// + this.growStyleAddRowBtn.AutoSize = true; + this.growStyleAddRowBtn.Location = new System.Drawing.Point(67, 335); + this.growStyleAddRowBtn.Name = "growStyleAddRowBtn"; + this.growStyleAddRowBtn.TabIndex = 14; + this.growStyleAddRowBtn.Text = "Add Rows"; + this.growStyleAddRowBtn.Click += new System.EventHandler(this.growStyleAddRowBtn_CheckedChanged); +// +// growStyleAddColumnBtn +// + this.growStyleAddColumnBtn.AutoSize = true; + this.growStyleAddColumnBtn.Location = new System.Drawing.Point(67, 366); + this.growStyleAddColumnBtn.Name = "growStyleAddColumnBtn"; + this.growStyleAddColumnBtn.TabIndex = 15; + this.growStyleAddColumnBtn.Text = "Add Columns"; + this.growStyleAddColumnBtn.Click += new System.EventHandler(this.growStyleAddColumnBtn_CheckedChanged); +// +// toggleColumnStylesBtn +// + this.toggleColumnStylesBtn.Location = new System.Drawing.Point(69, 397); + this.toggleColumnStylesBtn.Name = "toggleColumnStylesBtn"; + this.toggleColumnStylesBtn.Size = new System.Drawing.Size(118, 24); + this.toggleColumnStylesBtn.TabIndex = 16; + this.toggleColumnStylesBtn.Text = "Toggle ColumnStyles"; + this.toggleColumnStylesBtn.Click += new System.EventHandler(this.toggleColumnStylesBtn_Click); +// +// DemoTableLayoutPanel1 +// + this.DemoTableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.DemoTableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.DemoTableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.DemoTableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F)); + this.DemoTableLayoutPanel1.Controls.Add(this.Button12); + this.DemoTableLayoutPanel1.Controls.Add(this.Button10, 0, 1); + this.DemoTableLayoutPanel1.Controls.Add(this.Button11, 1, 1); + this.DemoTableLayoutPanel1.Location = new System.Drawing.Point(446, 24); + this.DemoTableLayoutPanel1.Name = "DemoTableLayoutPanel1"; + this.DemoTableLayoutPanel1.RowCount = 2; + this.DemoTableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F)); + this.DemoTableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F)); + this.DemoTableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F)); + this.DemoTableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F)); + this.DemoTableLayoutPanel1.Size = new System.Drawing.Size(256, 230); + this.DemoTableLayoutPanel1.TabIndex = 11; +// +// Button12 +// + this.Button12.Anchor = System.Windows.Forms.AnchorStyles.None; + this.Button12.Location = new System.Drawing.Point(90, 13); + this.Button12.Name = "Button12"; + this.Button12.TabIndex = 9; + this.Button12.Text = "Button12"; +// +// Button10 +// + this.Button10.Anchor = System.Windows.Forms.AnchorStyles.None; + this.Button10.Location = new System.Drawing.Point(90, 63); + this.Button10.Name = "Button10"; + this.Button10.TabIndex = 12; + this.Button10.Text = "Button10"; +// +// Button11 +// + this.Button11.Anchor = System.Windows.Forms.AnchorStyles.None; + this.Button11.Location = new System.Drawing.Point(90, 153); + this.Button11.Name = "Button11"; + this.Button11.TabIndex = 8; + this.Button11.Text = "Button11"; +// +// toggleRowStylesBtn +// + this.toggleRowStylesBtn.Location = new System.Drawing.Point(67, 440); + this.toggleRowStylesBtn.Name = "toggleRowStylesBtn"; + this.toggleRowStylesBtn.Size = new System.Drawing.Size(120, 22); + this.toggleRowStylesBtn.TabIndex = 17; + this.toggleRowStylesBtn.Text = "Toggle RowStyles"; + this.toggleRowStylesBtn.Click += new System.EventHandler(this.toggleRowStylesBtn_Click); +// +// toggleSpanBtn +// + this.toggleSpanBtn.Location = new System.Drawing.Point(247, 398); + this.toggleSpanBtn.Name = "toggleSpanBtn"; + this.toggleSpanBtn.TabIndex = 18; + this.toggleSpanBtn.Text = "Toggle Span"; + this.toggleSpanBtn.Click += new System.EventHandler(this.toggleSpanBtn_Click); +// +// swapRowsBtn +// + this.swapRowsBtn.Location = new System.Drawing.Point(458, 305); + this.swapRowsBtn.Name = "swapRowsBtn"; + this.swapRowsBtn.Size = new System.Drawing.Size(82, 23); + this.swapRowsBtn.TabIndex = 19; + this.swapRowsBtn.Text = "Swap Rows"; + this.swapRowsBtn.Click += new System.EventHandler(this.swapRowsBtn_Click); +// +// toggleMarginsBtn +// + this.toggleMarginsBtn.Location = new System.Drawing.Point(328, 397); + this.toggleMarginsBtn.Name = "toggleMarginsBtn"; + this.toggleMarginsBtn.Size = new System.Drawing.Size(93, 24); + this.toggleMarginsBtn.TabIndex = 20; + this.toggleMarginsBtn.Text = "Toggle Margins"; + this.toggleMarginsBtn.Click += new System.EventHandler(this.toggleMarginsBtn_Click); +// +// togglePaddingBtn +// + this.togglePaddingBtn.Location = new System.Drawing.Point(458, 396); + this.togglePaddingBtn.Name = "togglePaddingBtn"; + this.togglePaddingBtn.Size = new System.Drawing.Size(94, 23); + this.togglePaddingBtn.TabIndex = 21; + this.togglePaddingBtn.Text = "Toggle Padding"; + this.togglePaddingBtn.Click += new System.EventHandler(this.togglePaddingBtn_Click); +// +// Form1 +// + this.ClientSize = new System.Drawing.Size(773, 489); + this.Controls.Add(this.togglePaddingBtn); + this.Controls.Add(this.toggleMarginsBtn); + this.Controls.Add(this.swapRowsBtn); + this.Controls.Add(this.toggleSpanBtn); + this.Controls.Add(this.toggleRowStylesBtn); + this.Controls.Add(this.toggleColumnStylesBtn); + this.Controls.Add(this.growStyleAddColumnBtn); + this.Controls.Add(this.growStyleAddRowBtn); + this.Controls.Add(this.growStyleNoneBtn); + this.Controls.Add(this.DemoTableLayoutPanel1); + this.Controls.Add(this.borderStyleInsetRadioBtn); + this.Controls.Add(this.borderStyleOutsetRadioBtn); + this.Controls.Add(this.borderStyleNoneRadioBtn); + this.Controls.Add(this.swapControlsBtn); + this.Controls.Add(this.getRowBtn); + this.Controls.Add(this.getcontrolFromPosBtn); + this.Controls.Add(this.getColumnBtn); + this.Controls.Add(this.testGrowStyleBtn); + this.Controls.Add(this.enumerateChildrenBtn); + this.Controls.Add(this.TableLayoutPanel1); + this.Name = "Form1"; + this.Text = "Form1"; + this.TableLayoutPanel1.ResumeLayout(false); + this.DemoTableLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + +} + +// +public class DemoTableLayoutPanel : TableLayoutPanel +{ + protected override void OnCellPaint(TableLayoutCellPaintEventArgs e) + { + base.OnCellPaint(e); + + Control c = this.GetControlFromPosition(e.Column, e.Row); + + if ( c != null ) + { + Graphics g = e.Graphics; + + g.DrawRectangle( + Pens.Red, + e.CellBounds.Location.X+1, + e.CellBounds.Location.Y + 1, + e.CellBounds.Width - 2, e.CellBounds.Height - 2); + + g.FillRectangle( + Brushes.Blue, + e.CellBounds.Location.X + 1, + e.CellBounds.Location.Y + 1, + e.CellBounds.Width - 2, + e.CellBounds.Height - 2); + }; + } +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/CS/Form1.cs new file mode 100644 index 0000000000..6fbbb84ddc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/CS/Form1.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace TextRendering +{ + public class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + // + private void MeasureText1(PaintEventArgs e) + { + String text1 = "Measure this text"; + Font arialBold = new Font("Arial", 12.0F); + Size textSize = TextRenderer.MeasureText(text1, arialBold); + TextRenderer.DrawText(e.Graphics, text1, arialBold, + new Rectangle(new Point(10, 10), textSize), Color.Red); + } + // + // + private void MeasureText2(PaintEventArgs e) + { + String text1 = "How big is this text?"; + Font arialBold = new Font("Arial", 12.0F); + + // Indicate a size taller than it is wide. + Size proposedSize = new Size(40, 60); + + Size textSize = TextRenderer.MeasureText(text1, arialBold, proposedSize, TextFormatFlags.WordBreak); + TextRenderer.DrawText(e.Graphics, text1, arialBold, + new Rectangle(new Point(10, 10), textSize), Color.Red, TextFormatFlags.WordBreak); + } + // + // + private void RenderText1(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, "Regular Text", this.Font, + new Point(10, 10), SystemColors.ControlText); + } + // + // + private void RenderText2(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, "Regular Text", this.Font, + new Rectangle(10, 10, 100, 100), SystemColors.ControlText); + } + // + // + private void RenderText3(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, "Regular Text", this.Font, + new Point(10, 10), Color.Red, Color.PowderBlue); + } + // + // + private void RenderText4(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, "Regular Text.", this.Font, + new Rectangle(10, 10, 70, 70), SystemColors.ControlText, + SystemColors.ControlDark); + } + // + // + private void RenderText5(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, "Some text.", + this.Font, new Point(10, 10), SystemColors.ControlText, TextFormatFlags.Bottom); + } + // + // + private void RenderText6(PaintEventArgs e) + { + TextFormatFlags flags = TextFormatFlags.Bottom | TextFormatFlags.EndEllipsis; + TextRenderer.DrawText(e.Graphics, "This is some text that will be clipped at the end.", this.Font, + new Rectangle(10, 10, 100, 50), SystemColors.ControlText, flags); + } + // + // + private void RenderText7(PaintEventArgs e) + { + TextRenderer.DrawText(e.Graphics, "This is some text.", this.Font, + new Point(10, 10), Color.White, Color.SteelBlue, TextFormatFlags.Default); + } + // + // + private void RenderText8(PaintEventArgs e) + { + TextFormatFlags flags = TextFormatFlags.Bottom | TextFormatFlags.WordBreak; + TextRenderer.DrawText(e.Graphics, "This is some text that will display on multiple lines.", this.Font, + new Rectangle(10, 10, 100, 50), SystemColors.ControlText, SystemColors.ControlDark, flags); + } + + // + + // + private static void DrawALineOfText(PaintEventArgs e) + { + // Declare strings to render on the form. + string[] stringsToPaint = { "Tail", "Spin", " Toys" }; + + // Declare fonts for rendering the strings. + Font[] fonts = { new Font("Arial", 14, FontStyle.Regular), + new Font("Arial", 14, FontStyle.Italic), + new Font("Arial", 14, FontStyle.Regular) }; + + Point startPoint = new Point(10, 10); + + // Set TextFormatFlags to no padding so strings are drawn together. + TextFormatFlags flags = TextFormatFlags.NoPadding; + + // Declare a proposed size with dimensions set to the maximum integer value. + Size proposedSize = new Size(int.MaxValue, int.MaxValue); + + // Measure each string with its font and NoPadding value and + // draw it to the form. + for (int i = 0; i < stringsToPaint.Length; i++) + { + Size size = TextRenderer.MeasureText(e.Graphics, stringsToPaint[i], + fonts[i], proposedSize, flags); + Rectangle rect = new Rectangle(startPoint, size); + TextRenderer.DrawText(e.Graphics, stringsToPaint[i], fonts[i], + startPoint, Color.Black, flags); + startPoint.X += size.Width; + } + } + // + + private void InitializeComponent() + { + this.SuspendLayout(); + // + // Form1 + // + this.ClientSize = new System.Drawing.Size(292, 273); + this.Name = "Form1"; + this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); + this.ResumeLayout(false); + } + + private void Form1_Paint(object sender, PaintEventArgs e) + { + MeasureText2(e); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/CS/GridStrip.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/CS/GridStrip.cs new file mode 100644 index 0000000000..e4ca210198 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/CS/GridStrip.cs @@ -0,0 +1,557 @@ +// +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Text; +using System.Windows.Forms; +using System.Windows.Forms.Layout; + +namespace GridStripLib +{ + // + // The following class implements a sliding-tile puzzle. + // The GridStrip control is a custom ToolStrip that arranges + // its ToolStripButton controls in a grid layout. There is + // one empty cell, into which the user can slide an adjacent + // tile with a drag-and-drop operation. Tiles that are eligible + // for moving are highlighted. + public class GridStrip : ToolStrip + { + // The button that is the drag source. + private ToolStripButton dragButton = null; + + // Settings for the ToolStrip control's TableLayoutPanel. + // This provides access to the cell position of each + // ToolStripButton. + private TableLayoutSettings tableSettings = null; + + // The empty cell. ToolStripButton controls that are + // adjacent to this button can be moved to this button's + // cell position. + private ToolStripButton emptyCellButton = null; + + // The dimensions of each tile. A tile is represented + // by a ToolStripButton controls. + private Size tileSize = new Size(128, 128); + + // The number of rows in the GridStrip control. + private readonly int rows = 5; + + // The number of columns in the GridStrip control. + private readonly int columns = 5; + + // The one-time initialzation behavior is enforced + // with this field. For more information, see the + // OnPaint method. + private bool firstTime = false; + + // This is a required by the Windows Forms designer. + private System.ComponentModel.IContainer components; + + // The default constructor. + public GridStrip() + { + this.InitializeComponent(); + + this.InitializeTableLayoutSettings(); + } + + // This property exposes the empty cell to the + // GridStripRenderer class. + internal ToolStripButton EmptyCell + { + get + { + return this.emptyCellButton; + } + } + + // This utility method initializes the TableLayoutPanel + // which contains the ToolStripButton controls. + private void InitializeTableLayoutSettings() + { + // Specify the numbers of rows and columns in the GridStrip control. + this.tableSettings = base.LayoutSettings as TableLayoutSettings; + this.tableSettings.ColumnCount = this.rows; + this.tableSettings.RowCount = this.columns; + + // Create a dummy bitmap with the dimensions of each tile. + // The GridStrip control sizes itself based on these dimensions. + Bitmap b = new Bitmap(tileSize.Width, tileSize.Height); + + // Populate the GridStrip control with ToolStripButton controls. + for (int i = 0; i < this.tableSettings.ColumnCount; i++) + { + for (int j = 0; j < this.tableSettings.RowCount; j++) + { + // Create a new ToolStripButton control. + ToolStripButton btn = new ToolStripButton(); + btn.DisplayStyle = ToolStripItemDisplayStyle.Image; + btn.Image = b; + btn.ImageAlign = ContentAlignment.MiddleCenter; + btn.ImageScaling = ToolStripItemImageScaling.None; + btn.Margin = Padding.Empty; + btn.Padding = Padding.Empty; + + // Add the new ToolStripButton control to the GridStrip. + this.Items.Add(btn); + + // Set the cell position of the ToolStripButton control. + TableLayoutPanelCellPosition cellPos = new TableLayoutPanelCellPosition(i, j); + this.tableSettings.SetCellPosition(btn, cellPos); + + // If this is the ToolStripButton control at cell (0,0), + // assign it as the empty cell button. + if( i == 0 && j == 0 ) + { + btn.Text = "Empty Cell"; + btn.Image = b; + this.emptyCellButton = btn; + } + } + } + } + + // This method defines the Paint event behavior. + // The GridStripRenderer requires that the GridStrip + // be fully layed out when it is renders, so this + // initialization code cannot be placed in the + // GridStrip constructor. By the time the Paint + // event is raised, the control layout has been + // completed, so the GridStripRenderer can paint + // correctly. This one-time initialization is + // implemented with the firstTime field. + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + + if (!this.firstTime) + { + this.Renderer = new GridStripRenderer(); + + // Comment this line to see the unscrambled image. + this.ScrambleButtons(); + this.firstTime = true; + } + } + + // This utility method changes the ToolStripButton control + // positions in the TableLayoutPanel. This scrambles the + // buttons to initialize the puzzle. + private void ScrambleButtons() + { + int i = 0; + int lastElement = this.Items.Count - 1; + + while ( (i != lastElement ) && + (lastElement - i > 1) ) + { + TableLayoutPanelCellPosition pos1 = + this.tableSettings.GetCellPosition(this.Items[i]); + + TableLayoutPanelCellPosition pos2 = + this.tableSettings.GetCellPosition(this.Items[lastElement]); + + this.tableSettings.SetCellPosition( + this.Items[i++], + pos2); + + this.tableSettings.SetCellPosition( + this.Items[lastElement--], + pos1); + } + } + + // This method defines the MouseDown event behavior. + // If the user has clicked on a valid drag source, + // the drag operation starts. + protected override void OnMouseDown(MouseEventArgs mea) + { + base.OnMouseDown(mea); + + ToolStripButton btn = this.GetItemAt(mea.Location) as ToolStripButton; + + if (btn != null) + { + if (this.IsValidDragSource(btn)) + { + this.dragButton = btn; + } + } + } + + // This method defines the MouseMove event behavior. + protected override void OnMouseMove(MouseEventArgs mea) + { + base.OnMouseMove(mea); + + // Is a drag operation pending? + if (this.dragButton != null) + { + // A drag operation is pending. Call DoDragDrop to + // determine the disposition of the operation. + DragDropEffects dropEffect = this.DoDragDrop( + new DataObject(this.dragButton), + DragDropEffects.Move); + } + } + + // + // This method defines the DragOver event behavior. + protected override void OnDragOver(DragEventArgs dea) + { + base.OnDragOver(dea); + + // Get the ToolStripButton control + // at the given mouse position. + Point p = new Point(dea.X, dea.Y); + ToolStripButton item = this.GetItemAt( + this.PointToClient(p)) as ToolStripButton; + + // If the ToolStripButton control is the empty cell, + // indicate that the move operation is valid. + if( item == this.emptyCellButton ) + { + // Set the drag operation to indicate a valid move. + dea.Effect = DragDropEffects.Move; + } + } + // + + // This method defines the DragDrop event behavior. + protected override void OnDragDrop(DragEventArgs dea) + { + base.OnDragDrop(dea); + + // Did a valid move operation occur? + if (dea.Effect == DragDropEffects.Move) + { + // The move operation is valid. Adjust the state + // of the GridStrip control's TableLayoutPanel, + // by swapping the positions of the source button + // and the empty cell button. + + // Get the cell of the control to move. + TableLayoutPanelCellPosition sourcePos = + tableSettings.GetCellPosition(this.dragButton); + + // Get the cell of the emptyCellButton. + TableLayoutPanelCellPosition dropPos = + tableSettings.GetCellPosition(this.emptyCellButton); + + // Move the control to the empty cell. + tableSettings.SetCellPosition(this.dragButton, dropPos); + + // Set the position of the empty cell to + // that of the previously occupied cell. + tableSettings.SetCellPosition(this.emptyCellButton, sourcePos); + + // Reset the drag operation. + this.dragButton = null; + } + } + + // This method defines the DragLeave event behavior. + // If the mouse leaves the client area of the GridStrip + // control, the drag operation is canceled. + protected override void OnDragLeave(EventArgs e) + { + base.OnDragLeave(e); + + // Reset the drag operation. + this.dragButton = null; + } + + // This method defines the ueryContinueDrag event behavior. + // If the mouse leaves the client area of the GridStrip + // control, the drag operation is canceled. + protected override void OnQueryContinueDrag(QueryContinueDragEventArgs qcdevent) + { + base.OnQueryContinueDrag(qcdevent); + + // Get the current mouse position, in screen coordinates. + Point mousePos = this.PointToClient(Control.MousePosition); + + // If the mouse position is outside the GridStrip control's + // client area, cancel the drag operation. Be sure to + // transform the mouse's screen coordinates to client coordinates. + if (!this.ClientRectangle.Contains(mousePos)) + { + qcdevent.Action = DragAction.Cancel; + } + } + + // This utility method determines if a button + // is positioned relative to the empty cell + // such that it can be dragged into the empty cell. + private bool IsValidDragSource(ToolStripButton b) + { + TableLayoutPanelCellPosition sourcePos = + tableSettings.GetCellPosition(b); + + TableLayoutPanelCellPosition emptyPos = + tableSettings.GetCellPosition(this.emptyCellButton); + + return (IsValidDragSource(sourcePos, emptyPos)); + } + + // This utility method determines if a cell position + // is adjacent to the empty cell. + internal static bool IsValidDragSource( + TableLayoutPanelCellPosition sourcePos, + TableLayoutPanelCellPosition emptyPos) + { + bool returnValue = false; + + // A cell is considered to be a valid drag source if it + // is adjacent to the empty cell. Cells that are positioned + // on a diagonal are not valid. + if (((sourcePos.Column == emptyPos.Column - 1) && (sourcePos.Row == emptyPos.Row)) || + ((sourcePos.Column == emptyPos.Column + 1) && (sourcePos.Row == emptyPos.Row)) || + ((sourcePos.Column == emptyPos.Column) && (sourcePos.Row == emptyPos.Row - 1)) || + ((sourcePos.Column == emptyPos.Column) && (sourcePos.Row == emptyPos.Row + 1))) + { + returnValue = true; + } + + return returnValue; + } + // + + // + // This class implements a custom ToolStripRenderer for the + // GridStrip control. It customizes three aspects of the + // GridStrip control's appearance: GridStrip border, + // ToolStripButton border, and ToolStripButton image. + internal class GridStripRenderer : ToolStripRenderer + { + // The style of the empty cell's text. + private static StringFormat style = new StringFormat(); + + // The thickness (width or height) of a + // ToolStripButton control's border. + static int borderThickness = 2; + + // The main bitmap that is the source for the + // subimagesthat are assigned to individual + // ToolStripButton controls. + private Bitmap bmp = null; + + // The brush that paints the background of + // the GridStrip control. + private Brush backgroundBrush = null; + + // This is the static constructor. It initializes the + // StringFormat for drawing the text in the empty cell. + static GridStripRenderer() + { + style.Alignment = StringAlignment.Center; + style.LineAlignment = StringAlignment.Center; + } + + // This method initializes the GridStripRenderer by + // creating the image that is used as the source for + // the individual button images. + protected override void Initialize(ToolStrip ts) + { + base.Initialize(ts); + + this.InitializeBitmap(ts); + } + + // + // This method initializes an individual ToolStripButton + // control. It copies a subimage from the GridStripRenderer's + // main image, according to the position and size of + // the ToolStripButton. + protected override void InitializeItem(ToolStripItem item) + { + base.InitializeItem(item); + + GridStrip gs = item.Owner as GridStrip; + + // The empty cell does not receive a subimage. + if ((item is ToolStripButton) && + (item != gs.EmptyCell)) + { + // Copy the subimage from the appropriate + // part of the main image. + Bitmap subImage = bmp.Clone( + item.Bounds, + PixelFormat.Undefined); + + // Assign the subimage to the ToolStripButton + // control's Image property. + item.Image = subImage; + } + } + // + + // This utility method creates the main image that + // is the source for the subimages of the individual + // ToolStripButton controls. + private void InitializeBitmap(ToolStrip toolStrip) + { + // Create the main bitmap, into which the image is drawn. + this.bmp = new Bitmap( + toolStrip.Size.Width, + toolStrip.Size.Height); + + // Draw a fancy pattern. This could be any image or drawing. + using (Graphics g = Graphics.FromImage(bmp)) + { + // Draw smoothed lines. + g.SmoothingMode = SmoothingMode.AntiAlias; + + // Draw the image. In this case, it is + // a number of concentric ellipses. + for (int i = 0; i < toolStrip.Size.Width; i += 8) + { + g.DrawEllipse(Pens.Blue, 0, 0, i, i); + } + } + } + + // + // This method draws a border around the GridStrip control. + protected override void OnRenderToolStripBorder( + ToolStripRenderEventArgs e) + { + base.OnRenderToolStripBorder(e); + + ControlPaint.DrawFocusRectangle( + e.Graphics, + e.AffectedBounds, + SystemColors.ControlDarkDark, + SystemColors.ControlDarkDark); + } + // + + // + // This method renders the GridStrip control's background. + protected override void OnRenderToolStripBackground( + ToolStripRenderEventArgs e) + { + base.OnRenderToolStripBackground(e); + + // This late initialization is a workaround. The gradient + // depends on the bounds of the GridStrip control. The bounds + // are dependent on the layout engine, which hasn't fully + // performed layout by the time the Initialize method runs. + if (this.backgroundBrush == null) + { + this.backgroundBrush = new LinearGradientBrush( + e.ToolStrip.ClientRectangle, + SystemColors.ControlLightLight, + SystemColors.ControlDark, + 90, + true); + } + + // Paint the GridStrip control's background. + e.Graphics.FillRectangle( + this.backgroundBrush, + e.AffectedBounds); + } + // + + // + // This method draws a border around the button's image. If the background + // to be rendered belongs to the empty cell, a string is drawn. Otherwise, + // a border is drawn at the edges of the button. + protected override void OnRenderButtonBackground( + ToolStripItemRenderEventArgs e) + { + base.OnRenderButtonBackground(e); + + // Define some local variables for convenience. + Graphics g = e.Graphics; + GridStrip gs = e.ToolStrip as GridStrip; + ToolStripButton gsb = e.Item as ToolStripButton; + + // Calculate the rectangle around which the border is painted. + Rectangle imageRectangle = new Rectangle( + borderThickness, + borderThickness, + e.Item.Width - 2 * borderThickness, + e.Item.Height - 2 * borderThickness); + + // If rendering the empty cell background, draw an + // explanatory string, centered in the ToolStripButton. + if (gsb == gs.EmptyCell) + { + e.Graphics.DrawString( + "Drag to here", + gsb.Font, + SystemBrushes.ControlDarkDark, + imageRectangle, style); + } + else + { + // If the button can be a drag source, paint its border red. + // otherwise, paint its border a dark color. + Brush b = gs.IsValidDragSource(gsb) ? b = + Brushes.Red : SystemBrushes.ControlDarkDark; + + // Draw the top segment of the border. + Rectangle borderSegment = new Rectangle( + 0, + 0, + e.Item.Width, + imageRectangle.Top); + g.FillRectangle(b, borderSegment); + + // Draw the right segment. + borderSegment = new Rectangle( + imageRectangle.Right, + 0, + e.Item.Bounds.Right - imageRectangle.Right, + imageRectangle.Bottom); + g.FillRectangle(b, borderSegment); + + // Draw the left segment. + borderSegment = new Rectangle( + 0, + 0, + imageRectangle.Left, + e.Item.Height); + g.FillRectangle(b, borderSegment); + + // Draw the bottom segment. + borderSegment = new Rectangle( + 0, + imageRectangle.Bottom, + e.Item.Width, + e.Item.Bounds.Bottom - imageRectangle.Bottom); + g.FillRectangle(b, borderSegment); + } + } + // + } + // + + #region Windows Forms Designer generated code + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.SuspendLayout(); + // + // GridStrip + // + this.AllowDrop = true; + this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; + this.CanOverflow = false; + this.Dock = System.Windows.Forms.DockStyle.None; + this.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + this.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Table; + this.ResumeLayout(false); + } + + #endregion + + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/CS/Form1.cs new file mode 100644 index 0000000000..ee07bc4ba6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/CS/Form1.cs @@ -0,0 +1,281 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace MdiFormCS +{ + // This code example demonstrates an MDI form + // that supports menu merging and moveable + // ToolStrip controls + public class Form1 : Form + { + private MenuStrip menuStrip1; + private ToolStripMenuItem toolStripMenuItem1; + private ToolStripMenuItem newToolStripMenuItem; + private ToolStripPanel toolStripPanel1; + private ToolStrip toolStrip1; + private ToolStripPanel toolStripPanel2; + private ToolStrip toolStrip2; + private ToolStripPanel toolStripPanel3; + private ToolStrip toolStrip3; + private ToolStripPanel toolStripPanel4; + private ToolStrip toolStrip4; + + private System.ComponentModel.IContainer components = null; + + public Form1() + { + InitializeComponent(); + } + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + // + // This method creates a new ChildForm instance + // and attaches it to the MDI parent form. + private void newToolStripMenuItem_Click(object sender, EventArgs e) + { + ChildForm f = new ChildForm(); + f.MdiParent = this; + f.Text = "Form - " + this.MdiChildren.Length.ToString(); + f.Show(); + } + // + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripPanel1 = new System.Windows.Forms.ToolStripPanel(); + this.toolStrip1 = new System.Windows.Forms.ToolStrip(); + this.toolStripPanel2 = new System.Windows.Forms.ToolStripPanel(); + this.toolStrip2 = new System.Windows.Forms.ToolStrip(); + this.toolStripPanel3 = new System.Windows.Forms.ToolStripPanel(); + this.toolStrip3 = new System.Windows.Forms.ToolStrip(); + this.toolStripPanel4 = new System.Windows.Forms.ToolStripPanel(); + this.toolStrip4 = new System.Windows.Forms.ToolStrip(); + this.menuStrip1.SuspendLayout(); + this.toolStripPanel1.SuspendLayout(); + this.toolStripPanel2.SuspendLayout(); + this.toolStripPanel3.SuspendLayout(); + this.toolStripPanel4.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem1}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.MdiWindowListItem = this.toolStripMenuItem1; + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(292, 24); + this.menuStrip1.TabIndex = 0; + this.menuStrip1.Text = "menuStrip1"; + // + // toolStripMenuItem1 + // + this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.newToolStripMenuItem}); + this.toolStripMenuItem1.Name = "toolStripMenuItem1"; + this.toolStripMenuItem1.Size = new System.Drawing.Size(57, 20); + this.toolStripMenuItem1.Text = "Window"; + // + // newToolStripMenuItem + // + this.newToolStripMenuItem.Name = "newToolStripMenuItem"; + this.newToolStripMenuItem.Size = new System.Drawing.Size(106, 22); + this.newToolStripMenuItem.Text = "New"; + this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); + // + // toolStripPanel1 + // + this.toolStripPanel1.Controls.Add(this.toolStrip1); + this.toolStripPanel1.Dock = System.Windows.Forms.DockStyle.Left; + this.toolStripPanel1.Location = new System.Drawing.Point(0, 49); + this.toolStripPanel1.Name = "toolStripPanel1"; + this.toolStripPanel1.Orientation = System.Windows.Forms.Orientation.Vertical; + this.toolStripPanel1.RowMargin = new System.Windows.Forms.Padding(0, 3, 0, 0); + this.toolStripPanel1.Size = new System.Drawing.Size(26, 199); + // + // toolStrip1 + // + this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; + this.toolStrip1.Location = new System.Drawing.Point(0, 3); + this.toolStrip1.Name = "toolStrip1"; + this.toolStrip1.Size = new System.Drawing.Size(26, 109); + this.toolStrip1.TabIndex = 0; + // + // toolStripPanel2 + // + this.toolStripPanel2.Controls.Add(this.toolStrip2); + this.toolStripPanel2.Dock = System.Windows.Forms.DockStyle.Top; + this.toolStripPanel2.Location = new System.Drawing.Point(0, 24); + this.toolStripPanel2.Name = "toolStripPanel2"; + this.toolStripPanel2.Orientation = System.Windows.Forms.Orientation.Horizontal; + this.toolStripPanel2.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); + this.toolStripPanel2.Size = new System.Drawing.Size(292, 25); + // + // toolStrip2 + // + this.toolStrip2.Dock = System.Windows.Forms.DockStyle.None; + this.toolStrip2.Location = new System.Drawing.Point(3, 0); + this.toolStrip2.Name = "toolStrip2"; + this.toolStrip2.Size = new System.Drawing.Size(109, 25); + this.toolStrip2.TabIndex = 0; + // + // toolStripPanel3 + // + this.toolStripPanel3.Controls.Add(this.toolStrip3); + this.toolStripPanel3.Dock = System.Windows.Forms.DockStyle.Right; + this.toolStripPanel3.Location = new System.Drawing.Point(266, 49); + this.toolStripPanel3.Name = "toolStripPanel3"; + this.toolStripPanel3.Orientation = System.Windows.Forms.Orientation.Vertical; + this.toolStripPanel3.RowMargin = new System.Windows.Forms.Padding(0, 3, 0, 0); + this.toolStripPanel3.Size = new System.Drawing.Size(26, 199); + // + // toolStrip3 + // + this.toolStrip3.Dock = System.Windows.Forms.DockStyle.None; + this.toolStrip3.Location = new System.Drawing.Point(0, 3); + this.toolStrip3.Name = "toolStrip3"; + this.toolStrip3.Size = new System.Drawing.Size(26, 109); + this.toolStrip3.TabIndex = 0; + // + // toolStripPanel4 + // + this.toolStripPanel4.Controls.Add(this.toolStrip4); + this.toolStripPanel4.Dock = System.Windows.Forms.DockStyle.Bottom; + this.toolStripPanel4.Location = new System.Drawing.Point(0, 248); + this.toolStripPanel4.Name = "toolStripPanel4"; + this.toolStripPanel4.Orientation = System.Windows.Forms.Orientation.Horizontal; + this.toolStripPanel4.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); + this.toolStripPanel4.Size = new System.Drawing.Size(292, 25); + // + // toolStrip4 + // + this.toolStrip4.Dock = System.Windows.Forms.DockStyle.None; + this.toolStrip4.Location = new System.Drawing.Point(3, 0); + this.toolStrip4.Name = "toolStrip4"; + this.toolStrip4.Size = new System.Drawing.Size(109, 25); + this.toolStrip4.TabIndex = 0; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.toolStripPanel3); + this.Controls.Add(this.toolStripPanel1); + this.Controls.Add(this.toolStripPanel2); + this.Controls.Add(this.menuStrip1); + this.Controls.Add(this.toolStripPanel4); + this.IsMdiContainer = true; + this.MainMenuStrip = this.menuStrip1; + this.Name = "Form1"; + this.Text = "Form1"; + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.toolStripPanel1.ResumeLayout(false); + this.toolStripPanel1.PerformLayout(); + this.toolStripPanel2.ResumeLayout(false); + this.toolStripPanel2.PerformLayout(); + this.toolStripPanel3.ResumeLayout(false); + this.toolStripPanel3.PerformLayout(); + this.toolStripPanel4.ResumeLayout(false); + this.toolStripPanel4.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + } + + public class ChildForm : Form + { + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; + private System.ComponentModel.IContainer components = null; + + public ChildForm() + { + InitializeComponent(); + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + private void InitializeComponent() + { + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.menuStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem1}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(292, 24); + this.menuStrip1.TabIndex = 0; + this.menuStrip1.Text = "menuStrip1"; + // + // toolStripMenuItem1 + // + this.toolStripMenuItem1.Name = "toolStripMenuItem1"; + this.toolStripMenuItem1.Size = new System.Drawing.Size(90, 20); + this.toolStripMenuItem1.Text = "ChildMenuItem"; + // + // ChildForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.menuStrip1); + this.MainMenuStrip = this.menuStrip1; + this.Name = "ChildForm"; + this.Text = "ChildForm"; + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs new file mode 100644 index 0000000000..e6cc819d4a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/CS/Program.cs @@ -0,0 +1,678 @@ +// +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Drawing; +// + +namespace WindowsApplication2 +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + + //Application.Run(new Form1()); + //Application.Run(new Form2()); + Application.Run(new Form3()); + //Application.Run(new Form4()); + //Application.Run(new Form5()); + //Application.Run(new Form6()); + } + } + + // + // This code example demonstrates how to use ToolStripPanel + // controls with a multiple document interface (MDI). + public class Form1 : Form + { + public Form1() + { + // Make the Form an MDI parent. + this.IsMdiContainer = true; + + // + // Create ToolStripPanel controls. + ToolStripPanel tspTop = new ToolStripPanel(); + ToolStripPanel tspBottom = new ToolStripPanel(); + ToolStripPanel tspLeft = new ToolStripPanel(); + ToolStripPanel tspRight = new ToolStripPanel(); + + // Dock the ToolStripPanel controls to the edges of the form. + tspTop.Dock = DockStyle.Top; + tspBottom.Dock = DockStyle.Bottom; + tspLeft.Dock = DockStyle.Left; + tspRight.Dock = DockStyle.Right; + + // Create ToolStrip controls to move among the + // ToolStripPanel controls. + + // Create the "Top" ToolStrip control and add + // to the corresponding ToolStripPanel. + ToolStrip tsTop = new ToolStrip(); + tsTop.Items.Add("Top"); + tspTop.Join(tsTop); + + // Create the "Bottom" ToolStrip control and add + // to the corresponding ToolStripPanel. + ToolStrip tsBottom = new ToolStrip(); + tsBottom.Items.Add("Bottom"); + tspBottom.Join(tsBottom); + + // Create the "Right" ToolStrip control and add + // to the corresponding ToolStripPanel. + ToolStrip tsRight = new ToolStrip(); + tsRight.Items.Add("Right"); + tspRight.Join(tsRight); + + // Create the "Left" ToolStrip control and add + // to the corresponding ToolStripPanel. + ToolStrip tsLeft = new ToolStrip(); + tsLeft.Items.Add("Left"); + tspLeft.Join(tsLeft); + // + + // + // Create a MenuStrip control with a new window. + MenuStrip ms = new MenuStrip(); + ToolStripMenuItem windowMenu = new ToolStripMenuItem("Window"); + ToolStripMenuItem windowNewMenu = new ToolStripMenuItem("New", null, new EventHandler(windowNewMenu_Click)); + windowMenu.DropDownItems.Add(windowNewMenu); + ((ToolStripDropDownMenu)(windowMenu.DropDown)).ShowImageMargin = false; + ((ToolStripDropDownMenu)(windowMenu.DropDown)).ShowCheckMargin = true; + + // Assign the ToolStripMenuItem that displays + // the list of child forms. + ms.MdiWindowListItem = windowMenu; + + // Add the window ToolStripMenuItem to the MenuStrip. + ms.Items.Add(windowMenu); + + // Dock the MenuStrip to the top of the form. + ms.Dock = DockStyle.Top; + + // The Form.MainMenuStrip property determines the merge target. + this.MainMenuStrip = ms; + // + + // Add the ToolStripPanels to the form in reverse order. + this.Controls.Add(tspRight); + this.Controls.Add(tspLeft); + this.Controls.Add(tspBottom); + this.Controls.Add(tspTop); + + // Add the MenuStrip last. + // This is important for correct placement in the z-order. + this.Controls.Add(ms); + } + + // This event handler is invoked when + // the "New" ToolStripMenuItem is clicked. + // It creates a new Form and sets its MdiParent + // property to the main form. + void windowNewMenu_Click(object sender, EventArgs e) + { + Form f = new Form(); + f.MdiParent = this; + f.Text = "Form - " + this.MdiChildren.Length.ToString(); + f.Show(); + } + } + // + + // + // This code example demonstrates how to use a ProfessionalRenderer + // to define custom professional colors at runtime. + class Form2 : Form + { + // + public Form2() + { + // Create a new ToolStrip control. + ToolStrip ts = new ToolStrip(); + + // Populate the ToolStrip control. + ts.Items.Add("Apples"); + ts.Items.Add("Oranges"); + ts.Items.Add("Pears"); + ts.Items.Add( + "Change Colors", + null, + new EventHandler(ChangeColors_Click)); + + // Create a new MenuStrip. + MenuStrip ms = new MenuStrip(); + + // Dock the MenuStrip control to the top of the form. + ms.Dock = DockStyle.Top; + + // Add the top-level menu items. + ms.Items.Add("File"); + ms.Items.Add("Edit"); + ms.Items.Add("View"); + ms.Items.Add("Window"); + + // + // Add the ToolStrip to Controls collection. + this.Controls.Add(ts); + + // Add the MenuStrip control last. + // This is important for correct placement in the z-order. + this.Controls.Add(ms); + // + } + // + + // + // This event handler is invoked when the "Change colors" + // ToolStripItem is clicked. It assigns the Renderer + // property for the ToolStrip control. + void ChangeColors_Click(object sender, EventArgs e) + { + ToolStripManager.Renderer = + new ToolStripProfessionalRenderer(new CustomProfessionalColors()); + } + // + } + + // + // This class defines the gradient colors for + // the MenuStrip and the ToolStrip. + class CustomProfessionalColors : ProfessionalColorTable + { + public override Color ToolStripGradientBegin + { get { return Color.BlueViolet; } } + + public override Color ToolStripGradientMiddle + { get { return Color.CadetBlue; } } + + public override Color ToolStripGradientEnd + { get { return Color.CornflowerBlue; } } + + public override Color MenuStripGradientBegin + { get { return Color.Salmon; } } + + public override Color MenuStripGradientEnd + { get { return Color.OrangeRed; } } + } + // + // + + // + // This code example demonstrates how to handle the Opening event. + // It also demonstrates dynamic item addition and dynamic + // SourceControl determination with reuse. + class Form3 : Form + { + // Declare the ContextMenuStrip control. + private ContextMenuStrip fruitContextMenuStrip; + + public Form3() + { + // Create a new ContextMenuStrip control. + fruitContextMenuStrip = new ContextMenuStrip(); + + // Attach an event handler for the + // ContextMenuStrip control's Opening event. + fruitContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(cms_Opening); + + // Create a new ToolStrip control. + ToolStrip ts = new ToolStrip(); + + // Create a ToolStripDropDownButton control and add it + // to the ToolStrip control's Items collections. + ToolStripDropDownButton fruitToolStripDropDownButton = new ToolStripDropDownButton("Fruit", null, null, "Fruit"); + ts.Items.Add(fruitToolStripDropDownButton); + + // Dock the ToolStrip control to the top of the form. + ts.Dock = DockStyle.Top; + + // Assign the ContextMenuStrip control as the + // ToolStripDropDownButton control's DropDown menu. + fruitToolStripDropDownButton.DropDown = fruitContextMenuStrip; + + // Create a new MenuStrip control and add a ToolStripMenuItem. + MenuStrip ms = new MenuStrip(); + ToolStripMenuItem fruitToolStripMenuItem = new ToolStripMenuItem("Fruit", null, null, "Fruit"); + ms.Items.Add(fruitToolStripMenuItem); + + // Dock the MenuStrip control to the top of the form. + ms.Dock = DockStyle.Top; + + // Assign the MenuStrip control as the + // ToolStripMenuItem's DropDown menu. + fruitToolStripMenuItem.DropDown = fruitContextMenuStrip; + + // Assign the ContextMenuStrip to the form's + // ContextMenuStrip property. + this.ContextMenuStrip = fruitContextMenuStrip; + + // Add the ToolStrip control to the Controls collection. + this.Controls.Add(ts); + + //Add a button to the form and assign its ContextMenuStrip. + Button b = new Button(); + b.Location = new System.Drawing.Point(60, 60); + this.Controls.Add(b); + b.ContextMenuStrip = fruitContextMenuStrip; + + // Add the MenuStrip control last. + // This is important for correct placement in the z-order. + this.Controls.Add(ms); + } + + // + // This event handler is invoked when the ContextMenuStrip + // control's Opening event is raised. It demonstrates + // dynamic item addition and dynamic SourceControl + // determination with reuse. + void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e) + { + // Acquire references to the owning control and item. + Control c = fruitContextMenuStrip.SourceControl as Control; + ToolStripDropDownItem tsi = fruitContextMenuStrip.OwnerItem as ToolStripDropDownItem; + + // Clear the ContextMenuStrip control's Items collection. + fruitContextMenuStrip.Items.Clear(); + + // Check the source control first. + if (c != null) + { + // Add custom item (Form) + fruitContextMenuStrip.Items.Add("Source: " + c.GetType().ToString()); + } + else if (tsi != null) + { + // Add custom item (ToolStripDropDownButton or ToolStripMenuItem) + fruitContextMenuStrip.Items.Add("Source: " + tsi.GetType().ToString()); + } + + // Populate the ContextMenuStrip control with its default items. + fruitContextMenuStrip.Items.Add("-"); + fruitContextMenuStrip.Items.Add("Apples"); + fruitContextMenuStrip.Items.Add("Oranges"); + fruitContextMenuStrip.Items.Add("Pears"); + + // Set Cancel to false. + // It is optimized to true based on empty entry. + e.Cancel = false; + } + // + } + // + + // + // This code example demonstrates using the Spring property + // to interactively center a ToolStripStatusLabel in a StatusStrip. + class Form4 : Form + { + // Declare the ToolStripStatusLabel. + ToolStripStatusLabel middleLabel; + + public Form4() + { + // Create a new StatusStrip control. + StatusStrip ss = new StatusStrip(); + + // Add the leftmost label. + ss.Items.Add("Left"); + + // Handle middle label separately -- action will occur + // when the label is clicked. + middleLabel = new ToolStripStatusLabel("Middle (Spring)"); + middleLabel.Click += new EventHandler(middleLabel_Click); + ss.Items.Add(middleLabel); + + // Add the rightmost label + ss.Items.Add("Right"); + + // Add the StatusStrip control to the controls collection. + this.Controls.Add(ss); + } + + // + // This event hadler is invoked when the + // middleLabel control is clicked. It toggles + // the value of the Spring property. + void middleLabel_Click(object sender, EventArgs e) + { + // Toggle the value of the Spring property. + middleLabel.Spring ^= true; + + // Set the Text property according to the + // value of the Spring property. + middleLabel.Text = + middleLabel.Spring ? "Middle (Spring - True)" : "Middle (Spring - False)"; + } + // + } + // + + // + // This code example demonstrates how to set the check + // and image margins for a ToolStripMenuItem. + class Form5 : Form + { + // + public Form5() + { + // Size the form to show three wide menu items. + this.Width = 500; + this.Text = "ToolStripContextMenuStrip: Image and Check Margins"; + + // Create a new MenuStrip control. + MenuStrip ms = new MenuStrip(); + + // Create the ToolStripMenuItems for the MenuStrip control. + ToolStripMenuItem bothMargins = new ToolStripMenuItem("BothMargins"); + ToolStripMenuItem imageMarginOnly = new ToolStripMenuItem("ImageMargin"); + ToolStripMenuItem checkMarginOnly = new ToolStripMenuItem("CheckMargin"); + ToolStripMenuItem noMargins = new ToolStripMenuItem("NoMargins"); + + // Customize the DropDowns menus. + // This ToolStripMenuItem has an image margin + // and a check margin. + bothMargins.DropDown = CreateCheckImageContextMenuStrip(); + ((ContextMenuStrip)bothMargins.DropDown).ShowImageMargin = true; + ((ContextMenuStrip)bothMargins.DropDown).ShowCheckMargin = true; + + // This ToolStripMenuItem has only an image margin. + imageMarginOnly.DropDown = CreateCheckImageContextMenuStrip(); + ((ContextMenuStrip)imageMarginOnly.DropDown).ShowImageMargin = true; + ((ContextMenuStrip)imageMarginOnly.DropDown).ShowCheckMargin = false; + + // This ToolStripMenuItem has only a check margin. + checkMarginOnly.DropDown = CreateCheckImageContextMenuStrip(); + ((ContextMenuStrip)checkMarginOnly.DropDown).ShowImageMargin = false; + ((ContextMenuStrip)checkMarginOnly.DropDown).ShowCheckMargin = true; + + // This ToolStripMenuItem has no image and no check margin. + noMargins.DropDown = CreateCheckImageContextMenuStrip(); + ((ContextMenuStrip)noMargins.DropDown).ShowImageMargin = false; + ((ContextMenuStrip)noMargins.DropDown).ShowCheckMargin = false; + + // Populate the MenuStrip control with the ToolStripMenuItems. + ms.Items.Add(bothMargins); + ms.Items.Add(imageMarginOnly); + ms.Items.Add(checkMarginOnly); + ms.Items.Add(noMargins); + + // Dock the MenuStrip control to the top of the form. + ms.Dock = DockStyle.Top; + + // Add the MenuStrip control to the controls collection last. + // This is important for correct placement in the z-order. + this.Controls.Add(ms); + } + // + + // This utility method creates a Bitmap for use in + // a ToolStripMenuItem's image margin. + internal Bitmap CreateSampleBitmap() + { + // The Bitmap is a smiley face. + Bitmap sampleBitmap = new Bitmap(32, 32); + Graphics g = Graphics.FromImage(sampleBitmap); + + using (Pen p = new Pen(ProfessionalColors.ButtonPressedBorder)) + { + // Set the Pen width. + p.Width = 4; + + // Set up the mouth geometry. + Point[] curvePoints = new Point[]{ + new Point(4,14), + new Point(16,24), + new Point(28,14)}; + + // Draw the mouth. + g.DrawCurve(p, curvePoints); + + // Draw the eyes. + g.DrawEllipse(p, new Rectangle(new Point(7, 4), new Size(3, 3))); + g.DrawEllipse(p, new Rectangle(new Point(22, 4), new Size(3, 3))); + } + + return sampleBitmap; + } + + // + // This utility method creates a ContextMenuStrip control + // that has four ToolStripMenuItems showing the four + // possible combinations of image and check margins. + internal ContextMenuStrip CreateCheckImageContextMenuStrip() + { + // Create a new ContextMenuStrip control. + ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip(); + + // Create a ToolStripMenuItem with a + // check margin and an image margin. + ToolStripMenuItem yesCheckYesImage = + new ToolStripMenuItem("Check, Image"); + yesCheckYesImage.Checked = true; + yesCheckYesImage.Image = CreateSampleBitmap(); + + // Create a ToolStripMenuItem with no + // check margin and with an image margin. + ToolStripMenuItem noCheckYesImage = + new ToolStripMenuItem("No Check, Image"); + noCheckYesImage.Checked = false; + noCheckYesImage.Image = CreateSampleBitmap(); + + // Create a ToolStripMenuItem with a + // check margin and without an image margin. + ToolStripMenuItem yesCheckNoImage = + new ToolStripMenuItem("Check, No Image"); + yesCheckNoImage.Checked = true; + + // Create a ToolStripMenuItem with no + // check margin and no image margin. + ToolStripMenuItem noCheckNoImage = + new ToolStripMenuItem("No Check, No Image"); + noCheckNoImage.Checked = false; + + // Add the ToolStripMenuItems to the ContextMenuStrip control. + checkImageContextMenuStrip.Items.Add(yesCheckYesImage); + checkImageContextMenuStrip.Items.Add(noCheckYesImage); + checkImageContextMenuStrip.Items.Add(yesCheckNoImage); + checkImageContextMenuStrip.Items.Add(noCheckNoImage); + + return checkImageContextMenuStrip; + } + // + } + // + + // + // This example demonstrates how to apply a + // custom professional renderer to an individual + // ToolStrip or to the application as a whole. + class Form6 : Form + { + ComboBox targetComboBox = new ComboBox(); + + public Form6() + { + // Alter the renderer at the top level. + + // Create and populate a new ToolStrip control. + ToolStrip ts = new ToolStrip(); + ts.Name = "ToolStrip"; + ts.Items.Add("Apples"); + ts.Items.Add("Oranges"); + ts.Items.Add("Pears"); + + // Create a new menustrip with a new window. + MenuStrip ms = new MenuStrip(); + ms.Name = "MenuStrip"; + ms.Dock = DockStyle.Top; + + // add top level items + ToolStripMenuItem fileMenuItem = new ToolStripMenuItem("File"); + ms.Items.Add(fileMenuItem); + ms.Items.Add("Edit"); + ms.Items.Add("View"); + ms.Items.Add("Window"); + + // Add subitems to the "File" menu. + fileMenuItem.DropDownItems.Add("Open"); + fileMenuItem.DropDownItems.Add("Save"); + fileMenuItem.DropDownItems.Add("Save As..."); + fileMenuItem.DropDownItems.Add("-"); + fileMenuItem.DropDownItems.Add("Exit"); + + // Add a Button control to apply renderers. + Button applyButton = new Button(); + applyButton.Text = "Apply Custom Renderer"; + applyButton.Click += new EventHandler(applyButton_Click); + + // Add the ComboBox control for choosing how + // to apply the renderers. + targetComboBox.Items.Add("All"); + targetComboBox.Items.Add("MenuStrip"); + targetComboBox.Items.Add("ToolStrip"); + targetComboBox.Items.Add("Reset"); + + // Create and set up a TableLayoutPanel control. + TableLayoutPanel tlp = new TableLayoutPanel(); + tlp.Dock = DockStyle.Fill; + tlp.RowCount = 1; + tlp.ColumnCount = 2; + tlp.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent)); + tlp.Controls.Add(applyButton); + tlp.Controls.Add(targetComboBox); + + // Create a GroupBox for the TableLayoutPanel control. + GroupBox gb = new GroupBox(); + gb.Text = "Apply Renderers"; + gb.Dock = DockStyle.Fill; + gb.Controls.Add(tlp); + + // Add the GroupBox to the form. + this.Controls.Add(gb); + + // Add the ToolStrip to the form's Controls collection. + this.Controls.Add(ts); + + // Add the MenuStrip control last. + // This is important for correct placement in the z-order. + this.Controls.Add(ms); + } + + // + // This event handler is invoked when + // the "Apply Renderers" button is clicked. + // Depending on the value selected in a ComboBox control, + // it applies a custom renderer selectively to + // individual MenuStrip or ToolStrip controls, + // or it applies a custom renderer to the + // application as a whole. + void applyButton_Click(object sender, EventArgs e) + { + ToolStrip ms = ToolStripManager.FindToolStrip("MenuStrip"); + ToolStrip ts = ToolStripManager.FindToolStrip("ToolStrip"); + + if (targetComboBox.SelectedItem != null) + { + switch (targetComboBox.SelectedItem.ToString()) + { + case "Reset": + { + ms.RenderMode = ToolStripRenderMode.ManagerRenderMode; + ts.RenderMode = ToolStripRenderMode.ManagerRenderMode; + + // Set the default RenderMode to Professional. + ToolStripManager.RenderMode = ToolStripManagerRenderMode.Professional; + + break; + } + + case "All": + { + ms.RenderMode = ToolStripRenderMode.ManagerRenderMode; + ts.RenderMode = ToolStripRenderMode.ManagerRenderMode; + + // Assign the custom renderer at the application level. + ToolStripManager.Renderer = new CustomProfessionalRenderer(); + + break; + } + + case "MenuStrip": + { + // Assign the custom renderer to the MenuStrip control only. + ms.Renderer = new CustomProfessionalRenderer(); + + break; + } + + case "ToolStrip": + { + // Assign the custom renderer to the ToolStrip control only. + ts.Renderer = new CustomProfessionalRenderer(); + + break; + } + } + } + } + // + } + + // + // This type demonstrates a custom renderer. It overrides the + // OnRenderMenuItemBackground and OnRenderButtonBackground methods + // to customize the backgrounds of MenuStrip items and ToolStrip buttons. + class CustomProfessionalRenderer : ToolStripProfessionalRenderer + { + // + protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + if (e.Item.Selected) + { + using (Brush b = new SolidBrush(ProfessionalColors.SeparatorLight)) + { + e.Graphics.FillEllipse(b, e.Item.ContentRectangle); + } + } + else + { + using (Pen p = new Pen(ProfessionalColors.SeparatorLight)) + { + e.Graphics.DrawEllipse(p, e.Item.ContentRectangle); + } + } + } + // + + // + protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) + { + Rectangle r = Rectangle.Inflate(e.Item.ContentRectangle, -2, -2); + + if (e.Item.Selected) + { + using (Brush b = new SolidBrush(ProfessionalColors.SeparatorLight)) + { + e.Graphics.FillRectangle(b, r); + } + } + else + { + using (Pen p = new Pen(ProfessionalColors.SeparatorLight)) + { + e.Graphics.DrawRectangle(p, r); + } + } + } + // + } + // + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs new file mode 100644 index 0000000000..d543654210 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/CS/StackView.cs @@ -0,0 +1,537 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.IO; +using System.Windows.Forms; + +namespace StackViewCS +{ + public class StackView : UserControl + { + private ToolStrip stackStrip; + private ToolStripButton mailStackButton; + private ToolStripButton calendarStackButton; + private ToolStripButton contactsStackButton; + private ToolStripButton tasksStackButton; + + private System.ComponentModel.IContainer components = null; + + // + private static Bitmap mailBmp; + private static Bitmap calendarBmp; + private static Bitmap contactsBmp; + private static Bitmap tasksBmp; + + private static string mailBmpEnc = @"Qk32BgAAAAAAADYAAAAoAAAA"+ + "GAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7uv4yFvouE"+ + "vYmDu4eBuYV/t4N9tYB7s355sXt3tntxsnhwsHZurXNsrHFrp21pomln"+ + "oGdlnmVjnWNi7u7u7u7u7u7u7u7u7u7uwY6H9N3C/vDa/ejM+tSp+cye"+ + "98OS9bqI87F/87KA8qt68KRy76Bu7phl7ZVi7JVi54xb0ntSoGVj7u7u"+ + "7u7u7u7u7u7u7u7uwo+Ix6WZ9ujb//bn/u/b/OfL++HA+9iv+tev+tSr"+ + "+tKo+cyg+Mic9b+S9LqM8al35ZZmoXBSoWdk7u7u7u7u7u7u7u7u7u7u"+ + "xZSN9ejayaOY9uvh//js/vXo/e/a/evS/OfL/OTF+927+9u1+tSq+tKl"+ + "+cqW8buFqHZa7JVdn2hm7u7u7u7u7u7u7u7u7u7uxZSN//ns9ercxqKV"+ + "+O7k//nw//fu//fr/vTl/u/c/uvU/eLB/N+7+tev8b6Hq3pe+Lh6/69q"+ + "oWpp7u7u7u7u7u7u7u7u7u7ux5eP//vv//vw9OncxKOX9+7m//v1//nz"+ + "//jx//bs/+7Z/erQ/eTC8syiqntg+M6a/9Oh/8CFom1s7u7u7u7u7u7u"+ + "7u7u7u7uypqS//z4//v28ebYza2evp6V7+Lb8uzl8+3l8uvk9Ore9ejZ"+ + "6NO/poVyt4xx5b2T/9ap/8ybpXFw7u7u7u7u7u7u7u7u7u7uzJ2V///8"+ + "7uPbzaye/fv6/fv5v6GTvKCQvJ+Nu5qIupmJt5uKsZWE+u3e+unYo4Jq"+ + "572O/9KjqHd17u7u7u7u7u7u7u7u7u7uzqCX7OHbzKud/fr58url5tnQ"+ + "5dfO5dfN5dfM5NbM49TI3Mq+3Mm93Mm8382/+unbrIJp57WGrH597u7u"+ + "7u7u7u7u7u7u7u7uz6GZ0LGj6uHa/fv67OLc6+Hb7eTd7ePd7eLb7eLb"+ + "7uPb9e7l9evk9uvj9+zh/PHlzr61r4VtsoWC7u7u7u7u7u7u7u7u7u7u"+ + "0aKXfdb/8uzn///////////////////////+//37/Pn3+fXv9fHp8+vl"+ + "8enk7uXe1si/L6f3tYeC7u7u7u7u7u7u7u7u7u7uy6mkdM3/+vf1////"+ + "/////////////////fz8/Pv69fPx7vDw7O/w2OfvxN/swt/thMXnK6ft"+ + "r4SC7u7u7u7u7u7u7u7u7u7u1KeevuX6nNf2rN/7nNz9h9X+b8z+VMb/"+ + "RsT/RsT/PsP/Obz7NLT2MbL0K6vuJ6XpKKfrLqrvr4J/7u7u7u7u7u7u"+ + "7u7u7u7u28jC0rSo0O36yOv7x+r7v+f8suP9o97+jtj+idn+htX/e83/"+ + "a8f/XcD/Tbn/SLf/R7b/rJKJ7u7u7u7u7u7u7u7u7u7u7u7u7u7u6ePi"+ + "07ew29zd1e/61O/60e77y+z8vun9reH+mNn+gdH/ccj/ZMP/Vr3/t7/C"+ + "uKCX7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u6uXk2b621rux1fH6"+ + "3fL61/L7y+/8u+f9pt7+jNT+cMn/XcH/rZyW1c3L7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u6N/d07Op3d7f2/P60vD7xez8"+ + "r+H9k9X+kr/cv6Wb7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u6uXk2L612cG31e73yOv7seL8uKWezLex7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u6eHg1LOpzaeayaqh4dvb7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"; + + private static string calendarBmpEnc = @"Qk32BgAAAAAAADYAAAAo"+ + "AAAAGAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7uuKOUkXxqemNO"+ + "alM8YEgwYEgwYkoxYUgwYEgwY0szYkoxYEgwYEgwYEgwYEgwZEszYUgw"+ + "YEgwY0oyYUgwYEgwYEgw7u7u7u7uuqWW6tPE27qlxKCLu5d837OUzKGC"+ + "t41xsYpt37OUzKGCt41xrodq37OUzKGCt41xrodq37OUzKGCt41xrodq"+ + "Zk447u7u7u7uvKaX//fz/+3i/NvFwJl6/+nb/d3H+c+1vJV2/+HP/tW8"+ + "/MWluZJz/9vG/9Gw+8OfuJFy/86y/sKf97eSuJFyYEgw7u7u7u7uvaiZ"+ + "//j2//Hq/OTY0qiL/+7h/+TR/N3J0KWI/+TU/9vE/9S4zqOF/+LR/9zE"+ + "/sywzaKE/9e//8yt/sWizaKEYEgw7u7u7u7uv6qb//v5//j1//bx5Lug"+ + "//Ho//Dl/+nb5Lqg/+fZ/+LQ/97I5Lqf/+XU/+HN/9zF5Lqf/9bC/9S7"+ + "/9C05LqfYEgw7u7u7u7uwauc4bib1ayOxZyBvpd74LaY0qiKwJd7uJF1"+ + "4LWWz6WGvJJ2D0XuBTnjBjXQAiy8ACm137OUzKGCt41xrodqYEgw7u7u"+ + "7u7uxK6f//v6/Ozg/eHQx6CC/+/m+uHQ+tjDwpt9/+re/+DM/9O4I1Tz"+ + "/9zG/9O5/86wASu4/9fC98Sm87uYuJFyYEgw7u7u7u7uxrCh//39//n0"+ + "/One1qyQ//v4/vHn+uHR06mM//Pt/+rc/+HMPGr0/+TU/93H/9i/AzHJ"+ + "/+LP/9i++curzaKEYEgw7u7u7u7ux7Kj//39//38/fbw5Luh//z7/vj1"+ + "/uzh5Lug//fx//bv/+vgWoH2/+/m/+vd/+PQAzTa/+XU/+XU/97J5Lqf"+ + "YUkx7u7u7u7uybOk47yh3rab1q2SzaWL4bqe2a+SzKKHwpqA4bmd1q2O"+ + "x52CbY/5WYD3OWb0IFP0Aj3t4Lib06iJwJV5sopwYEgw7u7u7u7uzbep"+ + "//39//n1//Dn1a2S/vv6+uvh9+DPyqKG//Tt+eXX+eDSxJx//One+tzH"+ + "+dC3v5d6/9/K+9C1+8akuI9yalM97u7u7u7u0Lyu//39//r3//f03bWa"+ + "//7+/vXx+urg1q2R//f0/O3i+eTV06mM//fy/+7i+NfCz6WI/+zg/+DM"+ + "/9CzyZ6Adl5I7u7u7u7u0sCy//38//39//395L2j//7+//79/vn45L2j"+ + "//38//n2/vLr5L2j//37//n2/unf5L2j/+/l/+nc/+DN5L2jf2dS7u7u"+ + "7u7u6KaG6KaG6KSE56OB56B+55565pt25phy5ZVt5ZJp5I5k5Itf5Iha"+ + "44RV44FR4n5M4ntI4XhE23I812w00mkzyGAo7u7u7u7u6amK/93L/dfD"+ + "/9a+/s+2/syy/sis/sSl/cGh/byb/LeV+7SO+rCJ+auC+ad9+KN3+KBx"+ + "95xu95pq9pdn9pVkyGAo7u7u7u7u662P/+LQ/t/M/t3K/drG/dfC/dK8"+ + "/c63/Mqx/Mer+sKk+r6f+bqY+LaT+LGM96yG9qmA9aV69aB19J1w9Jps"+ + "yGAo7u7u7u7u7LKV7LKV662P6aeG56F/559855x45pp05pdw5ZRs5ZFo"+ + "5I5j5Itf5Ihb44VW44JS4n9O4nxK4XpG4XdC4XU/2Ws27u7u7u7upJqU"+ + "////pJqU////n5aQ////mZCL////kYmF////iIJ+////fnp2////dXJv"+ + "////bGpo////ZGNi////XV5c////7u7u7u7u7u7uICUg6enpICUg6enp"+ + "ICUg6enpICUg6enpICUg6enpICUg6enpICUg3t7eICUg0NDQICUgvb29"+ + "ICUguLi4ICUg7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u"; + + private static string contactsBmpEnc = @"Qk32BgAAAAAAADYAAAAo"+ + "AAAAGAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7uuqWWh3FeeWJN"+ + "alM8YEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgw"+ + "YEgwYEgwYEgwYEgwYEgw7u7u7u7uuqWW//bx7t3T7trO7tfI79LB7865"+ + "8Mqy8MWq8cCi8buZ8raR8rKJ862C86l69KV09KFt9Z5o9Zxk9Zph9Zph"+ + "YEgw7u7u7u7uu6aX//n2//fy//Xv//Lr//Dn/+3j/+re/+ja/+XW/+LR"+ + "/+DN/93J/9rF/9jB/9W9/9O5/9G2/8+z/86x9ZphYEgw7u7u7u7uvKiZ"+ + "//z6//r30M/SGlmtA0uuA0WfAz+RATmHADV9zr23/+PTs4t1roRuqX1m"+ + "pHhgoXRcoXRcoXRc/9C09Z1mYEgw7u7u7u7uvqqb//79//z7FFe3N3rV"+ + "SYrkQ4XeA0OaGW3eC02nGkF4/+fZ/+TV/+LQ/9/M/9zI/9rE/9fA/9W8"+ + "/9O59KFtYEgw7u7u7u7uwKyd//////7+E1i3Z57pUZDoTY7nA0SbGGze"+ + "E2DIAzmD/+vfuZJ9s4t1roRuqX1mpHhgoXRcoXRc/9a99KV0YEgw7u7u"+ + "7u7uwq6f////////GF69gKvkX5flA0WeGW7iA0+3GWzgEk+j/+7l/+zh"+ + "/+nc/+bY/+TT/+HP/97L/9zH/9nD86t9YEgw7u7u7u7uxLCh////////"+ + "tcDPE1StGly1yNXZ+fryBVG5BkGOz8rK//LqvpiEuZJ9s4t1roRuqX1m"+ + "pHhgoXRc/93I87CHYEgw7u7u7u7uxrKk////////9fX1zdDTYWZsVFVW"+ + "YWFhBkunubzC//jz//Xw//Ps//Do/+7k/+vf/+jb/+bX/+PS/+DO8raR"+ + "YEgw7u7u7u7ux7Sm////////xMTEAAAAwcHBoqKihYWFVVVVn56d//r3"+ + "//j0//bx//Tt//Hp/+/l/+zh/+nd/+fY/+TU8b2cYEgw7u7u7u7uybao"+ + "////////ODg4LCws1tbWwcHBoqKihYWFZGRk//37//v5//n2//fy//Xv"+ + "//Lr//Dn/+3j/+re/+ja8MOmYEgw7u7u7u7uy7iq////////U1NTSUlJ"+ + "tLS01dXVwcHBoqKidXV1///+//38/LeL+7SI+q+D+ap++KV496Bz9p1w"+ + "/+vg8MmxZk437u7u7u7uzbqs////////fn5+Y2NjXV1dbW1tWFhYwcHB"+ + "hISE//////////79//z7//v4//n1//bx//Tu//Lq/+/m78+6b1dB7u7u"+ + "7u7uz7yu////////xcXFbGxsgoKCoaGhjo6OVVVVra2t/////////LeL"+ + "+7SI+q+D+ap++KV496Bz9p1w//Pr79TEeWJN7u7u7u7u0L6w////////"+ + "8vLyuLi4jY2NiIiIhYWFtLS08fHx//////////////////////38//z6"+ + "//r3//j0//bw7tnMgm1Z7u7u7u7u0b+x////////////////////////"+ + "//////////////////////////////////////79//z7//v4//n1//fy"+ + "i3Zj7u7u7u7u0sCy0b+x0L6wz72vzrutzLqsy7iqybeoyLWmxrOkxLGi"+ + "w6+hwa2fv6udvqmbvKiZu6aXuaWWuKOUt6KTtqGStaCR7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"+ + "7u7u"; + + private static string tasksBmpEnc = @"Qk32BgAAAAAAADYAAAAoAAA"+ + "AGAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u3N3fkXxqeGB"+ + "LalE5cVc/c1lBf2JKl3RZiWhMe1xBb1M5aE42Zkw0Zk01aE42YUkxYkk"+ + "xYkkxkod97u7u7u7u7u7u7u7u7u7uv62e+ezi69nQ7M6+7Miz6L+prI+"+ + "rWFKqmHyk7rWU77OO77CM8LCK8bCH8a2F8qp98aV13pZnZkwz7u7u7u7"+ + "u7u7u7u7u7u7uv62e//37/vr3/vTw+uvkwLnaJDO/BhmzJjTDybTG99K"+ + "8+NC49syy9sms9sao9cOl8LiV8KR0aU417u7u7u7u7u7u7u7u7u7uwK6"+ + "f//7+//z7/Pj3xcTmLDvBFynIMEXkIDbXVGHO6dHO+tzJ+tjD+dW++dK"+ + "5+c+19sWn8qd2Y0kx7u7u7u7u7u7u7u7u7u7uw7Gj/////Pv9wcTsKDj"+ + "FFCnMRVjuZHX1PlPoFzHSeHPJ+d3O+tzI+tjD+dS9+dG59seq8ayEaEw"+ + "07u7u7u7u7u7u7u7u7u7uxrWm9vf9pKzoJjjNGi7TR1nreoj/j5v8ZXf"+ + "0N0zlJjTPv7LP+t7O+tvI+tfC+dS998qv8K+LaU427u7u7u7u7u7u7u7"+ + "u7u7u08W619v5Kz7XJjrfTl/ze4v/tLr59/Dyoab2Znb0LUPmNUTO1sX"+ + "R+9/N+tvH+tjC99C277GNbVI47u7u7u7u7u7u7u7u7u7uy7qt6+3+kp7"+ + "4UGT4c4P/sbj+/Pr5/vj16ePykpz5Y3T0KDzfbHHR6dTS++HQ+tvG+dn"+ + "D8bqabVI57u7u7u7u7u7u7u7u7u7uybeo////9ff/qLL/wsr//Pz///3"+ + "8/vv5/ff09e7wpav4YnP0KDzajYzQ6NPT/N7O+NrG8b+idFlA7u7u7u7"+ + "u7u7u7u7u7u7uyriq////////+Pn//v7///////////38/vr2/vj08er"+ + "wmaL6WWvyMELXmJbS9OPb+d/Q88mxc1Y97u7u7u7u7u7u7u7u7u7uzLq"+ + "s//////////////////////////7+//36/vr3/vn0+fDvsLT1WmruNUb"+ + "Qta/V+uXX9M+6hWdP7u7u7u7u7u7u7u7u7u7uzryt///////////////"+ + "///////////////7+//79//v3/vj0+O7wurz0TV3sSFTS08fa9t7PmXl"+ + "h7u7u7u7u7u7u7u7u7u7uz72v/////////////////////fj1+Orh9uH"+ + "W89TD88+78sew9NK99drNm5/xVWbwYWvV6dzgrIlw7u7u7u7u7u7u7u7"+ + "u7u7u0L6w////////////////X4ycVYGSTHaIS21/SGN0SGJySF9vdnd"+ + "9pZWQ89TDt7n1TF3oZGvOuJ2L7u7u7u7u7u7u7u7u7u7u0b+x///////"+ + "/////////dJmou+Xsmd3ofs/fdcXVcMHSbrrNbbHCbHJ69dTD++3nw8H"+ + "uNUjqZGjJ7u7u7u7u7u7u7u7u7u7u0b+x////////////////i6q2pMn"+ + "StuzzYYycdLG+fs/ed8jaXY2eRl1t8uDU++je/O7mzsnmUFCX7u7u7u7"+ + "u7u7u7u7u7u7u0sCy////////////////3ufqdZuqx+30V3aFXoCPaZW"+ + "kjdDeTWx8v7Ko/vr2/fTv/fTu+/XxnZSu7u7u7u7u7u7u7u7u7u7u6ur"+ + "r2Mq/0b+x0L6wz72vyLeqc5qpoMHLxfD3v+zzruXvkMjVaX6GwK6ewrC"+ + "hwa+gwK6fv62e4OHi7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u5ObnfKa1eaOxcpyrcJWkboiW4+Pj7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7"+ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u"; + + // Static constructor to initialize + // the form's static fields. + static StackView() + { + // Create the static bitmaps from Base64 encoding. + CreateBitmaps(); + } + + // + public StackView() + { + this.InitializeComponent(); + + // Assign icons to ToolStripButton controls. + this.InitializeImages(); + + // Set up renderers. + this.stackStrip.Renderer = new StackRenderer(); + } + // + + // This utility method assigns icons to each + // ToolStripButton control. + private void InitializeImages() + { + this.mailStackButton.Image = mailBmp; + this.calendarStackButton.Image = calendarBmp; + this.contactsStackButton.Image = contactsBmp; + this.tasksStackButton.Image = tasksBmp; + } + + // This utility method creates bitmaps for all the icons. + // It uses a utility method called DeserializeFromBase64 + // to decode the Base64 image data. + private static void CreateBitmaps() + { + mailBmp = DeserializeFromBase64(mailBmpEnc); + calendarBmp = DeserializeFromBase64(calendarBmpEnc); + contactsBmp = DeserializeFromBase64(contactsBmpEnc); + tasksBmp = DeserializeFromBase64(tasksBmpEnc); + } + + // This utility method cretes a bitmap from + // a Base64-encoded string. + internal static Bitmap DeserializeFromBase64(string data) + { + // Decode the string and create a memory stream + // on the decoded string data. + MemoryStream stream = + new MemoryStream(Convert.FromBase64String(data)); + + // Create a new bitmap from the stream. + Bitmap b = new Bitmap(stream); + + return b; + } + // + + // + // This method handles the Load event for the UserControl. + private void StackView_Load(object sender, EventArgs e) + { + // Dock bottom. + this.Dock = DockStyle.Bottom; + + // Set AutoSize. + this.AutoSize = true; + } + // + + // + // This method handles the Click event for all + // the ToolStripButton controls in the StackView. + private void stackButton_Click(object sender, EventArgs e) + { + // Define a "one of many" state, similar to + // the logic of a RadioButton control. + foreach (ToolStripItem item in this.stackStrip.Items) + { + if ((item != sender) && + (item is ToolStripButton)) + { + ((ToolStripButton)item).Checked = false; + } + } + } + // + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + // + internal class StackRenderer : ToolStripProfessionalRenderer + { + private static Bitmap titleBarGripBmp; + private static string titleBarGripEnc = @"Qk16AQAAAAAAADYAAAAoAAAAIwAAAAMAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5ANj+RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5ANj+RzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMANj+"; + + // Define titlebar colors. + private static Color titlebarColor1 = Color.FromArgb(89, 135, 214); + private static Color titlebarColor2 = Color.FromArgb(76, 123, 204); + private static Color titlebarColor3 = Color.FromArgb(63, 111, 194); + private static Color titlebarColor4 = Color.FromArgb(50, 99, 184); + private static Color titlebarColor5 = Color.FromArgb(38, 88, 174); + private static Color titlebarColor6 = Color.FromArgb(25, 76, 164); + private static Color titlebarColor7 = Color.FromArgb(12, 64, 154); + private static Color borderColor = Color.FromArgb(0, 0, 128); + + static StackRenderer() + { + titleBarGripBmp = StackView.DeserializeFromBase64(titleBarGripEnc); + } + + public StackRenderer() + { + } + + private void DrawTitleBar(Graphics g, Rectangle rect) + { + // Assign the image for the grip. + Image titlebarGrip = titleBarGripBmp; + + // Fill the titlebar. + // This produces the gradient and the rounded-corner effect. + g.DrawLine(new Pen(titlebarColor1), rect.X, rect.Y, rect.X + rect.Width, rect.Y); + g.DrawLine(new Pen(titlebarColor2), rect.X, rect.Y + 1, rect.X + rect.Width, rect.Y + 1); + g.DrawLine(new Pen(titlebarColor3), rect.X, rect.Y + 2, rect.X + rect.Width, rect.Y + 2); + g.DrawLine(new Pen(titlebarColor4), rect.X, rect.Y + 3, rect.X + rect.Width, rect.Y + 3); + g.DrawLine(new Pen(titlebarColor5), rect.X, rect.Y + 4, rect.X + rect.Width, rect.Y + 4); + g.DrawLine(new Pen(titlebarColor6), rect.X, rect.Y + 5, rect.X + rect.Width, rect.Y + 5); + g.DrawLine(new Pen(titlebarColor7), rect.X, rect.Y + 6, rect.X + rect.Width, rect.Y + 6); + + // Center the titlebar grip. + g.DrawImage( + titlebarGrip, + new Point(rect.X + ((rect.Width / 2) - (titlebarGrip.Width / 2)), + rect.Y + 1)); + } + + // This method handles the RenderGrip event. + protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) + { + DrawTitleBar( + e.Graphics, + new Rectangle(0, 0, e.ToolStrip.Width, 7)); + } + + // This method handles the RenderToolStripBorder event. + protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) + { + DrawTitleBar( + e.Graphics, + new Rectangle(0, 0, e.ToolStrip.Width, 7)); + } + + // This method handles the RenderButtonBackground event. + protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) + { + Graphics g = e.Graphics; + Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size); + + Color gradientBegin = Color.FromArgb(203, 225, 252); + Color gradientEnd = Color.FromArgb(125, 165, 224); + + ToolStripButton button = e.Item as ToolStripButton; + if (button.Pressed || button.Checked) + { + gradientBegin = Color.FromArgb(254, 128, 62); + gradientEnd = Color.FromArgb(255, 223, 154); + } + else if (button.Selected) + { + gradientBegin = Color.FromArgb(255, 255, 222); + gradientEnd = Color.FromArgb(255, 203, 136); + } + + using (Brush b = new LinearGradientBrush( + bounds, + gradientBegin, + gradientEnd, + LinearGradientMode.Vertical)) + { + g.FillRectangle(b, bounds); + } + + e.Graphics.DrawRectangle( + SystemPens.ControlDarkDark, + bounds); + + g.DrawLine( + SystemPens.ControlDarkDark, + bounds.X, + bounds.Y, + bounds.Width - 1, + bounds.Y); + + g.DrawLine( + SystemPens.ControlDarkDark, + bounds.X, + bounds.Y, + bounds.X, + bounds.Height - 1); + + ToolStrip toolStrip = button.Owner; + ToolStripButton nextItem = button.Owner.GetItemAt( + button.Bounds.X, + button.Bounds.Bottom + 1) as ToolStripButton; + + if (nextItem == null) + { + g.DrawLine( + SystemPens.ControlDarkDark, + bounds.X, + bounds.Height - 1, + bounds.X + bounds.Width - 1, + bounds.Height - 1); + } + } + } + // + + #region Component Designer generated code + + private void InitializeComponent() + { + this.stackStrip = new System.Windows.Forms.ToolStrip(); + this.mailStackButton = new System.Windows.Forms.ToolStripButton(); + this.calendarStackButton = new System.Windows.Forms.ToolStripButton(); + this.contactsStackButton = new System.Windows.Forms.ToolStripButton(); + this.tasksStackButton = new System.Windows.Forms.ToolStripButton(); + this.stackStrip.SuspendLayout(); + this.SuspendLayout(); + // + // stackStrip + // + this.stackStrip.CanOverflow = false; + this.stackStrip.Dock = System.Windows.Forms.DockStyle.Bottom; + this.stackStrip.Font = new System.Drawing.Font("Tahoma", 10F, System.Drawing.FontStyle.Bold); + this.stackStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + this.stackStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.mailStackButton, + this.calendarStackButton, + this.contactsStackButton, + this.tasksStackButton}); + this.stackStrip.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow; + this.stackStrip.Location = new System.Drawing.Point(0, 11); + this.stackStrip.Name = "stackStrip"; + this.stackStrip.Padding = new System.Windows.Forms.Padding(0, 7, 0, 0); + this.stackStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; + this.stackStrip.Size = new System.Drawing.Size(150, 139); + this.stackStrip.TabIndex = 0; + this.stackStrip.Text = "toolStrip1"; + // + // mailStackButton + // + this.mailStackButton.CheckOnClick = true; + this.mailStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.mailStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; + this.mailStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(238)))), ((int)(((byte)(238)))), ((int)(((byte)(238))))); + this.mailStackButton.Margin = new System.Windows.Forms.Padding(0); + this.mailStackButton.Name = "mailStackButton"; + this.mailStackButton.Padding = new System.Windows.Forms.Padding(3); + this.mailStackButton.Size = new System.Drawing.Size(149, 27); + this.mailStackButton.Text = " Mail"; + this.mailStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.mailStackButton.Click += new System.EventHandler(this.stackButton_Click); + // + // calendarStackButton + // + this.calendarStackButton.CheckOnClick = true; + this.calendarStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.calendarStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; + this.calendarStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(238)))), ((int)(((byte)(238)))), ((int)(((byte)(238))))); + this.calendarStackButton.Margin = new System.Windows.Forms.Padding(0); + this.calendarStackButton.Name = "calendarStackButton"; + this.calendarStackButton.Padding = new System.Windows.Forms.Padding(3); + this.calendarStackButton.Size = new System.Drawing.Size(149, 27); + this.calendarStackButton.Text = " Calendar"; + this.calendarStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.calendarStackButton.Click += new System.EventHandler(this.stackButton_Click); + // + // contactsStackButton + // + this.contactsStackButton.CheckOnClick = true; + this.contactsStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.contactsStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; + this.contactsStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(238)))), ((int)(((byte)(238)))), ((int)(((byte)(238))))); + this.contactsStackButton.Margin = new System.Windows.Forms.Padding(0); + this.contactsStackButton.Name = "contactsStackButton"; + this.contactsStackButton.Padding = new System.Windows.Forms.Padding(3); + this.contactsStackButton.Size = new System.Drawing.Size(149, 27); + this.contactsStackButton.Text = " Contacts"; + this.contactsStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.contactsStackButton.Click += new System.EventHandler(this.stackButton_Click); + // + // tasksStackButton + // + this.tasksStackButton.CheckOnClick = true; + this.tasksStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.tasksStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; + this.tasksStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(238)))), ((int)(((byte)(238)))), ((int)(((byte)(238))))); + this.tasksStackButton.Margin = new System.Windows.Forms.Padding(0); + this.tasksStackButton.Name = "tasksStackButton"; + this.tasksStackButton.Padding = new System.Windows.Forms.Padding(3); + this.tasksStackButton.Size = new System.Drawing.Size(149, 27); + this.tasksStackButton.Text = " Tasks"; + this.tasksStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.tasksStackButton.Click += new System.EventHandler(this.stackButton_Click); + // + // StackView + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.stackStrip); + this.Name = "StackView"; + this.Load += new System.EventHandler(this.StackView_Load); + this.stackStrip.ResumeLayout(false); + this.stackStrip.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/CS/Form1.cs new file mode 100644 index 0000000000..9738f298e9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/CS/Form1.cs @@ -0,0 +1,422 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace StandardMenuFormCS +{ + public class Form1 : Form + { + private StatusStrip statusStrip1; + private ToolStripStatusLabel toolStripStatusLabel1; + + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + public Form1() + { + InitializeComponent(); + } + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + // + // This utility method assigns the value of a ToolStripItem + // control's Text property to the Text property of the + // ToolStripStatusLabel. + private void UpdateStatus(ToolStripItem item) + { + if (item != null) + { + string msg = String.Format("{0} selected", item.Text); + this.statusStrip1.Items[0].Text = msg; + } + } + // + + // + // This method is the DropDownItemClicked event handler. + // It passes the ClickedItem object to a utility method + // called UpdateStatus, which updates the text displayed + // in the StatusStrip control. + private void fileToolStripMenuItem_DropDownItemClicked( + object sender, ToolStripItemClickedEventArgs e) + { + this.UpdateStatus(e.ClickedItem); + } + // + + #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() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); + this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); + this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); + this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); + this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); + this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); + this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.menuStrip1.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.fileToolStripMenuItem, + this.editToolStripMenuItem, + this.toolsToolStripMenuItem, + this.helpToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(292, 24); + this.menuStrip1.TabIndex = 0; + this.menuStrip1.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.newToolStripMenuItem, + this.openToolStripMenuItem, + this.toolStripSeparator, + this.saveToolStripMenuItem, + this.saveAsToolStripMenuItem, + this.toolStripSeparator1, + this.printToolStripMenuItem, + this.printPreviewToolStripMenuItem, + this.toolStripSeparator2, + this.exitToolStripMenuItem}); + this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); + this.fileToolStripMenuItem.Text = "&File"; + this.fileToolStripMenuItem.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.fileToolStripMenuItem_DropDownItemClicked); + // + // newToolStripMenuItem + // + this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image"))); + this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.newToolStripMenuItem.Name = "newToolStripMenuItem"; + this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); + this.newToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.newToolStripMenuItem.Text = "&New"; + // + // openToolStripMenuItem + // + this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image"))); + this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.openToolStripMenuItem.Name = "openToolStripMenuItem"; + this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); + this.openToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.openToolStripMenuItem.Text = "&Open"; + // + // toolStripSeparator + // + this.toolStripSeparator.Name = "toolStripSeparator"; + this.toolStripSeparator.Size = new System.Drawing.Size(149, 6); + // + // saveToolStripMenuItem + // + this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image"))); + this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); + this.saveToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.saveToolStripMenuItem.Text = "&Save"; + // + // saveAsToolStripMenuItem + // + this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; + this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.saveAsToolStripMenuItem.Text = "Save &As"; + // + // toolStripSeparator1 + // + this.toolStripSeparator1.Name = "toolStripSeparator1"; + this.toolStripSeparator1.Size = new System.Drawing.Size(149, 6); + // + // printToolStripMenuItem + // + this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image"))); + this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.printToolStripMenuItem.Name = "printToolStripMenuItem"; + this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P))); + this.printToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.printToolStripMenuItem.Text = "&Print"; + // + // printPreviewToolStripMenuItem + // + this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image"))); + this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem"; + this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.printPreviewToolStripMenuItem.Text = "Print Pre&view"; + // + // toolStripSeparator2 + // + this.toolStripSeparator2.Name = "toolStripSeparator2"; + this.toolStripSeparator2.Size = new System.Drawing.Size(149, 6); + // + // exitToolStripMenuItem + // + this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; + this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.exitToolStripMenuItem.Text = "E&xit"; + // + // editToolStripMenuItem + // + this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.undoToolStripMenuItem, + this.redoToolStripMenuItem, + this.toolStripSeparator3, + this.cutToolStripMenuItem, + this.copyToolStripMenuItem, + this.pasteToolStripMenuItem, + this.toolStripSeparator4, + this.selectAllToolStripMenuItem}); + this.editToolStripMenuItem.Name = "editToolStripMenuItem"; + this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20); + this.editToolStripMenuItem.Text = "&Edit"; + // + // undoToolStripMenuItem + // + this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; + this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z))); + this.undoToolStripMenuItem.Size = new System.Drawing.Size(150, 22); + this.undoToolStripMenuItem.Text = "&Undo"; + // + // redoToolStripMenuItem + // + this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; + this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y))); + this.redoToolStripMenuItem.Size = new System.Drawing.Size(150, 22); + this.redoToolStripMenuItem.Text = "&Redo"; + // + // toolStripSeparator3 + // + this.toolStripSeparator3.Name = "toolStripSeparator3"; + this.toolStripSeparator3.Size = new System.Drawing.Size(147, 6); + // + // cutToolStripMenuItem + // + this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image"))); + this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; + this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X))); + this.cutToolStripMenuItem.Size = new System.Drawing.Size(150, 22); + this.cutToolStripMenuItem.Text = "Cu&t"; + // + // copyToolStripMenuItem + // + this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image"))); + this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; + this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); + this.copyToolStripMenuItem.Size = new System.Drawing.Size(150, 22); + this.copyToolStripMenuItem.Text = "&Copy"; + // + // pasteToolStripMenuItem + // + this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image"))); + this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; + this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; + this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V))); + this.pasteToolStripMenuItem.Size = new System.Drawing.Size(150, 22); + this.pasteToolStripMenuItem.Text = "&Paste"; + // + // toolStripSeparator4 + // + this.toolStripSeparator4.Name = "toolStripSeparator4"; + this.toolStripSeparator4.Size = new System.Drawing.Size(147, 6); + // + // selectAllToolStripMenuItem + // + this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem"; + this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(150, 22); + this.selectAllToolStripMenuItem.Text = "Select &All"; + // + // toolsToolStripMenuItem + // + this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.customizeToolStripMenuItem, + this.optionsToolStripMenuItem}); + this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; + this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20); + this.toolsToolStripMenuItem.Text = "&Tools"; + // + // customizeToolStripMenuItem + // + this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem"; + this.customizeToolStripMenuItem.Size = new System.Drawing.Size(134, 22); + this.customizeToolStripMenuItem.Text = "&Customize"; + // + // optionsToolStripMenuItem + // + this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; + this.optionsToolStripMenuItem.Size = new System.Drawing.Size(134, 22); + this.optionsToolStripMenuItem.Text = "&Options"; + // + // helpToolStripMenuItem + // + this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.contentsToolStripMenuItem, + this.indexToolStripMenuItem, + this.searchToolStripMenuItem, + this.toolStripSeparator5, + this.aboutToolStripMenuItem}); + this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; + this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); + this.helpToolStripMenuItem.Text = "&Help"; + // + // contentsToolStripMenuItem + // + this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem"; + this.contentsToolStripMenuItem.Size = new System.Drawing.Size(129, 22); + this.contentsToolStripMenuItem.Text = "&Contents"; + // + // indexToolStripMenuItem + // + this.indexToolStripMenuItem.Name = "indexToolStripMenuItem"; + this.indexToolStripMenuItem.Size = new System.Drawing.Size(129, 22); + this.indexToolStripMenuItem.Text = "&Index"; + // + // searchToolStripMenuItem + // + this.searchToolStripMenuItem.Name = "searchToolStripMenuItem"; + this.searchToolStripMenuItem.Size = new System.Drawing.Size(129, 22); + this.searchToolStripMenuItem.Text = "&Search"; + // + // toolStripSeparator5 + // + this.toolStripSeparator5.Name = "toolStripSeparator5"; + this.toolStripSeparator5.Size = new System.Drawing.Size(126, 6); + // + // aboutToolStripMenuItem + // + this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; + this.aboutToolStripMenuItem.Size = new System.Drawing.Size(129, 22); + this.aboutToolStripMenuItem.Text = "&About..."; + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel1}); + this.statusStrip1.Location = new System.Drawing.Point(0, 251); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Size = new System.Drawing.Size(292, 22); + this.statusStrip1.TabIndex = 1; + this.statusStrip1.Text = "statusStrip1"; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + this.toolStripStatusLabel1.Size = new System.Drawing.Size(109, 17); + this.toolStripStatusLabel1.Text = "toolStripStatusLabel1"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(292, 273); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.menuStrip1); + this.MainMenuStrip = this.menuStrip1; + this.Name = "Form1"; + this.Text = "Form1"; + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator; + private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; + private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; + private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; + private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; + private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; + private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; + } + + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/CS/Form1.cs new file mode 100644 index 0000000000..582e14ced7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/CS/Form1.cs @@ -0,0 +1,34 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +public class Form1 : Form +{ + private ToolStripContainer tsc; + private RichTextBox rtb; + + public Form1() + { + InitializeComponent(); + } +[STAThread] +static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + this.tsc = new System.Windows.Forms.ToolStripContainer(); + this.rtb = new System.Windows.Forms.RichTextBox(); + this.tsc.ContentPanel.Controls.Add(this.rtb); + this.Controls.Add(this.tsc); + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs new file mode 100644 index 0000000000..f4ea207c4e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/CS/form1.cs @@ -0,0 +1,247 @@ +using System; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; +using System.Data; + +namespace System.Windows.Forms.ToolStripControlHostExample +{ + public partial class Form1 : System.Windows.Forms.Form + { + private System.ComponentModel.IContainer components = null; + private ToolStripTextBox textbox1; + public Form1() + { + InitializeComponent(); + InitializeDropDownMonthCalendar(); + textbox1 = new ToolStripTextBox(); + textbox1.Width = 70; + toolStrip1.Items.Add(textbox1); + InitializeDateTimePickerHost(); + } + static void Main() + { + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + this.toolStrip1 = new System.Windows.Forms.ToolStrip(); + this.ToolStripPanel1 = new System.Windows.Forms.ToolStripPanel(); + this.SuspendLayout(); +// +// toolStrip1 +// + this.toolStrip1.Anchor = System.Windows.Forms.AnchorStyles.Right; + this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; + this.toolStrip1.Location = new System.Drawing.Point(0, 0); + this.toolStrip1.Name = "toolStrip1"; + this.toolStrip1.TabIndex = 1; + this.toolStrip1.Text = "toolStrip1"; + this.toolStrip1.Visible = true; +// +// ToolStripPanel1 +// + this.ToolStripPanel1.AutoSize = true; + this.ToolStripPanel1.Dock = System.Windows.Forms.DockStyle.Top; + this.ToolStripPanel1.Location = new System.Drawing.Point(9, 9); + this.ToolStripPanel1.Name = "ToolStripPanel1"; + this.ToolStripPanel1.Orientation = System.Windows.Forms.Orientation.Horizontal; + this.ToolStripPanel1.RowMargin = new System.Windows.Forms.Padding(0); + this.ToolStripPanel1.Size = new System.Drawing.Size(274, 25); + this.ToolStripPanel1.TabIndex = 0; + this.ToolStripPanel1.Text = "ToolStripPanelToolStripPanelTop"; + this.ToolStripPanel1.Join(this.toolStrip1); +// +// Form1 +// + this.AutoSize = true; + this.ClientSize = new System.Drawing.Size(292, 266); + this.Controls.Add(this.ToolStripPanel1); + this.Name = "Form1"; + this.Padding = new System.Windows.Forms.Padding(9); + this.Text = "Form1"; + this.ResumeLayout(false); + this.PerformLayout(); + } + + /// + /// Clean up any resources being used. + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (components != null) + { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + private System.Windows.Forms.ToolStrip toolStrip1; + private System.Windows.Forms.ToolStripPanel ToolStripPanel1; + + // The following snippet demonstrates the ToolStripControlHost(Control) + // constructor, the ToolStripControlHost.Font, Width, DisplayStyle, + // Text properties. + // + ToolStripControlHost dateTimePickerHost; + + private void InitializeDateTimePickerHost() + { + + // Create a new ToolStripControlHost, passing in a control. + dateTimePickerHost = new ToolStripControlHost(new DateTimePicker()); + + // Set the font on the ToolStripControlHost, this will affect the hosted control. + dateTimePickerHost.Font = new Font("Arial", 7.0F, FontStyle.Italic); + + // Set the Width property, this will also affect the hosted control. + dateTimePickerHost.Width = 100; + dateTimePickerHost.DisplayStyle = ToolStripItemDisplayStyle.Text; + + // Setting the Text property requires a string that converts to a + // DateTime type since that is what the hosted control requires. + dateTimePickerHost.Text = "12/23/2005"; + + // Cast the Control property back to the original type to set a + // type-specific property. + ((DateTimePicker)dateTimePickerHost.Control).Format = DateTimePickerFormat.Short; + + // Add the control host to the ToolStrip. + toolStrip1.Items.Add(dateTimePickerHost); + } + // + + // The following example shows how to set the custom + // ToolStripMonthCalendar control. + // + private void InitializeDropDownMonthCalendar() + { + // Declare the drop-down button and the drop-down. + ToolStripDropDownButton dropDownButton2 = new ToolStripDropDownButton(); + + // Set the image to the MonthCalendar embedded bitmap + // image. + dropDownButton2.Image = new Bitmap(typeof(MonthCalendar), "MonthCalendar.bmp"); + + // Add the button to the ToolStrip. + toolStrip1.Items.Add(dropDownButton2); + + // Construct a new drop-down. + ToolStripDropDown dropDown = new ToolStripDropDown(); + + // Construct a new wrapped MonthCalendar control. + ToolStripMonthCalendar monthCalendar = new ToolStripMonthCalendar(); + + // Set a date in boldface. + monthCalendar.AddBoldedDate(DateTime.Today.AddDays(7)); + + // Handle the DateChanged event. + monthCalendar.DateChanged += new DateRangeEventHandler(monthCalendar_DateChanged); + + //Add the calendar to the drop-down. + dropDown.Items.Add(monthCalendar); + + //Set the drop-down on the DropDownButton. + dropDownButton2.DropDown = dropDown; + } + + private void monthCalendar_DateChanged(object sender, DateRangeEventArgs e) + { + textbox1.Text = e.Start.ToShortDateString(); + } + // + } + + // The following example shows how to wrap a control + // using ToolStripControlHost. + // + //Declare a class that inherits from ToolStripControlHost. + public class ToolStripMonthCalendar : ToolStripControlHost + { + // + // Call the base constructor passing in a MonthCalendar instance. + public ToolStripMonthCalendar() : base (new MonthCalendar()) { } + // + + // + public MonthCalendar MonthCalendarControl + { + get + { + return Control as MonthCalendar; + } + } + // + + // + // Expose the MonthCalendar.FirstDayOfWeek as a property. + public Day FirstDayOfWeek + { + get + { + return MonthCalendarControl.FirstDayOfWeek; + } + set { MonthCalendarControl.FirstDayOfWeek = value; } + } + + // Expose the AddBoldedDate method. + public void AddBoldedDate(DateTime dateToBold) + { + MonthCalendarControl.AddBoldedDate(dateToBold); + } + // + + // Subscribe and unsubscribe the control events you wish to expose. + // + // + protected override void OnSubscribeControlEvents(Control c) + { + // Call the base so the base events are connected. + base.OnSubscribeControlEvents(c); + + // Cast the control to a MonthCalendar control. + MonthCalendar monthCalendarControl = (MonthCalendar) c; + + // Add the event. + monthCalendarControl.DateChanged += + new DateRangeEventHandler(OnDateChanged); + } + // + + // + protected override void OnUnsubscribeControlEvents(Control c) + { + // Call the base method so the basic events are unsubscribed. + base.OnUnsubscribeControlEvents(c); + + // Cast the control to a MonthCalendar control. + MonthCalendar monthCalendarControl = (MonthCalendar) c; + + // Remove the event. + monthCalendarControl.DateChanged -= + new DateRangeEventHandler(OnDateChanged); + } + // + // + + // + // Declare the DateChanged event. + public event DateRangeEventHandler DateChanged; + + // Raise the DateChanged event. + private void OnDateChanged(object sender, DateRangeEventArgs e) + { + if (DateChanged != null) + { + DateChanged(this, e); + } + } + // + } + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/CS/form1.cs new file mode 100644 index 0000000000..50f6e208eb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/CS/form1.cs @@ -0,0 +1,699 @@ +// User Input Test Application for new Windows Forms user input conceptual topics +// in Visual Studio 2005 documentation. + +// +using System; +using System.Drawing; +using System.ComponentModel; +using System.Windows.Forms; + +namespace UserInputWalkthrough +{ + public class Form1 : Form + { + Label Label1 = new Label(); + Label Label2 = new Label(); + TextBox TextBoxOutput = new TextBox(); + TextBox TextBoxInput = new TextBox(); + GroupBox GroupBoxEvents = new GroupBox(); + Button ButtonClear = new Button(); + LinkLabel LinkLabelDrag = new LinkLabel(); + + CheckBox CheckBoxToggleAll = new CheckBox(); + CheckBox CheckBoxMouse = new CheckBox(); + CheckBox CheckBoxMouseEnter = new CheckBox(); + CheckBox CheckBoxMouseMove = new CheckBox(); + CheckBox CheckBoxMousePoints = new CheckBox(); + CheckBox CheckBoxMouseDrag = new CheckBox(); + CheckBox CheckBoxMouseDragOver = new CheckBox(); + CheckBox CheckBoxKeyboard = new CheckBox(); + CheckBox CheckBoxKeyUpDown = new CheckBox(); + CheckBox CheckBoxFocus = new CheckBox(); + CheckBox CheckBoxValidation = new CheckBox(); + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + : base() + { + this.Load += new EventHandler(Form1_Load); + } + + private void Form1_Load(object sender, EventArgs e) + { + this.GroupBoxEvents.SuspendLayout(); + this.SuspendLayout(); + + Label1.Location = new Point(232, 12); + Label1.Size = new Size(98, 14); + Label1.AutoSize = true; + Label1.Text = "Generated Events:"; + + Label2.Location = new Point(13, 12); + Label2.Size = new Size(95, 14); + Label2.AutoSize = true; + Label2.Text = "User Input Target:"; + + TextBoxInput.Location = new Point(13, 34); + TextBoxInput.Size = new Size(200, 200); + TextBoxInput.AllowDrop = true; + TextBoxInput.AutoSize = false; + TextBoxInput.Cursor = Cursors.Cross; + TextBoxInput.Multiline = true; + TextBoxInput.TabIndex = 1; + + LinkLabelDrag.AllowDrop = true; + LinkLabelDrag.AutoSize = true; + LinkLabelDrag.Location = new Point(13, 240); + LinkLabelDrag.Size = new Size(175, 14); + LinkLabelDrag.TabIndex = 2; + LinkLabelDrag.TabStop = true; + LinkLabelDrag.Text = "Click here to use as a drag source"; + LinkLabelDrag.Links.Add(new LinkLabel.Link(0, + LinkLabelDrag.Text.Length)); + + GroupBoxEvents.Location = new Point(13, 281); + GroupBoxEvents.Size = new Size(200, 302); + GroupBoxEvents.Text = "Event Filter:"; + GroupBoxEvents.TabStop = true; + GroupBoxEvents.TabIndex = 3; + GroupBoxEvents.Controls.Add(CheckBoxMouseEnter); + GroupBoxEvents.Controls.Add(CheckBoxToggleAll); + GroupBoxEvents.Controls.Add(CheckBoxMousePoints); + GroupBoxEvents.Controls.Add(CheckBoxKeyUpDown); + GroupBoxEvents.Controls.Add(CheckBoxMouseDragOver); + GroupBoxEvents.Controls.Add(CheckBoxMouseDrag); + GroupBoxEvents.Controls.Add(CheckBoxValidation); + GroupBoxEvents.Controls.Add(CheckBoxMouseMove); + GroupBoxEvents.Controls.Add(CheckBoxFocus); + GroupBoxEvents.Controls.Add(CheckBoxKeyboard); + GroupBoxEvents.Controls.Add(CheckBoxMouse); + + CheckBoxToggleAll.AutoSize = true; + CheckBoxToggleAll.Location = new Point(7, 20); + CheckBoxToggleAll.Size = new Size(122, 17); + CheckBoxToggleAll.TabIndex = 4; + CheckBoxToggleAll.Text = "Toggle All Events"; + + CheckBoxMouse.AutoSize = true; + CheckBoxMouse.Location = new Point(7, 45); + CheckBoxMouse.Size = new Size(137, 17); + CheckBoxMouse.TabIndex = 5; + CheckBoxMouse.Text = "Mouse and Click Events"; + + CheckBoxMouseEnter.AutoSize = true; + CheckBoxMouseEnter.Location = new Point(26, 69); + CheckBoxMouseEnter.Margin = new Padding(3, 3, 3, 1); + CheckBoxMouseEnter.Size = new System.Drawing.Size(151, 17); + CheckBoxMouseEnter.TabIndex = 6; + CheckBoxMouseEnter.Text = "Mouse Enter/Hover/Leave"; + + CheckBoxMouseMove.AutoSize = true; + CheckBoxMouseMove.Location = new Point(26, 89); + CheckBoxMouseMove.Margin = new Padding(3, 2, 3, 3); + CheckBoxMouseMove.Size = new Size(120, 17); + CheckBoxMouseMove.TabIndex = 7; + CheckBoxMouseMove.Text = "Mouse Move Events"; + + CheckBoxMousePoints.AutoSize = true; + CheckBoxMousePoints.Location = new Point(26, 112); + CheckBoxMousePoints.Margin = new Padding(3, 3, 3, 1); + CheckBoxMousePoints.Size = new Size(141, 17); + CheckBoxMousePoints.TabIndex = 8; + CheckBoxMousePoints.Text = "Draw Mouse Points"; + + CheckBoxMouseDrag.AutoSize = true; + CheckBoxMouseDrag.Location = new Point(26, 135); + CheckBoxMouseDrag.Margin = new Padding(3, 1, 3, 3); + CheckBoxMouseDrag.Size = new Size(151, 17); + CheckBoxMouseDrag.TabIndex = 9; + CheckBoxMouseDrag.Text = "Mouse Drag && Drop Events"; + + CheckBoxMouseDragOver.AutoSize = true; + CheckBoxMouseDragOver.Location = new Point(44, 159); + CheckBoxMouseDragOver.Size = new Size(142, 17); + CheckBoxMouseDragOver.TabIndex = 10; + CheckBoxMouseDragOver.Text = "Mouse Drag Over Events"; + + CheckBoxKeyboard.AutoSize = true; + CheckBoxKeyboard.Location = new Point(8, 184); + CheckBoxKeyboard.Size = new Size(103, 17); + CheckBoxKeyboard.TabIndex = 11; + CheckBoxKeyboard.Text = "Keyboard Events"; + + CheckBoxKeyUpDown.AutoSize = true; + CheckBoxKeyUpDown.Location = new Point(26, 207); + CheckBoxKeyUpDown.Margin = new Padding(3, 3, 3, 1); + CheckBoxKeyUpDown.Size = new Size(133, 17); + CheckBoxKeyUpDown.TabIndex = 12; + CheckBoxKeyUpDown.Text = "Key Up && Down Events"; + + CheckBoxFocus.AutoSize = true; + CheckBoxFocus.Location = new Point(8, 233); + CheckBoxFocus.Margin = new Padding(3, 2, 3, 3); + CheckBoxFocus.Size = new Size(146, 17); + CheckBoxFocus.TabIndex = 13; + CheckBoxFocus.Text = "Focus && Activation Events"; + + CheckBoxValidation.AutoSize = true; + CheckBoxValidation.Location = new Point(8, 257); + CheckBoxValidation.Size = new Size(104, 17); + CheckBoxValidation.TabIndex = 14; + CheckBoxValidation.Text = "Validation Events"; + + TextBoxOutput.Location = new Point(232, 34); + TextBoxOutput.Size = new Size(308, 510); + TextBoxOutput.Multiline = true; + TextBoxOutput.CausesValidation = false; + TextBoxOutput.ReadOnly = true; + TextBoxOutput.ScrollBars = ScrollBars.Vertical; + TextBoxOutput.TabIndex = 15; + TextBoxOutput.WordWrap = false; + + ButtonClear.Location = new Point(232, 560); + ButtonClear.Size = new Size(308, 23); + ButtonClear.TabIndex = 16; + ButtonClear.Text = "Clear Event List"; + + this.ClientSize = new Size(552, 595); + this.Controls.Add(LinkLabelDrag); + this.Controls.Add(ButtonClear); + this.Controls.Add(GroupBoxEvents); + this.Controls.Add(Label1); + this.Controls.Add(Label2); + this.Controls.Add(TextBoxInput); + this.Controls.Add(TextBoxOutput); + this.Text = "User Input Events"; + + ButtonClear.Click += + new EventHandler(ButtonClear_Click); + TextBoxInput.KeyDown += + new KeyEventHandler(TextBoxInput_KeyDown); + TextBoxInput.KeyPress += + new KeyPressEventHandler(TextBoxInput_KeyPress); + TextBoxInput.KeyUp += + new KeyEventHandler(TextBoxInput_KeyUp); + TextBoxInput.Click += + new EventHandler(TextBoxInput_Click); + TextBoxInput.DoubleClick += + new EventHandler(TextBoxInput_DoubleClick); + TextBoxInput.MouseClick += + new MouseEventHandler(TextBoxInput_MouseClick); + TextBoxInput.MouseDoubleClick += + new MouseEventHandler(TextBoxInput_MouseDoubleClick); + TextBoxInput.MouseDown += + new MouseEventHandler(TextBoxInput_MouseDown); + TextBoxInput.MouseUp += + new MouseEventHandler(TextBoxInput_MouseUp); + TextBoxInput.MouseEnter += + new EventHandler(TextBoxInput_MouseEnter); + TextBoxInput.MouseHover += + new EventHandler(TextBoxInput_MouseHover); + TextBoxInput.MouseLeave += + new EventHandler(TextBoxInput_MouseLeave); + TextBoxInput.MouseWheel += + new MouseEventHandler(TextBoxInput_MouseWheel); + TextBoxInput.MouseMove += + new MouseEventHandler(TextBoxInput_MouseMove); + TextBoxInput.MouseCaptureChanged += + new EventHandler(TextBoxInput_MouseCaptureChanged); + TextBoxInput.DragEnter += + new DragEventHandler(TextBoxInput_DragEnter); + TextBoxInput.DragDrop += + new DragEventHandler(TextBoxInput_DragDrop); + TextBoxInput.DragOver += + new DragEventHandler(TextBoxInput_DragOver); + TextBoxInput.DragLeave += + new EventHandler(TextBoxInput_DragLeave); + TextBoxInput.Enter += + new EventHandler(TextBoxInput_Enter); + TextBoxInput.Leave += + new EventHandler(TextBoxInput_Leave); + TextBoxInput.GotFocus += + new EventHandler(TextBoxInput_GotFocus); + TextBoxInput.LostFocus += + new EventHandler(TextBoxInput_LostFocus); + TextBoxInput.Validated += + new EventHandler(TextBoxInput_Validated); + TextBoxInput.Validating += + new CancelEventHandler(TextBoxInput_Validating); + + LinkLabelDrag.MouseDown += + new MouseEventHandler(LinkLabelDrag_MouseDown); + LinkLabelDrag.GiveFeedback += + new GiveFeedbackEventHandler(LinkLabelDrag_GiveFeedback); + + CheckBoxToggleAll.CheckedChanged += + new EventHandler(CheckBoxToggleAll_CheckedChanged); + CheckBoxMouse.CheckedChanged += + new EventHandler(CheckBoxMouse_CheckedChanged); + CheckBoxMouseDrag.CheckedChanged += + new EventHandler(CheckBoxMouseDrag_CheckedChanged); + CheckBoxMouseEnter.CheckedChanged += + new EventHandler(CheckBoxMouseMove_CheckedChanged); + CheckBoxMouseMove.CheckedChanged += + new EventHandler(CheckBoxMouseMove_CheckedChanged); + CheckBoxKeyboard.CheckedChanged += + new EventHandler(CheckBoxKeyboard_CheckedChanged); + + this.GroupBoxEvents.ResumeLayout(false); + this.GroupBoxEvents.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + CheckAllChildCheckBoxes(this, true); + } + + // Recursively search the form for all contained checkboxes and + // initially check them + private void CheckAllChildCheckBoxes(Control parent, bool value) + { + CheckBox box; + foreach (Control currentControl in parent.Controls) + { + if (currentControl is CheckBox) + { + box = (CheckBox)currentControl; + box.Checked = value; + } + + // Recurse if control contains other controls + if (currentControl.Controls.Count > 0) + { + CheckAllChildCheckBoxes(currentControl, value); + } + } + } + + // All-purpose method for displaying a line of text in one of the + // text boxes. + private void DisplayLine(string line) + { + TextBoxOutput.AppendText(line); + TextBoxOutput.AppendText(Environment.NewLine); + } + + // Click event handler for the button that clears the text box. + private void ButtonClear_Click(object sender, EventArgs e) + { + TextBoxOutput.Invalidate(); + TextBoxOutput.Clear(); + } + + private void TextBoxInput_KeyDown(object sender, KeyEventArgs e) + { + if (CheckBoxKeyUpDown.Checked) + { + DisplayLine("KeyDown: " + e.KeyData.ToString()); + } + } + + private void TextBoxInput_KeyUp(object sender, KeyEventArgs e) + { + if (CheckBoxKeyUpDown.Checked) + { + DisplayLine("KeyUp: " + e.KeyData.ToString()); + } + } + + private void TextBoxInput_KeyPress(object sender, + KeyPressEventArgs e) + { + if (CheckBoxKeyboard.Checked) + { + if (Char.IsWhiteSpace(e.KeyChar)) + { + DisplayLine("KeyPress: WS"); + } + else + { + DisplayLine("KeyPress: " + e.KeyChar.ToString()); + } + } + } + + private void TextBoxInput_Click(object sender, EventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("Click event"); + } + } + + private void TextBoxInput_DoubleClick(object sender, EventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("DoubleClick event"); + } + } + + private void TextBoxInput_MouseClick(object sender, MouseEventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("MouseClick: " + e.Button.ToString() + + " " + e.Location.ToString()); + } + } + + private void TextBoxInput_MouseDoubleClick(object sender, + MouseEventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("MouseDoubleClick: " + e.Button.ToString() + + " " + e.Location.ToString()); + } + } + + private void TextBoxInput_MouseDown(object sender, + MouseEventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("MouseDown: " + e.Button.ToString() + + " " + e.Location.ToString()); + } + } + + private void TextBoxInput_MouseUp(object sender, + MouseEventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("MouseUp: " + e.Button.ToString() + + " " + e.Location.ToString()); + } + + // The TextBox control was designed to change focus only on + // the primary click, so force focus to avoid user confusion. + if (!TextBoxInput.Focused) + { + TextBoxInput.Focus(); + } + } + + private void TextBoxInput_MouseEnter(object sender, EventArgs e) + { + if (CheckBoxMouseEnter.Checked) + { + DisplayLine("MouseEnter event"); + } + } + + private void TextBoxInput_MouseHover(object sender, EventArgs e) + { + if (CheckBoxMouseEnter.Checked) + { + DisplayLine("MouseHover event"); + } + } + + private void TextBoxInput_MouseLeave(object sender, EventArgs e) + { + if (CheckBoxMouseEnter.Checked) + { + DisplayLine("MouseLeave event"); + } + } + + private void TextBoxInput_MouseWheel(object sender, + MouseEventArgs e) + { + if (CheckBoxMouse.Checked) + { + DisplayLine("MouseWheel: " + e.Delta.ToString() + + " detents at " + e.Location.ToString()); + } + } + + private void TextBoxInput_MouseMove(object sender, + MouseEventArgs e) + { + if (CheckBoxMouseMove.Checked) + { + DisplayLine("MouseMove: " + e.Button.ToString() + " " + + e.Location.ToString()); + } + + if (CheckBoxMousePoints.Checked) + { + Graphics g = TextBoxInput.CreateGraphics(); + g.FillRectangle(Brushes.Black, e.Location.X, + e.Location.Y, 1, 1); + g.Dispose(); + } + } + + private void TextBoxInput_MouseCaptureChanged(object sender, + EventArgs e) + { + if (CheckBoxMouseDrag.Checked) + { + DisplayLine("MouseCaptureChanged event"); + } + } + + private void TextBoxInput_DragEnter(object sender, + DragEventArgs e) + { + if (CheckBoxMouseDrag.Checked) + { + Point pt = new Point(e.X, e.Y); + DisplayLine("DragEnter: " + + CovertKeyStateToString(e.KeyState) + + " at " + pt.ToString()); + } + } + + private void TextBoxInput_DragDrop(object sender, + DragEventArgs e) + { + if (CheckBoxMouseDrag.Checked) + { + Point pt = new Point(e.X, e.Y); + DisplayLine("DragDrop: " + + CovertKeyStateToString(e.KeyState) + + " at " + pt.ToString()); + } + } + + private void TextBoxInput_DragOver(object sender, + DragEventArgs e) + { + if (CheckBoxMouseDragOver.Checked) + { + Point pt = new Point(e.X, e.Y); + DisplayLine("DragOver: " + + CovertKeyStateToString(e.KeyState) + + " at " + pt.ToString()); + } + + // Allow if drop data is of type string. + if (!e.Data.GetDataPresent(typeof(String))) + { + e.Effect = DragDropEffects.None; + } + else + { + e.Effect = DragDropEffects.Copy; + } + } + + private void TextBoxInput_DragLeave(object sender, + EventArgs e) + { + if (CheckBoxMouseDrag.Checked) + { + DisplayLine("DragLeave event"); + } + } + + private string CovertKeyStateToString(int keyState) + { + string keyString = "None"; + + // Which button was pressed? + if ((keyState & 1) == 1) + { + keyString = "Left"; + } + else if ((keyState & 2) == 2) + { + keyString = "Right"; + } + else if ((keyState & 16) == 16) + { + keyString = "Middle"; + } + + // Are one or more modifier keys also pressed? + if ((keyState & 4) == 4) + { + keyString += "+SHIFT"; + } + + if ((keyState & 8) == 8) + { + keyString += "+CTRL"; + } + + if ((keyState & 32) == 32) + { + keyString += "+ALT"; + } + + return keyString; + } + + private void TextBoxInput_Enter(object sender, EventArgs e) + { + if (CheckBoxFocus.Checked) + { + DisplayLine("Enter event"); + } + } + + private void TextBoxInput_Leave(object sender, EventArgs e) + { + if (CheckBoxFocus.Checked) + { + DisplayLine("Leave event"); + } + } + + private void TextBoxInput_GotFocus(object sender, EventArgs e) + { + if (CheckBoxFocus.Checked) + { + DisplayLine("GotFocus event"); + } + } + + private void TextBoxInput_LostFocus(object sender, EventArgs e) + { + if (CheckBoxFocus.Checked) + { + DisplayLine("LostFocus event"); + } + } + + private void TextBoxInput_Validated(object sender, EventArgs e) + { + if (CheckBoxValidation.Checked) + { + DisplayLine("Validated event"); + } + } + + private void TextBoxInput_Validating( + object sender, CancelEventArgs e) + { + if (CheckBoxValidation.Checked) + { + DisplayLine("Validating event"); + } + } + + private void CheckBoxToggleAll_CheckedChanged( + object sender, EventArgs e) + { + if (sender is CheckBox) + { + CheckAllChildCheckBoxes(this, ((CheckBox)sender).Checked); + } + } + + private void CheckBoxMouse_CheckedChanged( + object sender, EventArgs e) + { + ConfigureCheckBoxSettings(); + } + + private void CheckBoxMouseDrag_CheckedChanged( + object sender, EventArgs e) + { + ConfigureCheckBoxSettings(); + } + + private void CheckBoxKeyboard_CheckedChanged( + object sender, EventArgs e) + { + ConfigureCheckBoxSettings(); + } + + private void CheckBoxMouseMove_CheckedChanged( + object sender, EventArgs e) + { + ConfigureCheckBoxSettings(); + } + + // Reconcile dependencies between the check box + // selection choices. + private void ConfigureCheckBoxSettings() + { + // CheckBoxMouse is a top-level check box. + if (!CheckBoxMouse.Checked) + { + CheckBoxMouseEnter.Enabled = false; + CheckBoxMouseMove.Enabled = false; + CheckBoxMouseDrag.Enabled = false; + CheckBoxMouseDragOver.Enabled = false; + CheckBoxMousePoints.Enabled = false; + } + else + { + CheckBoxMouseEnter.Enabled = true; + CheckBoxMouseMove.Enabled = true; + CheckBoxMouseDrag.Enabled = true; + CheckBoxMousePoints.Enabled = true; + + // Enable children depending on the state of the parent. + if (!CheckBoxMouseDrag.Checked) + { + CheckBoxMouseDragOver.Enabled = false; + } + else + { + CheckBoxMouseDragOver.Enabled = true; + } + } + + if (!CheckBoxKeyboard.Checked) + { + CheckBoxKeyUpDown.Enabled = false; + } + else + { + CheckBoxKeyUpDown.Enabled = true; + } + } + + private void LinkLabelDrag_MouseDown(object sender, + MouseEventArgs e) + { + string data = "Sample Data"; + LinkLabelDrag.DoDragDrop(data, DragDropEffects.All); + } + + private void LinkLabelDrag_GiveFeedback(object sender, + GiveFeedbackEventArgs e) + { + if ((e.Effect & DragDropEffects.Copy) == + DragDropEffects.Copy) + { + LinkLabelDrag.Cursor = Cursors.HSplit; + } + else + { + LinkLabelDrag.Cursor = Cursors.Default; + } + } + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer/CS/form1.cs new file mode 100644 index 0000000000..c455336377 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer/CS/form1.cs @@ -0,0 +1,419 @@ +// This sample might go in a VisualStyleRenderer conceptual topic, or the VisualStyleRenderer +// class itself. The sample defines a custom control that imitates a window using VisualStyleElements +// for the window parts. It handles resizing and moving the window. + +// This sample uses the following VisualStyleRenderer members: +// Snippet10: VisualStyleRenderer.GetPartSize (with ThemeSizeType.True) +// Snippet10: VisualStyleRenderer.GetPoint (with PointProperty.Offset) +// Snippet20: VisualStyleRenderer.DrawBackground +// Snippet30: VisualStyleRenderer.GetBackgroundRegion +// Snippet40: VisualStyleRenderer.IsElementDefined +// Snippet40: VisualStyleRenderer(VisualStyleElement) constructor +// Snippet40: VisualStyleRenderer.SetParameters + +// Work Items: - Try to make HitTestBackground method work in MouseDown event handler. +// - Why does the offset value obtained for the close button make it draw a bit +// too far to the right? +// - Right now I'm hard-coding the height of the status bar rect to 22, which +// visual matches the standard Windows version. Doing GetPartSize on this +// part only returns a height of 15, which is way to short; is this a bug? + +// +using System; +using System.Text; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +namespace VisualStyleRendererSample +{ + class Form1 : Form + { + public Form1() + : base() + { + this.Size = new Size(800, 600); + this.Location = new Point(20, 20); + this.BackColor = Color.DarkGray; + WindowSimulation Window1 = new WindowSimulation(); + Controls.Add(Window1); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } + + public class WindowSimulation : Control + { + private Dictionary windowElements = + new Dictionary(); + private Dictionary elementRectangles = + new Dictionary(); + private VisualStyleRenderer renderer = null; + + private Point closeButtonOffset; + private Size gripperSize; + private Size closeButtonSize; + private bool isResizing = false; + private bool isMoving = false; + private bool isClosing = false; + private int captionHeight; + private int frameThickness; + private int statusHeight = 22; + private Point originalClick = new Point(); + private Point resizeOffset = new Point(); + + public WindowSimulation() + : base() + { + this.Location = new Point(50, 50); + this.Size = new Size(350, 300); + this.BackColor = Color.Azure; + this.DoubleBuffered = true; + this.MinimumSize = new Size(300, 200); + this.Font = SystemFonts.CaptionFont; + this.Text = "Simulated Window"; + + // Insert the VisualStyleElement objects into the Dictionary. + windowElements.Add("windowCaption", + VisualStyleElement.Window.Caption.Active); + windowElements.Add("windowBottom", + VisualStyleElement.Window.FrameBottom.Active); + windowElements.Add("windowLeft", + VisualStyleElement.Window.FrameLeft.Active); + windowElements.Add("windowRight", + VisualStyleElement.Window.FrameRight.Active); + windowElements.Add("windowClose", + VisualStyleElement.Window.CloseButton.Normal); + windowElements.Add("statusBar", + VisualStyleElement.Status.Bar.Normal); + windowElements.Add("statusGripper", + VisualStyleElement.Status.Gripper.Normal); + + // Get the sizes and location offsets for the window parts + // as specified by the visual style, and then use this + // information to calcualate the rectangles for each part. + GetPartDetails(); + CalculateRectangles(); + + this.MouseDown += + new MouseEventHandler(ImitationWindow_MouseDown); + this.MouseUp += + new MouseEventHandler(ImitationWindow_MouseUp); + this.MouseMove += + new MouseEventHandler(ImitationWindow_MouseMove); + } + + // + // Get the sizes and offsets for the window parts as specified + // by the visual style. + private void GetPartDetails() + { + // Do nothing further if visual styles are not enabled. + if (!Application.RenderWithVisualStyles) + { + return; + } + + using (Graphics g = this.CreateGraphics()) + { + // Get the size and offset of the close button. + if (SetRenderer(windowElements["windowClose"])) + { + closeButtonSize = + renderer.GetPartSize(g, ThemeSizeType.True); + closeButtonOffset = + renderer.GetPoint(PointProperty.Offset); + } + + // Get the height of the window caption. + if (SetRenderer(windowElements["windowCaption"])) + { + captionHeight = renderer.GetPartSize(g, + ThemeSizeType.True).Height; + } + + // Get the thickness of the left, bottom, + // and right window frame. + if (SetRenderer(windowElements["windowLeft"])) + { + frameThickness = renderer.GetPartSize(g, + ThemeSizeType.True).Width; + } + + // Get the size of the resizing gripper. + if (SetRenderer(windowElements["statusGripper"])) + { + gripperSize = renderer.GetPartSize(g, + ThemeSizeType.True); + } + } + } + // + + // Use the part metrics to determine the current size + // of the rectangles for all of the window parts. + private void CalculateRectangles() + { + int heightMinusFrame = + ClientRectangle.Height - frameThickness; + + // Calculate the window frame rectangles and add them + // to the Dictionary of rectangles. + elementRectangles["windowCaption"] = + new Rectangle(0, 0, + ClientRectangle.Width, captionHeight); + elementRectangles["windowBottom"] = + new Rectangle(0, heightMinusFrame, + ClientRectangle.Width, frameThickness); + elementRectangles["windowLeft"] = + new Rectangle(0, captionHeight, frameThickness, + heightMinusFrame - captionHeight); + elementRectangles["windowRight"] = + new Rectangle(ClientRectangle.Width - frameThickness, + captionHeight, frameThickness, + heightMinusFrame - captionHeight); + + // Calculate the window button rectangle and add it + // to the Dictionary of rectangles. + elementRectangles["windowClose"] = + new Rectangle(ClientRectangle.Right + + closeButtonOffset.X, closeButtonOffset.Y, + closeButtonSize.Width, closeButtonSize.Height); + + // Calculate the status bar rectangles and add them + // to the Dictionary of rectangles. + elementRectangles["statusBar"] = + new Rectangle(frameThickness, + heightMinusFrame - statusHeight, + ClientRectangle.Width - (2 * frameThickness), + statusHeight); + elementRectangles["statusGripper"] = + new Rectangle(ClientRectangle.Right - + gripperSize.Width - frameThickness, + heightMinusFrame - gripperSize.Height, + gripperSize.Width, gripperSize.Height); + } + + // + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + + // Ensure that visual styles are supported. + if (!Application.RenderWithVisualStyles) + { + this.Text = "Visual styles are not enabled."; + TextRenderer.DrawText(e.Graphics, this.Text, + this.Font, this.Location, this.ForeColor); + return; + } + + // Set the clip region to define the curved corners + // of the caption. + SetClipRegion(); + + // Draw each part of the window. + foreach (KeyValuePair entry + in windowElements) + { + if (SetRenderer(entry.Value)) + { + renderer.DrawBackground(e.Graphics, + elementRectangles[entry.Key]); + } + } + + // Draw the caption text. + TextRenderer.DrawText(e.Graphics, this.Text, this.Font, + elementRectangles["windowCaption"], Color.White, + TextFormatFlags.VerticalCenter | + TextFormatFlags.HorizontalCenter); + } + // + + // Initiate dragging, resizing, or closing the imitation window. + void ImitationWindow_MouseDown(object sender, MouseEventArgs e) + { + // The user clicked the close button. + if (elementRectangles["windowClose"].Contains(e.Location)) + { + windowElements["windowClose"] = + VisualStyleElement.Window.CloseButton.Pressed; + isClosing = true; + } + + // The user clicked the status grip. + else if (elementRectangles["statusGripper"]. + Contains(e.Location)) + { + isResizing = true; + this.Cursor = Cursors.SizeNWSE; + resizeOffset.X = this.Right - this.Left - e.X; + resizeOffset.Y = this.Bottom - this.Top - e.Y; + } + + // The user clicked the window caption. + else if (elementRectangles["windowCaption"]. + Contains(e.Location)) + { + isMoving = true; + originalClick.X = e.X; + originalClick.Y = e.Y; + } + + Invalidate(); + } + + // Stop any current resizing or moving actions. + void ImitationWindow_MouseUp(object sender, MouseEventArgs e) + { + // Stop moving the location of the window rectangles. + if (isMoving) + { + isMoving = false; + } + + // Change the cursor back to the default if the user + // stops resizing. + else if (isResizing) + { + isResizing = false; + } + + // Close the application if the user clicks the + // close button. + else if (elementRectangles["windowClose"]. + Contains(e.Location) && isClosing) + { + Application.Exit(); + } + } + + // Handle resizing or moving actions. + void ImitationWindow_MouseMove(object sender, + MouseEventArgs e) + { + // The left mouse button is down. + if ((MouseButtons.Left & e.Button) == MouseButtons.Left) + { + // Calculate the new control size if the user is + // dragging the resizing grip. + if (isResizing) + { + this.Width = e.X + resizeOffset.X; + this.Height = e.Y + resizeOffset.Y; + CalculateRectangles(); + } + + // Calculate the new location of the control if the + // user is dragging the window caption. + else if (isMoving) + { + int XChange = this.Location.X + + (e.X - originalClick.X); + int YChange = this.Location.Y + + (e.Y - originalClick.Y); + this.Location = new Point(XChange, YChange); + } + + // Cancel the closing action if the user clicked + // and held down on the close button, and has dragged + // the pointer outside the button. + else if (!elementRectangles["windowClose"]. + Contains(e.Location) && isClosing) + { + isClosing = false; + windowElements["windowClose"] = + VisualStyleElement.Window.CloseButton.Normal; + } + } + + // The left mouse button is not down. + else + { + // Paint the close button hot if the cursor is on it. + Rectangle closeRectangle = + elementRectangles["windowClose"]; + windowElements["windowClose"] = + closeRectangle.Contains(e.Location) ? + VisualStyleElement.Window.CloseButton.Hot : + VisualStyleElement.Window.CloseButton.Normal; + + // Use a resizing cursor if the cursor is on the + // status grip. + Rectangle gripRectangle = + elementRectangles["statusGripper"]; + this.Cursor = gripRectangle.Contains(e.Location) ? + Cursors.SizeNWSE : Cursors.Default; + } + + Invalidate(); + } + + // + // Calculate and set the clipping region for the control + // so that the corners of the title bar are rounded. + private void SetClipRegion() + { + if (!Application.RenderWithVisualStyles) + { + return; + } + + using (Graphics g = this.CreateGraphics()) + { + // Get the current region for the window caption. + if (SetRenderer(windowElements["windowCaption"])) + { + Region clipRegion = renderer.GetBackgroundRegion( + g, elementRectangles["windowCaption"]); + + // Get the client rectangle, but exclude the region + // of the window caption. + int height = (int)clipRegion.GetBounds(g).Height; + Rectangle nonCaptionRect = new Rectangle( + ClientRectangle.X, + ClientRectangle.Y + height, + ClientRectangle.Width, + ClientRectangle.Height - height); + + // Add the rectangle to the caption region, and + // make this region the form's clipping region. + clipRegion.Union(nonCaptionRect); + this.Region = clipRegion; + } + } + } + // + + // + // Set the VisualStyleRenderer to a new element. + private bool SetRenderer(VisualStyleElement element) + { + if (!VisualStyleRenderer.IsElementDefined(element)) + { + return false; + } + + if (renderer == null) + { + renderer = new VisualStyleRenderer(element); + } + else + { + renderer.SetParameters(element); + } + + return true; + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/CS/form1.cs new file mode 100644 index 0000000000..28889dc59c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/CS/form1.cs @@ -0,0 +1,66 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +namespace SimpleVisualStyleRendererSample +{ + class Form1 : Form + { + public Form1() + { + this.Size = new Size(400, 400); + this.BackColor = Color.WhiteSmoke; + this.Controls.Add(new CustomControl()); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } + + public class CustomControl : Control + { + // + private VisualStyleRenderer renderer = null; + private readonly VisualStyleElement element = + VisualStyleElement.StartPanel.LogOffButtons.Normal; + + public CustomControl() + { + this.Location = new Point(50, 50); + this.Size = new Size(200, 200); + this.BackColor = SystemColors.ActiveBorder; + + if (Application.RenderWithVisualStyles && + VisualStyleRenderer.IsElementDefined(element)) + { + renderer = new VisualStyleRenderer(element); + } + } + // + + // + protected override void OnPaint(PaintEventArgs e) + { + // Draw the element if the renderer has been set. + if (renderer != null) + { + renderer.DrawBackground(e.Graphics, this.ClientRectangle); + } + + // Visual styles are disabled or the element is undefined, + // so just draw a message. + else + { + this.Text = "Visual styles are disabled."; + TextRenderer.DrawText(e.Graphics, this.Text, this.Font, + new Point(0, 0), this.ForeColor); + } + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs new file mode 100644 index 0000000000..81edf59f5e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/CS/form1.cs @@ -0,0 +1,74 @@ +// +using System; +using System.Windows.Forms; +using System.Security.Permissions; + +[PermissionSet(SecurityAction.Demand, Name="FullTrust")] +[System.Runtime.InteropServices.ComVisibleAttribute(true)] +public class Form1 : Form +{ + private WebBrowser webBrowser1 = new WebBrowser(); + private Button button1 = new Button(); + + [STAThread] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + public Form1() + { + button1.Text = "call script code from client code"; + button1.Dock = DockStyle.Top; + button1.Click += new EventHandler(button1_Click); + webBrowser1.Dock = DockStyle.Fill; + Controls.Add(webBrowser1); + Controls.Add(button1); + Load += new EventHandler(Form1_Load); + } + + private void Form1_Load(object sender, EventArgs e) + { + // + webBrowser1.AllowWebBrowserDrop = false; + // + // + webBrowser1.IsWebBrowserContextMenuEnabled = false; + // + // + webBrowser1.WebBrowserShortcutsEnabled = false; + // + // + webBrowser1.ObjectForScripting = this; + // + // + // Uncomment the following line when you are finished debugging. + //webBrowser1.ScriptErrorsSuppressed = true; + // + + webBrowser1.DocumentText = + "" + + ""; + } + + // + public void Test(String message) + { + MessageBox.Show(message, "client code"); + } + // + + private void button1_Click(object sender, EventArgs e) + { + // + webBrowser1.Document.InvokeScript("test", + new String[] { "called from client code" }); + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CS/form1.cs new file mode 100644 index 0000000000..e3c5a60fd0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/CS/form1.cs @@ -0,0 +1,360 @@ +// +using System; +using System.Windows.Forms; +using System.Security.Permissions; + +[PermissionSet(SecurityAction.Demand, Name = "FullTrust")] +public class Form1 : Form +{ + public Form1() + { + // Create the form layout. If you are using Visual Studio, + // you can replace this code with code generated by the designer. + InitializeForm(); + + // The following events are not visible in the designer, so + // you must associate them with their event-handlers in code. + webBrowser1.CanGoBackChanged += + new EventHandler(webBrowser1_CanGoBackChanged); + webBrowser1.CanGoForwardChanged += + new EventHandler(webBrowser1_CanGoForwardChanged); + webBrowser1.DocumentTitleChanged += + new EventHandler(webBrowser1_DocumentTitleChanged); + webBrowser1.StatusTextChanged += + new EventHandler(webBrowser1_StatusTextChanged); + + // Load the user's home page. + webBrowser1.GoHome(); + } + + // + // Displays the Save dialog box. + private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) + { + webBrowser1.ShowSaveAsDialog(); + } + // + + // + // Displays the Page Setup dialog box. + private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e) + { + webBrowser1.ShowPageSetupDialog(); + } + // + + // + // Displays the Print dialog box. + private void printToolStripMenuItem_Click(object sender, EventArgs e) + { + webBrowser1.ShowPrintDialog(); + } + // + + // + // Displays the Print Preview dialog box. + private void printPreviewToolStripMenuItem_Click( + object sender, EventArgs e) + { + webBrowser1.ShowPrintPreviewDialog(); + } + // + + // + // Displays the Properties dialog box. + private void propertiesToolStripMenuItem_Click( + object sender, EventArgs e) + { + webBrowser1.ShowPropertiesDialog(); + } + // + + // Selects all the text in the text box when the user clicks it. + private void toolStripTextBox1_Click(object sender, EventArgs e) + { + toolStripTextBox1.SelectAll(); + } + + // + // Navigates to the URL in the address box when + // the ENTER key is pressed while the ToolStripTextBox has focus. + private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + Navigate(toolStripTextBox1.Text); + } + } + + // Navigates to the URL in the address box when + // the Go button is clicked. + private void goButton_Click(object sender, EventArgs e) + { + Navigate(toolStripTextBox1.Text); + } + + // Navigates to the given URL if it is valid. + private void Navigate(String address) + { + if (String.IsNullOrEmpty(address)) return; + if (address.Equals("about:blank")) return; + if (!address.StartsWith("http://") && + !address.StartsWith("https://")) + { + address = "http://" + address; + } + try + { + webBrowser1.Navigate(new Uri(address)); + } + catch (System.UriFormatException) + { + return; + } + } + + // Updates the URL in TextBoxAddress upon navigation. + private void webBrowser1_Navigated(object sender, + WebBrowserNavigatedEventArgs e) + { + toolStripTextBox1.Text = webBrowser1.Url.ToString(); + } + // + + // + // Navigates webBrowser1 to the previous page in the history. + private void backButton_Click(object sender, EventArgs e) + { + webBrowser1.GoBack(); + } + + // Disables the Back button at the beginning of the navigation history. + private void webBrowser1_CanGoBackChanged(object sender, EventArgs e) + { + backButton.Enabled = webBrowser1.CanGoBack; + } + // + + // + // Navigates webBrowser1 to the next page in history. + private void forwardButton_Click(object sender, EventArgs e) + { + webBrowser1.GoForward(); + } + + // Disables the Forward button at the end of navigation history. + private void webBrowser1_CanGoForwardChanged(object sender, EventArgs e) + { + forwardButton.Enabled = webBrowser1.CanGoForward; + } + // + + // + // Halts the current navigation and any sounds or animations on + // the page. + private void stopButton_Click(object sender, EventArgs e) + { + webBrowser1.Stop(); + } + // + + // + // Reloads the current page. + private void refreshButton_Click(object sender, EventArgs e) + { + // Skip refresh if about:blank is loaded to avoid removing + // content specified by the DocumentText property. + if (!webBrowser1.Url.Equals("about:blank")) + { + webBrowser1.Refresh(); + } + } + // + + // + // Navigates webBrowser1 to the home page of the current user. + private void homeButton_Click(object sender, EventArgs e) + { + webBrowser1.GoHome(); + } + // + + // + // Navigates webBrowser1 to the search page of the current user. + private void searchButton_Click(object sender, EventArgs e) + { + webBrowser1.GoSearch(); + } + // + + // + // Prints the current document using the current print settings. + private void printButton_Click(object sender, EventArgs e) + { + webBrowser1.Print(); + } + // + + // + // Updates the status bar with the current browser status text. + private void webBrowser1_StatusTextChanged(object sender, EventArgs e) + { + toolStripStatusLabel1.Text = webBrowser1.StatusText; + } + // + + // + // Updates the title bar with the current document title. + private void webBrowser1_DocumentTitleChanged(object sender, EventArgs e) + { + this.Text = webBrowser1.DocumentTitle; + } + // + + // Exits the application. + private void exitToolStripMenuItem_Click(object sender, EventArgs e) + { + Application.Exit(); + } + + // The remaining code in this file provides basic form initialization and + // includes a Main method. If you use the Visual Studio designer to create + // your form, you can use the designer generated code instead of this code, + // but be sure to use the names shown in the variable declarations here, + // and be sure to attach the event handlers to the associated events. + + private WebBrowser webBrowser1; + + private MenuStrip menuStrip1; + private ToolStripMenuItem fileToolStripMenuItem, + saveAsToolStripMenuItem, printToolStripMenuItem, + printPreviewToolStripMenuItem, exitToolStripMenuItem, + pageSetupToolStripMenuItem, propertiesToolStripMenuItem; + private ToolStripSeparator toolStripSeparator1, toolStripSeparator2; + + private ToolStrip toolStrip1, toolStrip2; + private ToolStripTextBox toolStripTextBox1; + private ToolStripButton goButton, backButton, + forwardButton, stopButton, refreshButton, + homeButton, searchButton, printButton; + + private StatusStrip statusStrip1; + private ToolStripStatusLabel toolStripStatusLabel1; + + private void InitializeForm() + { + webBrowser1 = new WebBrowser(); + + menuStrip1 = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + saveAsToolStripMenuItem = new ToolStripMenuItem(); + toolStripSeparator1 = new ToolStripSeparator(); + printToolStripMenuItem = new ToolStripMenuItem(); + printPreviewToolStripMenuItem = new ToolStripMenuItem(); + toolStripSeparator2 = new ToolStripSeparator(); + exitToolStripMenuItem = new ToolStripMenuItem(); + pageSetupToolStripMenuItem = new ToolStripMenuItem(); + propertiesToolStripMenuItem = new ToolStripMenuItem(); + + toolStrip1 = new ToolStrip(); + goButton = new ToolStripButton(); + backButton = new ToolStripButton(); + forwardButton = new ToolStripButton(); + stopButton = new ToolStripButton(); + refreshButton = new ToolStripButton(); + homeButton = new ToolStripButton(); + searchButton = new ToolStripButton(); + printButton = new ToolStripButton(); + + toolStrip2 = new ToolStrip(); + toolStripTextBox1 = new ToolStripTextBox(); + + statusStrip1 = new StatusStrip(); + toolStripStatusLabel1 = new ToolStripStatusLabel(); + + menuStrip1.Items.Add(fileToolStripMenuItem); + + fileToolStripMenuItem.DropDownItems.AddRange( + new ToolStripItem[] { + saveAsToolStripMenuItem, toolStripSeparator1, + pageSetupToolStripMenuItem, printToolStripMenuItem, + printPreviewToolStripMenuItem, toolStripSeparator2, + propertiesToolStripMenuItem, exitToolStripMenuItem + }); + + fileToolStripMenuItem.Text = "&File"; + saveAsToolStripMenuItem.Text = "Save &As..."; + pageSetupToolStripMenuItem.Text = "Page Set&up..."; + printToolStripMenuItem.Text = "&Print..."; + printPreviewToolStripMenuItem.Text = "Print Pre&view..."; + propertiesToolStripMenuItem.Text = "Properties"; + exitToolStripMenuItem.Text = "E&xit"; + + // + printToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; + // + + saveAsToolStripMenuItem.Click += + new System.EventHandler(saveAsToolStripMenuItem_Click); + pageSetupToolStripMenuItem.Click += + new System.EventHandler(pageSetupToolStripMenuItem_Click); + printToolStripMenuItem.Click += + new System.EventHandler(printToolStripMenuItem_Click); + printPreviewToolStripMenuItem.Click += + new System.EventHandler(printPreviewToolStripMenuItem_Click); + propertiesToolStripMenuItem.Click += + new System.EventHandler(propertiesToolStripMenuItem_Click); + exitToolStripMenuItem.Click += + new System.EventHandler(exitToolStripMenuItem_Click); + + toolStrip1.Items.AddRange(new ToolStripItem[] { + goButton, backButton, forwardButton, stopButton, + refreshButton, homeButton, searchButton, printButton}); + + goButton.Text = "Go"; + backButton.Text = "Back"; + forwardButton.Text = "Forward"; + stopButton.Text = "Stop"; + refreshButton.Text = "Refresh"; + homeButton.Text = "Home"; + searchButton.Text = "Search"; + printButton.Text = "Print"; + + backButton.Enabled = false; + forwardButton.Enabled = false; + + goButton.Click += new System.EventHandler(goButton_Click); + backButton.Click += new System.EventHandler(backButton_Click); + forwardButton.Click += new System.EventHandler(forwardButton_Click); + stopButton.Click += new System.EventHandler(stopButton_Click); + refreshButton.Click += new System.EventHandler(refreshButton_Click); + homeButton.Click += new System.EventHandler(homeButton_Click); + searchButton.Click += new System.EventHandler(searchButton_Click); + printButton.Click += new System.EventHandler(printButton_Click); + + toolStrip2.Items.Add(toolStripTextBox1); + toolStripTextBox1.Size = new System.Drawing.Size(250, 25); + toolStripTextBox1.KeyDown += + new KeyEventHandler(toolStripTextBox1_KeyDown); + toolStripTextBox1.Click += + new System.EventHandler(toolStripTextBox1_Click); + + statusStrip1.Items.Add(toolStripStatusLabel1); + + webBrowser1.Dock = DockStyle.Fill; + webBrowser1.Navigated += + new WebBrowserNavigatedEventHandler(webBrowser1_Navigated); + + Controls.AddRange(new Control[] { + webBrowser1, toolStrip2, toolStrip1, + menuStrip1, statusStrip1, menuStrip1 }); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/CS/form1.cs new file mode 100644 index 0000000000..c9ff4c5422 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/CS/form1.cs @@ -0,0 +1,56 @@ +// +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +namespace SimpleControlRenderingSample +{ + class Form1 : Form + { + public Form1() + : base() + { + this.Size = new Size(300, 300); + CustomComboBoxArrow ComboBox1 = new CustomComboBoxArrow(); + Controls.Add(ComboBox1); + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + } + + public class CustomComboBoxArrow : Control + { + public CustomComboBoxArrow() + : base() + { + this.Location = new Point(50, 50); + this.Size = new Size(40, 40); + } + + // + // Render the drop-down arrow with or without visual styles. + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + + if (!ComboBoxRenderer.IsSupported) + { + ControlPaint.DrawComboButton(e.Graphics, + this.ClientRectangle, ButtonState.Normal); + } + else + { + ComboBoxRenderer.DrawDropDownButton(e.Graphics, + this.ClientRectangle, ComboBoxState.Normal); + } + } + // + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.Designer.cs new file mode 100644 index 0000000000..6bf6596a1d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.Designer.cs @@ -0,0 +1,93 @@ +namespace TestVerticalTabsCS +{ + 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.tabControl1 = new System.Windows.Forms.TabControl(); + this.tabPage1 = new System.Windows.Forms.TabPage(); + this.tabPage2 = new System.Windows.Forms.TabPage(); + this.tabControl1.SuspendLayout(); + this.SuspendLayout(); + // + // tabControl1 + // + this.tabControl1.Alignment = System.Windows.Forms.TabAlignment.Right; + this.tabControl1.Controls.Add(this.tabPage1); + this.tabControl1.Controls.Add(this.tabPage2); + this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; + this.tabControl1.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed; + this.tabControl1.ItemSize = new System.Drawing.Size(25, 150); + this.tabControl1.Location = new System.Drawing.Point(0, 0); + this.tabControl1.Multiline = true; + this.tabControl1.Name = "tabControl1"; + this.tabControl1.SelectedIndex = 0; + this.tabControl1.Size = new System.Drawing.Size(588, 382); + this.tabControl1.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; + this.tabControl1.TabIndex = 0; + // + // tabPage1 + // + this.tabPage1.Location = new System.Drawing.Point(4, 4); + this.tabPage1.Name = "tabPage1"; + this.tabPage1.Padding = new System.Windows.Forms.Padding(3); + this.tabPage1.Size = new System.Drawing.Size(430, 374); + this.tabPage1.TabIndex = 0; + this.tabPage1.Text = "tabPage1"; + this.tabPage1.UseVisualStyleBackColor = true; + // + // tabPage2 + // + this.tabPage2.Location = new System.Drawing.Point(4, 4); + this.tabPage2.Name = "tabPage2"; + this.tabPage2.Padding = new System.Windows.Forms.Padding(3); + this.tabPage2.Size = new System.Drawing.Size(561, 374); + this.tabPage2.TabIndex = 1; + this.tabPage2.Text = "tabPage2"; + this.tabPage2.UseVisualStyleBackColor = true; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(588, 382); + this.Controls.Add(this.tabControl1); + this.Name = "Form1"; + this.Text = "Form1"; + this.tabControl1.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.TabControl tabControl1; + private System.Windows.Forms.TabPage tabPage1; + private System.Windows.Forms.TabPage tabPage2; + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.cs new file mode 100644 index 0000000000..1f61cad384 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +namespace TestVerticalTabsCS +{ + public partial class Form1 : Form + { + // + public Form1() + { + // Remove this call if you do not program using Visual Studio. + InitializeComponent(); + + tabControl1.DrawItem += new DrawItemEventHandler(tabControl1_DrawItem); + } + + private void tabControl1_DrawItem(Object sender, System.Windows.Forms.DrawItemEventArgs e) + { + Graphics g = e.Graphics; + Brush _textBrush; + + // Get the item from the collection. + TabPage _tabPage = tabControl1.TabPages[e.Index]; + + // Get the real bounds for the tab rectangle. + Rectangle _tabBounds = tabControl1.GetTabRect(e.Index); + + if (e.State == DrawItemState.Selected) + { + + // Draw a different background color, and don't paint a focus rectangle. + _textBrush = new SolidBrush(Color.Red); + g.FillRectangle(Brushes.Gray, e.Bounds); + } + else + { + _textBrush = new System.Drawing.SolidBrush(e.ForeColor); + e.DrawBackground(); + } + + // Use our own font. + Font _tabFont = new Font("Arial", 10.0f, FontStyle.Bold, GraphicsUnit.Pixel); + + // Draw string. Center the text. + StringFormat _stringFlags = new StringFormat(); + _stringFlags.Alignment = StringAlignment.Center; + _stringFlags.LineAlignment = StringAlignment.Center; + g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags)); + } + // + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.resx new file mode 100644 index 0000000000..19dc0dd8b3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Program.cs new file mode 100644 index 0000000000..ea145392b5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Program.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace TestVerticalTabsCS +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..d1d41603b6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("TestVerticalTabsCS")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("TestVerticalTabsCS")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2006")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("f680b693-1e96-402a-9fa6-4066e72b7d72")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Resources.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..1fdfaae5b3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.20305.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace TestVerticalTabsCS.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TestVerticalTabsCS.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Settings.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Settings.Designer.cs new file mode 100644 index 0000000000..55ba0a5d0a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.20305.0 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace TestVerticalTabsCS.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Settings.settings new file mode 100644 index 0000000000..39645652af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/TestVerticalTabsCS.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/TestVerticalTabsCS.csproj new file mode 100644 index 0000000000..ebf9d8e89a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabControl.RightAlignedTabs/CS/TestVerticalTabsCS.csproj @@ -0,0 +1,85 @@ + + + Debug + AnyCPU + 10.0.20305 + 2.0 + {9A37C3B5-3438-475B-8EBF-CAC9AFDCFC96} + WinExe + Properties + TestVerticalTabsCS + TestVerticalTabsCS + + + + + 2.0 + v2.0 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + Form + + + Form1.cs + + + + + Designer + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabPage/CS/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabPage/CS/form1.cs new file mode 100644 index 0000000000..607ce3399e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/TabPage/CS/form1.cs @@ -0,0 +1,39 @@ +// +using System.Drawing; +using System.Windows.Forms; + +public class Form1 : Form +{ + private TabControl tabControl1; + + // Declares tabPage1 as a TabPage type. + private System.Windows.Forms.TabPage tabPage1; + + private void MyTabs() + { + this.tabControl1 = new TabControl(); + + // Invokes the TabPage() constructor to create the tabPage1. + this.tabPage1 = new System.Windows.Forms.TabPage(); + + this.tabControl1.Controls.AddRange(new Control[] { + this.tabPage1}); + this.tabControl1.Location = new Point(25, 25); + this.tabControl1.Size = new Size(250, 250); + + this.ClientSize = new Size(300, 300); + this.Controls.AddRange(new Control[] { + this.tabControl1}); + } + + public Form1() + { + MyTabs(); + } + + static void Main() + { + Application.Run(new Form1()); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs new file mode 100644 index 0000000000..b39afbdcc7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/cs/ToolStripRadioButtonMenuItem.cs @@ -0,0 +1,325 @@ +// +// +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Windows.Forms.VisualStyles; + +public class ToolStripRadioButtonMenuItem : ToolStripMenuItem +{ + public ToolStripRadioButtonMenuItem() + : base() + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(string text) + : base(text, null, (EventHandler)null) + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(Image image) + : base(null, image, (EventHandler)null) + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(string text, Image image) + : base(text, image, (EventHandler)null) + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(string text, Image image, + EventHandler onClick) + : base(text, image, onClick) + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(string text, Image image, + EventHandler onClick, string name) + : base(text, image, onClick, name) + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(string text, Image image, + params ToolStripItem[] dropDownItems) + : base(text, image, dropDownItems) + { + Initialize(); + } + + public ToolStripRadioButtonMenuItem(string text, Image image, + EventHandler onClick, Keys shortcutKeys) + : base(text, image, onClick) + { + Initialize(); + this.ShortcutKeys = shortcutKeys; + } + + // + // Called by all constructors to initialize CheckOnClick. + private void Initialize() + { + CheckOnClick = true; + } + // + + // + protected override void OnCheckedChanged(EventArgs e) + { + base.OnCheckedChanged(e); + + // If this item is no longer in the checked state or if its + // parent has not yet been initialized, do nothing. + if (!Checked || this.Parent == null) return; + + // Clear the checked state for all siblings. + foreach (ToolStripItem item in Parent.Items) + { + ToolStripRadioButtonMenuItem radioItem = + item as ToolStripRadioButtonMenuItem; + if (radioItem != null && radioItem != this && radioItem.Checked) + { + radioItem.Checked = false; + + // Only one item can be selected at a time, + // so there is no need to continue. + return; + } + } + } + // + + // + protected override void OnClick(EventArgs e) + { + // If the item is already in the checked state, do not call + // the base method, which would toggle the value. + if (Checked) return; + + base.OnClick(e); + } + // + + // + // Let the item paint itself, and then paint the RadioButton + // where the check mark is normally displayed. + protected override void OnPaint(PaintEventArgs e) + { + if (Image != null) + { + // If the client sets the Image property, the selection behavior + // remains unchanged, but the RadioButton is not displayed and the + // selection is indicated only by the selection rectangle. + base.OnPaint(e); + return; + } + else + { + // If the Image property is not set, call the base OnPaint method + // with the CheckState property temporarily cleared to prevent + // the check mark from being painted. + CheckState currentState = this.CheckState; + this.CheckState = CheckState.Unchecked; + base.OnPaint(e); + this.CheckState = currentState; + } + + // Determine the correct state of the RadioButton. + RadioButtonState buttonState = RadioButtonState.UncheckedNormal; + if (Enabled) + { + if (mouseDownState) + { + if (Checked) buttonState = RadioButtonState.CheckedPressed; + else buttonState = RadioButtonState.UncheckedPressed; + } + else if (mouseHoverState) + { + if (Checked) buttonState = RadioButtonState.CheckedHot; + else buttonState = RadioButtonState.UncheckedHot; + } + else + { + if (Checked) buttonState = RadioButtonState.CheckedNormal; + } + } + else + { + if (Checked) buttonState = RadioButtonState.CheckedDisabled; + else buttonState = RadioButtonState.UncheckedDisabled; + } + + // Calculate the position at which to display the RadioButton. + Int32 offset = (ContentRectangle.Height - + RadioButtonRenderer.GetGlyphSize( + e.Graphics, buttonState).Height) / 2; + Point imageLocation = new Point( + ContentRectangle.Location.X + 4, + ContentRectangle.Location.Y + offset); + + // Paint the RadioButton. + RadioButtonRenderer.DrawRadioButton( + e.Graphics, imageLocation, buttonState); + } + // + + // + private bool mouseHoverState = false; + + protected override void OnMouseEnter(EventArgs e) + { + mouseHoverState = true; + + // Force the item to repaint with the new RadioButton state. + Invalidate(); + + base.OnMouseEnter(e); + } + + protected override void OnMouseLeave(EventArgs e) + { + mouseHoverState = false; + base.OnMouseLeave(e); + } + + private bool mouseDownState = false; + + protected override void OnMouseDown(MouseEventArgs e) + { + mouseDownState = true; + + // Force the item to repaint with the new RadioButton state. + Invalidate(); + + base.OnMouseDown(e); + } + + protected override void OnMouseUp(MouseEventArgs e) + { + mouseDownState = false; + base.OnMouseUp(e); + } + // + + // + // Enable the item only if its parent item is in the checked state + // and its Enabled property has not been explicitly set to false. + public override bool Enabled + { + get + { + ToolStripMenuItem ownerMenuItem = + OwnerItem as ToolStripMenuItem; + + // Use the base value in design mode to prevent the designer + // from setting the base value to the calculated value. + if (!DesignMode && + ownerMenuItem != null && ownerMenuItem.CheckOnClick) + { + return base.Enabled && ownerMenuItem.Checked; + } + else + { + return base.Enabled; + } + } + set + { + base.Enabled = value; + } + } + // + + // + // When OwnerItem becomes available, if it is a ToolStripMenuItem + // with a CheckOnClick property value of true, subscribe to its + // CheckedChanged event. + protected override void OnOwnerChanged(EventArgs e) + { + ToolStripMenuItem ownerMenuItem = + OwnerItem as ToolStripMenuItem; + if (ownerMenuItem != null && ownerMenuItem.CheckOnClick) + { + ownerMenuItem.CheckedChanged += + new EventHandler(OwnerMenuItem_CheckedChanged); + } + base.OnOwnerChanged(e); + } + // + + // + // When the checked state of the parent item changes, + // repaint the item so that the new Enabled state is displayed. + private void OwnerMenuItem_CheckedChanged( + object sender, EventArgs e) + { + Invalidate(); + } + // +} +// + +// +public class Form1 : Form +{ + private MenuStrip menuStrip1 = new MenuStrip(); + private ToolStripMenuItem mainToolStripMenuItem = new ToolStripMenuItem(); + private ToolStripMenuItem toolStripMenuItem1 = new ToolStripMenuItem(); + private ToolStripRadioButtonMenuItem toolStripRadioButtonMenuItem1 = + new ToolStripRadioButtonMenuItem(); + private ToolStripRadioButtonMenuItem toolStripRadioButtonMenuItem2 = + new ToolStripRadioButtonMenuItem(); + private ToolStripRadioButtonMenuItem toolStripRadioButtonMenuItem3 = + new ToolStripRadioButtonMenuItem(); + private ToolStripRadioButtonMenuItem toolStripRadioButtonMenuItem4 = + new ToolStripRadioButtonMenuItem(); + private ToolStripRadioButtonMenuItem toolStripRadioButtonMenuItem5 = + new ToolStripRadioButtonMenuItem(); + private ToolStripRadioButtonMenuItem toolStripRadioButtonMenuItem6 = + new ToolStripRadioButtonMenuItem(); + + public Form1() + { + mainToolStripMenuItem.Text = "main"; + toolStripRadioButtonMenuItem1.Text = "option 1"; + toolStripRadioButtonMenuItem2.Text = "option 2"; + toolStripRadioButtonMenuItem3.Text = "option 2-1"; + toolStripRadioButtonMenuItem4.Text = "option 2-2"; + toolStripRadioButtonMenuItem5.Text = "option 3-1"; + toolStripRadioButtonMenuItem6.Text = "option 3-2"; + toolStripMenuItem1.Text = "toggle"; + toolStripMenuItem1.CheckOnClick = true; + + mainToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { + toolStripRadioButtonMenuItem1, toolStripRadioButtonMenuItem2, + toolStripMenuItem1}); + toolStripRadioButtonMenuItem2.DropDownItems.AddRange( + new ToolStripItem[] {toolStripRadioButtonMenuItem3, + toolStripRadioButtonMenuItem4}); + toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { + toolStripRadioButtonMenuItem5, toolStripRadioButtonMenuItem6}); + + menuStrip1.Items.AddRange(new ToolStripItem[] {mainToolStripMenuItem}); + Controls.Add(menuStrip1); + MainMenuStrip = menuStrip1; + Text = "ToolStripRadioButtonMenuItem demo"; + } +} + +static class Program +{ + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } +} +// +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripSpringTextBox/cs/ToolStripSpringTextBox.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripSpringTextBox/cs/ToolStripSpringTextBox.cs new file mode 100644 index 0000000000..ffa7a9d720 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/ToolStripSpringTextBox/cs/ToolStripSpringTextBox.cs @@ -0,0 +1,97 @@ +// +// +using System; +using System.Drawing; +using System.Windows.Forms; + +public class ToolStripSpringTextBox : ToolStripTextBox +{ + public override Size GetPreferredSize(Size constrainingSize) + { + // Use the default size if the text box is on the overflow menu + // or is on a vertical ToolStrip. + if (IsOnOverflow || Owner.Orientation == Orientation.Vertical) + { + return DefaultSize; + } + + // Declare a variable to store the total available width as + // it is calculated, starting with the display width of the + // owning ToolStrip. + Int32 width = Owner.DisplayRectangle.Width; + + // Subtract the width of the overflow button if it is displayed. + if (Owner.OverflowButton.Visible) + { + width = width - Owner.OverflowButton.Width - + Owner.OverflowButton.Margin.Horizontal; + } + + // Declare a variable to maintain a count of ToolStripSpringTextBox + // items currently displayed in the owning ToolStrip. + Int32 springBoxCount = 0; + + foreach (ToolStripItem item in Owner.Items) + { + // Ignore items on the overflow menu. + if (item.IsOnOverflow) continue; + + if (item is ToolStripSpringTextBox) + { + // For ToolStripSpringTextBox items, increment the count and + // subtract the margin width from the total available width. + springBoxCount++; + width -= item.Margin.Horizontal; + } + else + { + // For all other items, subtract the full width from the total + // available width. + width = width - item.Width - item.Margin.Horizontal; + } + } + + // If there are multiple ToolStripSpringTextBox items in the owning + // ToolStrip, divide the total available width between them. + if (springBoxCount > 1) width /= springBoxCount; + + // If the available width is less than the default width, use the + // default width, forcing one or more items onto the overflow menu. + if (width < DefaultSize.Width) width = DefaultSize.Width; + + // Retrieve the preferred size from the base class, but change the + // width to the calculated width. + Size size = base.GetPreferredSize(constrainingSize); + size.Width = width; + return size; + } +} +// + +// +public class Form1 : Form +{ + public Form1() + { + ToolStrip toolStrip1 = new ToolStrip(); + toolStrip1.Dock = DockStyle.Top; + toolStrip1.Items.Add(new ToolStripLabel("Address")); + toolStrip1.Items.Add(new ToolStripSpringTextBox()); + toolStrip1.Items.Add(new ToolStripButton("Go")); + Controls.Add(toolStrip1); + Text = "ToolStripSpringTextBox demo"; + } +} + +static class Program +{ + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } +} +// +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs new file mode 100644 index 0000000000..729e35c5d3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/UsingImageEncodersDecoders/CS/Form1.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Text; +using System.Windows.Forms; +using System.Drawing.Imaging; + +namespace GDIPlusPort +{ + public partial class Form1 : Form + { + public Form1() + { + } + + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + + // + private void GetImageEncodersExample(PaintEventArgs e) + { + // Get an array of available encoders. + ImageCodecInfo[] myCodecs; + myCodecs = ImageCodecInfo.GetImageEncoders(); + int numCodecs = myCodecs.GetLength(0); + + // Set up display variables. + Color foreColor = Color.Black; + Font font = new Font("Arial", 8); + int i = 0; + + // Check to determine whether any codecs were found. + if (numCodecs > 0) + { + // Set up an array to hold codec information. There are 9 + // information elements plus 1 space for each codec, so 10 times + // the number of codecs found is allocated. + string[] myCodecInfo = new string[numCodecs * 10]; + + // Write all the codec information to the array. + for (i = 0; i < numCodecs; i++) + { + myCodecInfo[i * 10] = "Codec Name = " + myCodecs[i].CodecName; + myCodecInfo[(i * 10) + 1] = "Class ID = " + + myCodecs[i].Clsid.ToString(); + myCodecInfo[(i * 10) + 2] = "DLL Name = " + myCodecs[i].DllName; + myCodecInfo[(i * 10) + 3] = "Filename Ext. = " + + myCodecs[i].FilenameExtension; + myCodecInfo[(i * 10) + 4] = "Flags = " + + myCodecs[i].Flags.ToString(); + myCodecInfo[(i * 10) + 5] = "Format Descrip. = " + + myCodecs[i].FormatDescription; + myCodecInfo[(i * 10) + 6] = "Format ID = " + + myCodecs[i].FormatID.ToString(); + myCodecInfo[(i * 10) + 7] = "MimeType = " + myCodecs[i].MimeType; + myCodecInfo[(i * 10) + 8] = "Version = " + + myCodecs[i].Version.ToString(); + myCodecInfo[(i * 10) + 9] = " "; + } + int numMyCodecInfo = myCodecInfo.GetLength(0); + + // Render all of the information to the screen. + int j = 20; + for (i = 0; i < numMyCodecInfo; i++) + { + e.Graphics.DrawString(myCodecInfo[i], + font, + new SolidBrush(foreColor), + 20, + j); + j += 12; + } + } + else + e.Graphics.DrawString("No Codecs Found", + font, + new SolidBrush(foreColor), + 20, + 20); + } + + // + + // + private void GetImageDecodersExample(PaintEventArgs e) + { + // Get an array of available decoders. + ImageCodecInfo[] myCodecs; + myCodecs = ImageCodecInfo.GetImageDecoders(); + int numCodecs = myCodecs.GetLength(0); + + // Set up display variables. + Color foreColor = Color.Black; + Font font = new Font("Arial", 8); + int i = 0; + + // Check to determine whether any codecs were found. + if (numCodecs > 0) + { + // Set up an array to hold codec information. There are 9 + // information elements plus 1 space for each codec, so 10 times + // the number of codecs found is allocated. + string[] myCodecInfo = new string[numCodecs * 10]; + + // Write all the codec information to the array. + for (i = 0; i < numCodecs; i++) + { + myCodecInfo[i * 10] = "Codec Name = " + myCodecs[i].CodecName; + myCodecInfo[(i * 10) + 1] = "Class ID = " + + myCodecs[i].Clsid.ToString(); + myCodecInfo[(i * 10) + 2] = "DLL Name = " + myCodecs[i].DllName; + myCodecInfo[(i * 10) + 3] = "Filename Ext. = " + + myCodecs[i].FilenameExtension; + myCodecInfo[(i * 10) + 4] = "Flags = " + + myCodecs[i].Flags.ToString(); + myCodecInfo[(i * 10) + 5] = "Format Descrip. = " + + myCodecs[i].FormatDescription; + myCodecInfo[(i * 10) + 6] = "Format ID = " + + myCodecs[i].FormatID.ToString(); + myCodecInfo[(i * 10) + 7] = "MimeType = " + myCodecs[i].MimeType; + myCodecInfo[(i * 10) + 8] = "Version = " + + myCodecs[i].Version.ToString(); + myCodecInfo[(i * 10) + 9] = " "; + } + int numMyCodecInfo = myCodecInfo.GetLength(0); + + // Render all of the information to the screen. + int j = 20; + for (i = 0; i < numMyCodecInfo; i++) + { + e.Graphics.DrawString(myCodecInfo[i], + font, + new SolidBrush(foreColor), + 20, + j); + j += 12; + } + } + else + e.Graphics.DrawString("No Codecs Found", + font, + new SolidBrush(foreColor), + 20, + 20); + } + // + + // + private void GetSupportedParameters(PaintEventArgs e) + { + Bitmap bitmap1 = new Bitmap(1, 1); + ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); + EncoderParameters paramList = bitmap1.GetEncoderParameterList(jpgEncoder.Clsid); + EncoderParameter[] encParams = paramList.Param; + StringBuilder paramInfo = new StringBuilder(); + + for (int i = 0; i < encParams.Length; i++) + { + paramInfo.Append("Param " + i + " holds " + encParams[i].NumberOfValues + + " items of type " + + encParams[i].ValueType + "\r\n" + "Guid category: " + encParams[i].Encoder.Guid + "\r\n"); + } + e.Graphics.DrawString(paramInfo.ToString(), this.Font, Brushes.Red, 10.0F, 10.0F); + } + + // + private ImageCodecInfo GetEncoder(ImageFormat format) + { + ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); + + foreach (ImageCodecInfo codec in codecs) + { + if (codec.FormatID == format.Guid) + { + return codec; + } + } + + return null; + } + // + // + + // + private void SaveBmpAsPNG() + { + Bitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp"); + bmp1.Save(@"c:\button.png", ImageFormat.Png); + } + // + + // + private void VaryQualityLevel() + { + // Get a bitmap. + Bitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg"); + ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); + + // Create an Encoder object based on the GUID + // for the Quality parameter category. + System.Drawing.Imaging.Encoder myEncoder = + System.Drawing.Imaging.Encoder.Quality; + + // Create an EncoderParameters object. + // An EncoderParameters object has an array of EncoderParameter + // objects. In this case, there is only one + // EncoderParameter object in the array. + EncoderParameters myEncoderParameters = new EncoderParameters(1); + + EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); + myEncoderParameters.Param[0] = myEncoderParameter; + bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters); + + myEncoderParameter = new EncoderParameter(myEncoder, 100L); + myEncoderParameters.Param[0] = myEncoderParameter; + bmp1.Save(@"c:\TestPhotoQualityHundred.jpg", jpgEncoder, myEncoderParameters); + + // Save the bitmap as a JPG file with zero quality level compression. + myEncoderParameter = new EncoderParameter(myEncoder, 0L); + myEncoderParameters.Param[0] = myEncoderParameter; + bmp1.Save(@"c:\TestPhotoQualityZero.jpg", jpgEncoder, myEncoderParameters); + } + // + + private void Form1_Load(object sender, EventArgs e) + { + //SaveBmpAsPng(); + } + + private void Form1_Paint(object sender, PaintEventArgs e) + { + GetSupportedParameters(e); + SaveBmpAsPNG(); + VaryQualityLevel(); + // GetImageDecodersExample(e); + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WebBrowserMisc/CS/WebBrowserMisc.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WebBrowserMisc/CS/WebBrowserMisc.cs new file mode 100644 index 0000000000..85b1f1eb06 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WebBrowserMisc/CS/WebBrowserMisc.cs @@ -0,0 +1,123 @@ +using System; +using System.Windows.Forms; +using System.Security.Permissions; + +[PermissionSetAttribute(SecurityAction.Demand, Name="FullTrust")] +public class Form1 : Form +{ + [STAThread] + public static void Main() + { + Application.Run(new Form1()); + } + + private Button button = new Button(); + + public Form1() + { + button.Click += new EventHandler(button_Click); + this.Controls.Add(button); + this.Controls.Add(webBrowser1); + } + + void button_Click(object sender, EventArgs e) + { + PrintHelpPage(); + } + + // + private void PrintHelpPage() + { + // Create a WebBrowser instance. + WebBrowser webBrowserForPrinting = new WebBrowser(); + + // Add an event handler that prints the document after it loads. + webBrowserForPrinting.DocumentCompleted += + new WebBrowserDocumentCompletedEventHandler(PrintDocument); + + // Set the Url property to load the document. + webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html"); + } + + private void PrintDocument(object sender, + WebBrowserDocumentCompletedEventArgs e) + { + // Print the document now that it is fully loaded. + ((WebBrowser)sender).Print(); + + // Dispose the WebBrowser now that the task is complete. + ((WebBrowser)sender).Dispose(); + } + // + + private WebBrowser webBrowser1 = new WebBrowser(); + + private void InitializeHtmlViewer() + { + // + webBrowser1.AllowWebBrowserDrop = false; + // + + // + webBrowser1.Url = new Uri("http://www.contoso.com/"); + // + } + + // + private void Form1_Load(object sender, EventArgs e) + { + webBrowser1.DocumentText = + "Please enter your name:
" + + "
" + + "continue" + + ""; + webBrowser1.Navigating += + new WebBrowserNavigatingEventHandler(webBrowser1_Navigating); + } + + private void webBrowser1_Navigating(object sender, + WebBrowserNavigatingEventArgs e) + { + System.Windows.Forms.HtmlDocument document = + this.webBrowser1.Document; + + if (document != null && document.All["userName"] != null && + String.IsNullOrEmpty( + document.All["userName"].GetAttribute("value"))) + { + e.Cancel = true; + System.Windows.Forms.MessageBox.Show( + "You must enter your name before you can navigate to " + + e.Url.ToString()); + } + } + //
+ + // + // Hides script errors without hiding other dialog boxes. + private void SuppressScriptErrorsOnly(WebBrowser browser) + { + // Ensure that ScriptErrorsSuppressed is set to false. + browser.ScriptErrorsSuppressed = false; + + // Handle DocumentCompleted to gain access to the Document object. + browser.DocumentCompleted += + new WebBrowserDocumentCompletedEventHandler( + browser_DocumentCompleted); + } + + private void browser_DocumentCompleted(object sender, + WebBrowserDocumentCompletedEventArgs e) + { + ((WebBrowser)sender).Document.Window.Error += + new HtmlElementErrorEventHandler(Window_Error); + } + + private void Window_Error(object sender, + HtmlElementErrorEventArgs e) + { + // Ignore the error and suppress the error dialog box. + e.Handled = true; + } + // +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.Designer.cs new file mode 100644 index 0000000000..a951dbc994 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.Designer.cs @@ -0,0 +1,61 @@ +namespace WinFormsAutoScaling +{ + 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.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(24, 30); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(65, 13); + this.label1.TabIndex = 0; + this.label1.Text = "Hello, world!"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(133, 113); + this.Controls.Add(this.label1); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + } +} + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs new file mode 100644 index 0000000000..703fb7299a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.cs @@ -0,0 +1,46 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; +// +using Microsoft.Win32; +// + +namespace WinFormsAutoScaling +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + + // + this.Font = SystemFonts.IconTitleFont; + SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged); + this.FormClosing += new FormClosingEventHandler(Form1_FormClosing); + // + } + + // + void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) + { + if (e.Category == UserPreferenceCategory.Window) + { + this.Font = SystemFonts.IconTitleFont; + } + } + // + + // + void Form1_FormClosing(object sender, FormClosingEventArgs e) + { + SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged); + } + // + } +} +// diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.resx new file mode 100644 index 0000000000..19dc0dd8b3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Program.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Program.cs new file mode 100644 index 0000000000..56d75833c7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Program.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; + +namespace WinFormsAutoScaling +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/AssemblyInfo.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..a7ed5e418b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WinFormsAutoScaling")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("WinFormsAutoScaling")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2006")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("804270f5-052d-47c6-a41e-633a8e3d7368")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Resources.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..552fb2c5e2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WinFormsAutoScaling.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WinFormsAutoScaling.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Resources.resx b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Settings.Designer.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Settings.Designer.cs new file mode 100644 index 0000000000..841aebf49d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:2.0.50727.42 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WinFormsAutoScaling.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Settings.settings b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Settings.settings new file mode 100644 index 0000000000..39645652af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/WinFormsAutoScaling.csproj b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/WinFormsAutoScaling.csproj new file mode 100644 index 0000000000..d5122a983e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/WinFormsAutoScaling/CS/WinFormsAutoScaling.csproj @@ -0,0 +1,78 @@ + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {19E5F50F-DBED-4E75-BD24-3B55763BA46A} + WinExe + Properties + WinFormsAutoScaling + WinFormsAutoScaling + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + Form + + + Form1.cs + + + + + Designer + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/powermode/cs/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/powermode/cs/form1.cs new file mode 100644 index 0000000000..2f90dcf679 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/powermode/cs/form1.cs @@ -0,0 +1,49 @@ +using System; +using System.Windows.Forms; +using Microsoft.Win32; + +namespace PowerMode1 +{ + public partial class Form1 : Form + { + // + public Form1() + { + InitializeComponent(); + SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged); + } + + void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) + { + switch (SystemInformation.PowerStatus.BatteryChargeStatus) + { + case System.Windows.Forms.BatteryChargeStatus.Low: + MessageBox.Show("Battery is running low.", "Low Battery", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + break; + case System.Windows.Forms.BatteryChargeStatus.Critical: + MessageBox.Show("Battery is critcally low.", "Critical Battery", MessageBoxButtons.OK, MessageBoxIcon.Stop); + break; + default: + // Battery is okay. + break; + } + } + // + + private void Hibernate() + { + // + if (SystemInformation.PowerStatus.BatteryChargeStatus == System.Windows.Forms.BatteryChargeStatus.Critical) + { + Application.SetSuspendState(PowerState.Hibernate, false, false); + } + // + } + + [STAThread] + static void Main() + { + Application.Run(new Form1()); + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/CS/Form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/CS/Form1.cs new file mode 100644 index 0000000000..8bbd3f744b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/CS/Form1.cs @@ -0,0 +1,78 @@ +using System; +using System.Windows.Forms; +using System.Drawing; +using System.Collections; + +//Create a Class that inherits from System.Windows.Forms.Form. +class myForm : Form +{ + public myForm() + { + InitializeComponent(); + InitializeMenuTreeView(); + } + + // + // Declare the TreeView and ContextMenuStrip + private TreeView menuTreeView; + private ContextMenuStrip docMenu; + + public void InitializeMenuTreeView() + { + // Create the TreeView. + menuTreeView = new TreeView(); + menuTreeView.Size = new Size(200, 200); + + // Create the root node. + TreeNode docNode = new TreeNode("Documents"); + + // Add some additional nodes. + docNode.Nodes.Add("phoneList.doc"); + docNode.Nodes.Add("resume.doc"); + + // Add the root nodes to the TreeView. + menuTreeView.Nodes.Add(docNode); + + // Create the ContextMenuStrip. + docMenu = new ContextMenuStrip(); + + //Create some menu items. + ToolStripMenuItem openLabel = new ToolStripMenuItem(); + openLabel.Text = "Open"; + ToolStripMenuItem deleteLabel = new ToolStripMenuItem(); + deleteLabel.Text = "Delete"; + ToolStripMenuItem renameLabel = new ToolStripMenuItem(); + renameLabel.Text = "Rename"; + + //Add the menu items to the menu. + docMenu.Items.AddRange(new ToolStripMenuItem[]{openLabel, + deleteLabel, renameLabel}); + + // Set the ContextMenuStrip property to the ContextMenuStrip. + docNode.ContextMenuStrip = docMenu; + + // Add the TreeView to the form. + this.Controls.Add(menuTreeView); + } + + // + [STAThreadAttribute] + public static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new myForm()); + } + + private void InitializeComponent() + { + + this.SuspendLayout(); + +// +// myForm +// + this.ClientSize = new System.Drawing.Size(292, 266); + this.Name = "myForm"; + this.ResumeLayout(false); + } +} \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/cs/form1.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/cs/form1.cs new file mode 100644 index 0000000000..374ae773ed --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/cs/form1.cs @@ -0,0 +1,40 @@ +// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Text; +using System.Windows.Forms; + +public class Form1 : Form +{ + private ToolStripContainer toolStripContainer1; + private ToolStrip toolStrip1; + + public Form1() + { + InitializeComponent(); + } + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.Run(new Form1()); + } + + private void InitializeComponent() + { + toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); + toolStrip1 = new System.Windows.Forms.ToolStrip(); + // Add items to the ToolStrip. + toolStrip1.Items.Add("One"); + toolStrip1.Items.Add("Two"); + toolStrip1.Items.Add("Three"); + // Add the ToolStrip to the top panel of the ToolStripContainer. + toolStripContainer1.TopToolStripPanel.Controls.Add(toolStrip1); + // Add the ToolStripContainer to the form. + Controls.Add(toolStripContainer1); + } +} +// \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cs/add.cs b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cs/add.cs new file mode 100644 index 0000000000..3de4e801da --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/csharp/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/cs/add.cs @@ -0,0 +1,19 @@ +using System.Drawing; +using System.Windows.Forms; + +public class Form1 : Form +{ + public Form1() + { + var tabPage1 = new TabPage(); + + // + tabPage1.Controls.Add(new Button()); + // + } + + static void Main() + { + Application.Run(new Form1()); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/AccessHTMLDOMControl.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/AccessHTMLDOMControl.vbproj new file mode 100644 index 0000000000..b52e29d7d8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/AccessHTMLDOMControl.vbproj @@ -0,0 +1,96 @@ + + + Debug + AnyCPU + 8.0.41021 + 2.0 + {27488D51-440E-4549-AC2D-304F5F622173} + Library + + + AccessHTMLDOMControl + AccessHTMLDOMControl + Windows + + + true + full + true + true + bin\ + AccessHTMLDOMControl.xml + 42016,42017,42018,42019,42032 + + + pdbonly + false + true + true + bin\ + AccessHTMLDOMControl.xml + 42016,42017,42018,42019,42032 + + + + + + + + + + + + + + + + + + + + True + MyApplication.myapp + + + UserControl + + + UserControl1.vb + + + + True + True + MyResources.resx + + + True + MySettings.settings + True + + + + + VbMyResourcesResXFileCodeGenerator + MyResources.vb + My.Resources + + + UserControl1.vb + + + + + MyApplicationCodeGenerator + MyApplication.vb + + + SettingsSingleFileGenerator + MySettings.vb + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..379d7f0aad --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/AssemblyInfo.vb @@ -0,0 +1,33 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyApplication.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyApplication.myapp new file mode 100644 index 0000000000..f5ae68aaf1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyApplication.myapp @@ -0,0 +1,9 @@ + + + false + false + 0 + true + 0 + 1 + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyApplication.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyApplication.vb new file mode 100644 index 0000000000..07be907157 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyApplication.vb @@ -0,0 +1,12 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyResources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyResources.resx new file mode 100644 index 0000000000..3e18af958a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyResources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyResources.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyResources.vb new file mode 100644 index 0000000000..30065a8841 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MyResources.vb @@ -0,0 +1,61 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict Off +Option Explicit On + +Imports System.IO +Imports System.Resources + +Namespace My.Resources + + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + 'This class was auto-generated by the Strongly Typed Resource Builder + 'class via a tool like ResGen or Visual Studio.NET. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + _ + Module MyResources + + Private _resMgr As System.Resources.ResourceManager + + Private _resCulture As System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Public ReadOnly Property ResourceManager() As System.Resources.ResourceManager + Get + If (_resMgr Is Nothing) Then + Dim temp As System.Resources.ResourceManager = New System.Resources.ResourceManager("$safeprojectname$.MyResources", GetType(MyResources).Assembly) + System.Threading.Thread.MemoryBarrier + _resMgr = temp + End If + Return _resMgr + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Public Property Culture() As System.Globalization.CultureInfo + Get + Return _resCulture + End Get + Set + _resCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MySettings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MySettings.settings new file mode 100644 index 0000000000..0bcb11da33 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MySettings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MySettings.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MySettings.vb new file mode 100644 index 0000000000..3d12c6fb5f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/My Project/MySettings.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict Off +Option Explicit On + + + +Partial Friend NotInheritable Class MySettings + Inherits System.Configuration.ApplicationSettingsBase + + Private Shared m_Value As MySettings + + Private Shared m_SyncObject As Object = New Object + + _ + Public Shared ReadOnly Property Value() As MySettings + Get + If (MySettings.m_Value Is Nothing) Then + System.Threading.Monitor.Enter(MySettings.m_SyncObject) + If (MySettings.m_Value Is Nothing) Then + Try + MySettings.m_Value = New MySettings + Finally + System.Threading.Monitor.Exit(MySettings.m_SyncObject) + End Try + End If + End If + Return MySettings.m_Value + End Get + End Property +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.Designer.vb new file mode 100644 index 0000000000..57ed65dbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.Designer.vb @@ -0,0 +1,40 @@ +Partial Public Class UserControl1 + Inherits System.Windows.Forms.UserControl + + _ + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + End Sub + + 'UserControl1 overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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() + ' + 'UserControl1 + ' + Me.Name = "UserControl1" + Me.Size = New System.Drawing.Size(463, 481) + Me.ResumeLayout(False) + + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.resx new file mode 100644 index 0000000000..25c2f26478 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.vb new file mode 100644 index 0000000000..654af035d3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/AccessHTMLDOMControl/vb/UserControl1.vb @@ -0,0 +1,10 @@ +Public Class UserControl1 + + ' + Private Sub UserControl1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + If (Me.Site IsNot Nothing) Then + Dim Doc As HtmlDocument = CType(Me.Site.GetService(Type.GetType("System.Windows.Forms.HtmlDocument")), HtmlDocument) + End If + End Sub + ' +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/Application/VB/source.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/Application/VB/source.vb new file mode 100644 index 0000000000..37762ea735 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/Application/VB/source.vb @@ -0,0 +1,224 @@ +' +Imports System.Drawing +Imports System.Windows.Forms +Imports System.ComponentModel +Imports System.Text +Imports System.IO + +' A simple form that represents a window in our application +Public Class AppForm1 + Inherits System.Windows.Forms.Form + + Public Sub New() + MyBase.New() + + Me.Size = New System.Drawing.Size(300, 300) + Me.Text = "AppForm1" + + End Sub + +End Class + +' A simple form that represents a window in our application +Public Class AppForm2 + Inherits System.Windows.Forms.Form + + Public Sub New() + MyBase.New() + + Me.Size = New System.Drawing.Size(300, 300) + Me.Text = "AppForm2" + + End Sub + +End Class + +' +' The class that handles the creation of the application windows +Public Class MyApplicationContext + Inherits ApplicationContext + + Private _formCount As Integer + Private _form1 As AppForm1 + Private _form2 As AppForm2 + + Private _form1Position As Rectangle + Private _form2Position As Rectangle + + Private _userData As FileStream + + ' + Public Sub New() + MyBase.New() + _formCount = 0 + + ' Handle the ApplicationExit event to know when the application is exiting. + AddHandler Application.ApplicationExit, AddressOf OnApplicationExit + + Try + ' Create a file that the application will store user specific data in. + _userData = New FileStream(Application.UserAppDataPath + "\appdata.txt", FileMode.OpenOrCreate) + + Catch e As IOException + ' Inform the user that an error occurred. + MessageBox.Show("An error occurred while attempting to show the application." + + "The error is:" + e.ToString()) + + ' Exit the current thread instead of showing the windows. + ExitThread() + End Try + + ' Create both application forms and handle the Closed event + ' to know when both forms are closed. + _form1 = New AppForm1() + AddHandler _form1.Closed, AddressOf OnFormClosed + AddHandler _form1.Closing, AddressOf OnFormClosing + _formCount = _formCount + 1 + + _form2 = New AppForm2() + AddHandler _form2.Closed, AddressOf OnFormClosed + AddHandler _form2.Closing, AddressOf OnFormClosing + _formCount = _formCount + 1 + + ' Get the form positions based upon the user specific data. + If (ReadFormDataFromFile()) Then + ' If the data was read from the file, set the form + ' positions manually. + _form1.StartPosition = FormStartPosition.Manual + _form2.StartPosition = FormStartPosition.Manual + + _form1.Bounds = _form1Position + _form2.Bounds = _form2Position + End If + + ' Show both forms. + _form1.Show() + _form2.Show() + End Sub + + Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs) + ' When the application is exiting, write the application data to the + ' user file and close it. + WriteFormDataToFile() + + Try + ' Ignore any errors that might occur while closing the file handle. + _userData.Close() + Catch + End Try + End Sub + ' + + Private Sub OnFormClosing(ByVal sender As Object, ByVal e As CancelEventArgs) + ' When a form is closing, remember the form position so it + ' can be saved in the user data file. + If TypeOf sender Is AppForm1 Then + _form1Position = CType(sender, Form).Bounds + ElseIf TypeOf sender Is AppForm2 Then + _form2Position = CType(sender, Form).Bounds + End If + End Sub + + ' + Private Sub OnFormClosed(ByVal sender As Object, ByVal e As EventArgs) + ' When a form is closed, decrement the count of open forms. + + ' When the count gets to 0, exit the app by calling + ' ExitThread(). + _formCount = _formCount - 1 + If (_formCount = 0) Then + ExitThread() + End If + End Sub + ' + + Private Function WriteFormDataToFile() As Boolean + ' Write the form positions to the file. + Dim encoding As UTF8Encoding = New UTF8Encoding() + + Dim rectConv As RectangleConverter = New RectangleConverter() + Dim form1pos As String = rectConv.ConvertToString(_form1Position) + Dim form2pos As String = rectConv.ConvertToString(_form2Position) + + Dim dataToWrite As Byte() = encoding.GetBytes("~" + form1pos + "~" + form2pos) + + Try + ' Set the write position to the start of the file and write + _userData.Seek(0, SeekOrigin.Begin) + _userData.Write(dataToWrite, 0, dataToWrite.Length) + _userData.Flush() + + _userData.SetLength(dataToWrite.Length) + Return True + + Catch + ' An error occurred while attempting to write, return false. + Return False + End Try + + End Function + + Private Function ReadFormDataFromFile() As Boolean + ' Read the form positions from the file. + Dim encoding As UTF8Encoding = New UTF8Encoding() + Dim data As String + + If (_userData.Length <> 0) Then + Dim dataToRead(_userData.Length - 1) As Byte + + Try + ' Set the read position to the start of the file and read. + _userData.Seek(0, SeekOrigin.Begin) + _userData.Read(dataToRead, 0, dataToRead.Length) + + Catch e As IOException + Dim errorInfo As String = e.ToString() + ' An error occurred while attempt to read, return false. + Return False + End Try + + ' Parse out the data to get the window rectangles + data = encoding.GetString(dataToRead) + + Try + ' Convert the string data to rectangles + Dim rectConv As RectangleConverter = New RectangleConverter() + Dim form1pos As String = data.Substring(1, data.IndexOf("~", 1) - 1) + + _form1Position = CType(rectConv.ConvertFromString(form1pos), Rectangle) + + Dim form2pos As String = data.Substring(data.IndexOf("~", 1) + 1) + _form2Position = CType(rectConv.ConvertFromString(form2pos), Rectangle) + + Return True + + Catch + ' Error occurred while attempting to convert the rectangle data. + ' Return false to use default values. + Return False + End Try + + Else + ' No data in the file, return false to use default values. + Return False + End If + End Function + +End Class + +' +Public Module MyApplication + Public Sub Main() + ' Create the MyApplicationContext, that derives from ApplicationContext, + ' that manages when the application should exit. + + Dim context As MyApplicationContext = New MyApplicationContext() + + ' Run the application with the specific context. It will exit when + ' all forms are closed. + Application.Run(context) + End Sub +End Module +' +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/ApplicationSettings.Architecture.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/ApplicationSettings.Architecture.vbproj new file mode 100644 index 0000000000..6c7b703451 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/ApplicationSettings.Architecture.vbproj @@ -0,0 +1,103 @@ + + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {2052A2CE-1D66-40A2-9C64-DD04B931EB2B} + WinExe + ApplicationSettings.Architecture.My.MyApplication + ApplicationSettings.Architecture + ApplicationSettings.Architecture + WindowsForms + + + true + full + true + true + bin\Debug\ + ApplicationSettings.Architecture.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + pdbonly + false + true + true + bin\Release\ + ApplicationSettings.Architecture.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + + + + + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/DummyProviderClass.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/DummyProviderClass.vb new file mode 100644 index 0000000000..83b0931ab0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/DummyProviderClass.vb @@ -0,0 +1,29 @@ +' +Imports System.Configuration + + _ +Public Class CustomSettings + Inherits ApplicationSettingsBase + + ' Implementation goes here. +End Class +' + +Public MustInherit Class DummyProviderBase + Public MustOverride Property ApplicationName() As String +End Class + +Public Class DummyProviderClass + Inherits DummyProviderBase + + ' + Public Overrides Property ApplicationName() As String + Get + ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + End Get + Set(ByVal value As String) + ' Do nothing. + End Set + End Property + ' +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/Form1.Designer.vb new file mode 100644 index 0000000000..aa7d61cb98 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/Form1.Designer.vb @@ -0,0 +1,27 @@ + _ +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) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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 + Me.Text = "Form1" + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/Form1.vb new file mode 100644 index 0000000000..17d659563f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/Form1.vb @@ -0,0 +1,3 @@ +Public Class Form1 + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Application.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Application.Designer.vb new file mode 100644 index 0000000000..0a291ed38a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Application.Designer.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.ApplicationSettings.Architecture.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Application.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Application.myapp new file mode 100644 index 0000000000..1243847fd9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Application.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..ef8e4f60ef --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,34 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Resources.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Resources.Designer.vb new file mode 100644 index 0000000000..b14dfbed7a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ApplicationSettings.Architecture.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Resources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Settings.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Settings.Designer.vb new file mode 100644 index 0000000000..75e7066aa1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.ApplicationSettings.Architecture.My.MySettings + Get + Return Global.ApplicationSettings.Architecture.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Settings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Settings.settings new file mode 100644 index 0000000000..85b890b3c6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Architecture/VB/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/AppSettingsArchitectureProjectVB.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/AppSettingsArchitectureProjectVB.vbproj new file mode 100644 index 0000000000..e69c174e2b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/AppSettingsArchitectureProjectVB.vbproj @@ -0,0 +1,107 @@ + + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {BA320BE8-C1E9-46CE-B5E9-2CFB08216B95} + WinExe + AppSettingsArchitectureProjectVB.My.MyApplication + AppSettingsArchitectureProjectVB + AppSettingsArchitectureProjectVB + WindowsForms + + + true + full + true + true + bin\Debug\ + AppSettingsArchitectureProjectVB.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + pdbonly + false + true + true + bin\Release\ + AppSettingsArchitectureProjectVB.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + + + + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + + Designer + Form1.vb + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.Designer.vb new file mode 100644 index 0000000000..5fb59b2bc0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.Designer.vb @@ -0,0 +1,35 @@ + _ +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) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.resx new file mode 100644 index 0000000000..19dc0dd8b3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.vb new file mode 100644 index 0000000000..9810aba401 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/Form1.vb @@ -0,0 +1,17 @@ +Public Class Form1 + ' + Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing + Mus.Save() + End Sub + ' + + ' + Dim Mus As MyUserSettings + + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + Mus = New MyUserSettings() + Mus.BackgroundColor = Color.AliceBlue + Me.DataBindings.Add(New Binding("BackColor", Mus, "BackgroundColor")) + End Sub + ' +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Application.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Application.Designer.vb new file mode 100644 index 0000000000..1554e639d5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Application.Designer.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.AppSettingsArchitectureProjectVB.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Application.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Application.myapp new file mode 100644 index 0000000000..1243847fd9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Application.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..ccf8a20bfa --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,34 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Resources.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Resources.Designer.vb new file mode 100644 index 0000000000..5cca308699 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("AppSettingsArchitectureProjectVB.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Resources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Settings.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Settings.Designer.vb new file mode 100644 index 0000000000..c707b6ac00 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.AppSettingsArchitectureProjectVB.My.MySettings + Get + Return Global.AppSettingsArchitectureProjectVB.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Settings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Settings.settings new file mode 100644 index 0000000000..85b890b3c6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/MyAppSettings.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/MyAppSettings.vb new file mode 100644 index 0000000000..c4029cbab1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ApplicationSettings.Create/VB/MyAppSettings.vb @@ -0,0 +1,18 @@ +' +Imports System.Configuration + +Public Class MyUserSettings + Inherits ApplicationSettingsBase + _ + _ + Public Property BackgroundColor() As Color + Get + BackgroundColor = Me("BackgroundColor") + End Get + + Set(ByVal value As Color) + Me("BackgroundColor") = value + End Set + End Property +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.Designer.vb new file mode 100644 index 0000000000..76ce0bd0a7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.Designer.vb @@ -0,0 +1,52 @@ +Public Partial Class CodeForm + Inherits System.Windows.Forms.Form + + _ + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.RichTextBox1 = New System.Windows.Forms.RichTextBox + Me.SuspendLayout() + ' + 'RichTextBox1 + ' + Me.RichTextBox1.Dock = System.Windows.Forms.DockStyle.Fill + Me.RichTextBox1.Location = New System.Drawing.Point(0, 0) + Me.RichTextBox1.Name = "RichTextBox1" + Me.RichTextBox1.Size = New System.Drawing.Size(703, 459) + Me.RichTextBox1.TabIndex = 0 + Me.RichTextBox1.Text = "" + ' + 'CodeForm + ' + Me.ClientSize = New System.Drawing.Size(703, 459) + Me.Controls.Add(Me.RichTextBox1) + Me.Name = "CodeForm" + Me.Text = "CodeForm" + Me.ResumeLayout(False) + + End Sub + Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.resx new file mode 100644 index 0000000000..25c2f26478 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.vb new file mode 100644 index 0000000000..a286c10824 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/CodeForm.vb @@ -0,0 +1,17 @@ +Public Class CodeForm + ' + Public Property Code() As String + Get + If (RichTextBox1.Text IsNot Nothing) Then + Code = RichTextBox1.Text + Else + Code = "" + End If + End Get + + Set(ByVal value As String) + RichTextBox1.Text = value + End Set + End Property + ' +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/DisplayWebBrowserCodeVB.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/DisplayWebBrowserCodeVB.vbproj new file mode 100644 index 0000000000..798c9c7f8b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/DisplayWebBrowserCodeVB.vbproj @@ -0,0 +1,105 @@ + + + + Debug + AnyCPU + 8.0.41025 + 2.0 + {BF207E8C-EBC4-4249-8D43-248022609973} + WinExe + DisplayWebBrowserCodeVB.My.MyApplication + DisplayWebBrowserCodeVB + DisplayWebBrowserCodeVB + WindowsForms + + + true + full + true + true + bin\ + DisplayWebBrowserCodeVB.xml + 42016,42017,42018,42019,42032,42036 + + + pdbonly + false + true + true + bin\ + DisplayWebBrowserCodeVB.xml + 42016,42017,42018,42019,42032,42036 + + + + + + + + + + + + + + + + + + + + CodeForm.vb + + + Form + + + Form + + + Form1.vb + Form + + + + True + MyApplication.myapp + + + True + True + MyResources.resx + + + True + MySettings.settings + True + + + + + + CodeForm.vb + + + Form1.vb + + + VbMyResourcesResXFileCodeGenerator + MyResources.vb + My.Resources + + + + + + MyApplicationCodeGenerator + MyApplication.vb + + + SettingsSingleFileGenerator + MySettings.vb + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.Designer.vb new file mode 100644 index 0000000000..a31b658acc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.Designer.vb @@ -0,0 +1,70 @@ +Partial Public Class Form1 + Inherits System.Windows.Forms.Form + + _ + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.WebBrowser1 = New System.Windows.Forms.WebBrowser + Me.Button1 = New System.Windows.Forms.Button + Me.Button2 = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + 'WebBrowser1 + ' + Me.WebBrowser1.Location = New System.Drawing.Point(12, 186) + Me.WebBrowser1.Name = "WebBrowser1" + Me.WebBrowser1.Size = New System.Drawing.Size(677, 250) + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 12) + Me.Button1.Name = "Button1" + Me.Button1.TabIndex = 1 + Me.Button1.Text = "Button1" + ' + 'Button2 + ' + Me.Button2.Location = New System.Drawing.Point(93, 12) + Me.Button2.Name = "Button2" + Me.Button2.TabIndex = 3 + Me.Button2.Text = "Button2" + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(701, 448) + Me.Controls.Add(Me.Button2) + Me.Controls.Add(Me.Button1) + Me.Controls.Add(Me.WebBrowser1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + Friend WithEvents WebBrowser1 As System.Windows.Forms.WebBrowser + Friend WithEvents Button1 As System.Windows.Forms.Button + Friend WithEvents Button2 As System.Windows.Forms.Button + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.resx new file mode 100644 index 0000000000..25c2f26478 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.vb new file mode 100644 index 0000000000..b0cf745d99 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/Form1.vb @@ -0,0 +1,18 @@ +Public Class Form1 + + ' + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + Dim elem As HtmlElement + + If (WebBrowser1.Document IsNot Nothing) Then + Dim cf As New CodeForm() + Dim elems As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("HTML") + If (elems.Count = 1) Then + elem = elems(0) + cf.Code = elem.OuterHtml + cf.Show() + End If + End If + End Sub + ' +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..634453e6ec --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,34 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyApplication.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyApplication.myapp new file mode 100644 index 0000000000..b456038a82 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyApplication.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyApplication.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyApplication.vb new file mode 100644 index 0000000000..7f8739ce8f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyApplication.vb @@ -0,0 +1,30 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + Partial Class MyApplication + + Public Sub New() + MyBase.New(ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = False + Me.EnableVisualStyles = True + Me.SaveMySettingsOnExit = True + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.DisplayWebBrowserCodeVB.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyEvents.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyEvents.vb new file mode 100644 index 0000000000..b6dfb0a6eb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyEvents.vb @@ -0,0 +1,15 @@ +Namespace My + + 'Use the editor window dropdowns in the Application pane of the Project Designer to handle MyApplication Events + ' + 'Startup: Raised when the application starts, before the startup form is created. + 'Shutdown: Raised after all application forms are closed. This event is not raised if the application is terminating abnormally. + 'UnhandledException: Raised if the application encounters an unhandled exception. + 'StartupNextInstance: Raised when launching a single-instance application and the application is already active. + 'NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. + + Partial Friend Class MyApplication + + End Class + +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyResources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyResources.resx new file mode 100644 index 0000000000..3e18af958a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyResources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyResources.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyResources.vb new file mode 100644 index 0000000000..0600b0a45e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MyResources.vb @@ -0,0 +1,61 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict Off +Option Explicit On + +Imports System.IO +Imports System.Resources + +Namespace My.Resources + + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + 'This class was auto-generated by the Strongly Typed Resource Builder + 'class via a tool like ResGen or Visual Studio.NET. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + _ + Module MyResources + + Private _resMgr As System.Resources.ResourceManager + + Private _resCulture As System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Public ReadOnly Property ResourceManager() As System.Resources.ResourceManager + Get + If (_resMgr Is Nothing) Then + Dim temp As System.Resources.ResourceManager = New System.Resources.ResourceManager("DisplayWebBrowserCodeVB.MyResources", GetType(MyResources).Assembly) + System.Threading.Thread.MemoryBarrier + _resMgr = temp + End If + Return _resMgr + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Public Property Culture() As System.Globalization.CultureInfo + Get + Return _resCulture + End Get + Set + _resCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MySettings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MySettings.settings new file mode 100644 index 0000000000..c2dbd5cad3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MySettings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MySettings.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MySettings.vb new file mode 100644 index 0000000000..3d12c6fb5f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/My Project/MySettings.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict Off +Option Explicit On + + + +Partial Friend NotInheritable Class MySettings + Inherits System.Configuration.ApplicationSettingsBase + + Private Shared m_Value As MySettings + + Private Shared m_SyncObject As Object = New Object + + _ + Public Shared ReadOnly Property Value() As MySettings + Get + If (MySettings.m_Value Is Nothing) Then + System.Threading.Monitor.Enter(MySettings.m_SyncObject) + If (MySettings.m_Value Is Nothing) Then + Try + MySettings.m_Value = New MySettings + Finally + System.Threading.Monitor.Exit(MySettings.m_SyncObject) + End Try + End If + End If + Return MySettings.m_Value + End Get + End Property +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/app.config b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/app.config new file mode 100644 index 0000000000..f636923451 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/DisplayWebBrowserCode/VB/app.config @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb new file mode 100644 index 0000000000..76808170ec --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/LinesCurvesAndShapes/VB/Class1.vb @@ -0,0 +1,301 @@ +Option Explicit On +Option Strict On + +Imports System.Diagnostics +Imports System.Windows.Forms +Imports System.Xml +Imports System.Data +Imports System.Collections +Imports System.Drawing +Imports System.Drawing.Drawing2D + +Public Class LinesCurvesAndShapes + Inherits Form + Dim myPen As Pen = Pens.Black + Dim mySolidBrush As SolidBrush = CType(Brushes.Red,SolidBrush) + Dim myGraphicsPath As New GraphicsPath() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New LinesCurvesAndShapes()) + End Sub + + ' 0195df81-66be-452d-bb53-5a582ebfdc09 + ' Vector Graphics Overview + Public Sub Method11(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.DrawRectangle(myPen, 20, 10, 100, 50) + + ' + End Sub + ' 08d2cc9a-dc9d-4eed-bcbb-2c8e2ca5d3ae + ' Open and Closed Curves in GDI+ + Public Sub Method21(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.FillPie(mySolidBrush, 0, 0, 140, 70, 0, 120) + myGraphics.DrawArc(myPen, 0, 0, 140, 70, 0, 120) + + ' + End Sub + Public Sub Method22(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myPointArray As Point() = _ + {New Point(0, 0), New Point(60, 20), New Point(40, 50)} + myGraphics.DrawClosedCurve(myPen, myPointArray) + myGraphics.FillClosedCurve(mySolidBrush, myPointArray) + + ' + End Sub + Public Sub Method23(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim mySolidBrush As New SolidBrush(Color.Aqua) + Dim myGraphicsPath As New GraphicsPath() + + Dim myPointArray As Point() = { _ + New Point(15, 20), _ + New Point(20, 40), _ + New Point(50, 30)} + + Dim myFontFamily As New FontFamily("Times New Roman") + Dim myPointF As New PointF(50, 20) + Dim myStringFormat As New StringFormat() + + myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180) + myGraphicsPath.AddCurve(myPointArray) + myGraphicsPath.AddString("a string in a path", myFontFamily, _ + 0, 24, myPointF, myStringFormat) + myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110) + + myGraphics.FillPath(mySolidBrush, myGraphicsPath) + myGraphics.DrawPath(myPen, myGraphicsPath) + + ' + End Sub + ' 09b3797a-6294-422d-9adf-a5a0a7695c0c + ' Cardinal Splines in GDI+ + Public Sub Method31(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + Dim myPointArray() As Point = New Point() {New Point(10, 10), _ + New Point(50, 40), New Point(123, 200)} + ' + myGraphics.DrawCurve(myPen, myPointArray, 1.5F) + + ' + End Sub + ' 30b25aae-e3eb-4479-bdb8-187cf651fc84 + ' Pens, Lines, and Rectangles in GDI+ + Public Sub Method41(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.DrawLine(myPen, 4, 2, 12, 6) + + ' + End Sub + Public Sub Method42(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myStartPoint As New Point(4, 2) + Dim myEndPoint As New Point(12, 6) + myGraphics.DrawLine(myPen, myStartPoint, myEndPoint) + + ' + End Sub + Public Sub Method43(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myPen As New Pen(Color.Blue, 2) + myGraphics.DrawLine(myPen, 0, 0, 60, 30) + + ' + End Sub + Public Sub Method44(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myPen.DashStyle = DashStyle.Dash + myGraphics.DrawLine(myPen, 100, 50, 300, 80) + + ' + End Sub + Public Sub Method45(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.DrawRectangle(myPen, 100, 50, 80, 40) + + ' + End Sub + Public Sub Method46(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myRectangle As New Rectangle(100, 50, 80, 40) + myGraphics.DrawRectangle(myPen, myRectangle) + + ' + End Sub + ' 34f35133-a835-4ca4-81f6-0dfedee8b683 + ' Ellipses and Arcs in GDI+ + Public Sub Method51(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.DrawEllipse(myPen, 100, 50, 80, 40) + + ' + End Sub + Public Sub Method52(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myRectangle As New Rectangle(100, 50, 80, 40) + myGraphics.DrawEllipse(myPen, myRectangle) + + ' + End Sub + Public Sub Method53(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.DrawArc(myPen, 100, 50, 140, 70, 30, 180) + + ' + End Sub + ' 52184f9b-16dd-4bbd-85be-029112644ceb + ' Regions in GDI+ + Public Sub Method61(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + Dim myRegion As New Region(Me.ClientRectangle) + ' + myGraphics.FillRegion(mySolidBrush, myRegion) + + ' + End Sub + ' 5774ce1e-87d4-4bc7-88c4-4862052781b8 + ' Bézier Splines in GDI+ + Public Sub Method71(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.DrawBezier(myPen, 0, 0, 40, 20, 80, 150, 100, 10) + + ' + End Sub + ' 810da1a4-c136-4abf-88df-68e49efdd8d4 + ' Antialiasing with Lines and Curves + Public Sub Method81(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphics.SmoothingMode = SmoothingMode.AntiAlias + myGraphics.DrawLine(myPen, 0, 0, 12, 8) + + ' + End Sub + ' 8b5f71d9-d2f0-4540-9c41-740f90fd4c26 + ' Restricting the Drawing Surface in GDI+ + Public Sub Method91(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + Dim myRegion As New Region(Me.ClientRectangle) + ' + myGraphics.Clip = myRegion + myGraphics.DrawLine(myPen, 0, 0, 200, 200) + + ' + End Sub + ' a5500dec-666c-41fd-9da3-2169dd89c5eb + ' Graphics Paths in GDI+ + Public Sub Method101(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + myGraphicsPath.AddLine(0, 0, 30, 20) + myGraphicsPath.AddEllipse(20, 20, 20, 40) + myGraphicsPath.AddBezier(30, 60, 70, 60, 50, 30, 100, 10) + myGraphics.DrawPath(myPen, myGraphicsPath) + + ' + End Sub + Public Sub Method102(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + Dim graphicsPath1 As New GraphicsPath() + Dim graphicsPath2 As New GraphicsPath() + ' + myGraphicsPath.AddPath(graphicsPath1, False) + myGraphicsPath.AddPath(graphicsPath2, False) + + ' + End Sub + Public Sub Method103(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myGraphicsPath As New GraphicsPath() + + Dim myPointArray As Point() = { _ + New Point(5, 30), _ + New Point(20, 40), _ + New Point(50, 30)} + + Dim myFontFamily As New FontFamily("Times New Roman") + Dim myPointF As New PointF(50, 20) + Dim myStringFormat As New StringFormat() + + myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180) + myGraphicsPath.StartFigure() + myGraphicsPath.AddCurve(myPointArray) + myGraphicsPath.AddString("a string in a path", myFontFamily, _ + 0, 24, myPointF, myStringFormat) + myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110) + myGraphics.DrawPath(myPen, myGraphicsPath) + + ' + End Sub + ' a72213d2-d69a-4c2b-a75c-be7b20390c13 + ' Polygons in GDI+ + Public Sub Method111(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myPointArray As Point() = _ + {New Point(0, 0), New Point(50, 30), New Point(30, 60)} + myGraphics.DrawPolygon(myPen, myPointArray) + + ' + End Sub + ' e863e2a7-0294-4130-99b6-f1ea3201e7cd + ' Brushes and Filled Shapes in GDI+ + Public Sub Method121(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim mySolidBrush As New SolidBrush(Color.Red) + myGraphics.FillEllipse(mySolidBrush, 0, 0, 60, 40) + + ' + End Sub + Public Sub Method122() + ' + Dim myHatchBrush As _ + New HatchBrush(HatchStyle.Vertical, Color.Blue, Color.Green) + + ' + End Sub + Public Sub Method123(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + ' + Dim myImage As Image = Image.FromFile("MyTexture.bmp") + Dim myTextureBrush As New TextureBrush(myImage) + myGraphics.FillEllipse(myTextureBrush, 0, 0, 100, 50) + + ' + End Sub + Public Sub Method124(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + Dim myRectangle As Rectangle = Me.ClientRectangle + ' + Dim myLinearGradientBrush As New LinearGradientBrush( _ + myRectangle, _ + Color.Blue, _ + Color.Green, _ + LinearGradientMode.Horizontal) + myGraphics.FillEllipse(myLinearGradientBrush, myRectangle) + + ' + End Sub +End Class + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.Designer.vb new file mode 100644 index 0000000000..430da03cc8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.Designer.vb @@ -0,0 +1,46 @@ + _ +Partial Public Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.WebBrowser1 = New System.Windows.Forms.WebBrowser + Me.SuspendLayout() + ' + 'WebBrowser1 + ' + Me.WebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill + Me.WebBrowser1.Location = New System.Drawing.Point(0, 0) + Me.WebBrowser1.Name = "WebBrowser1" + Me.WebBrowser1.Size = New System.Drawing.Size(623, 299) + Me.WebBrowser1.Url = New System.Uri("c:\userfiles\jayallen\ManagedDOMStyles\test.htm", System.UriKind.Absolute) + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(623, 299) + Me.Controls.Add(Me.WebBrowser1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + Friend WithEvents WebBrowser1 As System.Windows.Forms.WebBrowser + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.resx new file mode 100644 index 0000000000..02bbfa2c72 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.vb new file mode 100644 index 0000000000..2414372afb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/Form1.vb @@ -0,0 +1,32 @@ +' + _ +Public Class Form1 + + Dim SG As StyleGenerator = Nothing + Dim Elem As HtmlElement = Nothing + Dim WithEvents DocumentEvents As HtmlDocument + + Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted + SG = New StyleGenerator() + DocumentEvents = WebBrowser1.Document + End Sub + + Private Sub Document_MouseOver(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles DocumentEvents.MouseOver + Elem = WebBrowser1.Document.GetElementFromPoint(e.MousePosition) + If Elem.TagName.Equals("DIV") Then + SG.ParseStyleString(Elem.Style) + SG.SetStyle("font-style", "italic") + Elem.Style = SG.GetStyleString() + End If + End Sub + + Private Sub Document_MouseLeave(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles DocumentEvents.MouseLeave + If (Elem IsNot Nothing) Then + SG.RemoveStyle("font-style") + Elem.Style = SG.GetStyleString() + ' Reset, since we may mouse over a new DIV element next time. + SG.Clear() + End If + End Sub +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/ManagedDOMStylesVB.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/ManagedDOMStylesVB.vbproj new file mode 100644 index 0000000000..08523c4360 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/ManagedDOMStylesVB.vbproj @@ -0,0 +1,96 @@ + + + + Debug + AnyCPU + 8.0.50304 + 2.0 + {E51D84AE-820E-4429-BF77-C7E728AD76E7} + WinExe + ManagedDOMStylesVB.My.MyApplication + ManagedDOMStylesVB + ManagedDOMStylesVB + WindowsForms + + + true + full + true + true + bin\Debug\ + ManagedDOMStylesVB.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + pdbonly + false + true + true + bin\Release\ + ManagedDOMStylesVB.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + + + Form1.vb + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + Settings.Designer.vb + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Application.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Application.Designer.vb new file mode 100644 index 0000000000..d87743a485 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Application.Designer.vb @@ -0,0 +1,37 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50304.0 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + +Namespace My + + 'NOTE: This file is auto-generated, do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to project properties or double-click on the My Project node in the + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Class MyApplication + + _ + Public Sub New() + MyBase.New(Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.ManagedDOMStylesVB.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Application.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Application.myapp new file mode 100644 index 0000000000..1243847fd9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Application.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/ApplicationEvents.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/ApplicationEvents.vb new file mode 100644 index 0000000000..31b18beb73 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/ApplicationEvents.vb @@ -0,0 +1,15 @@ +Namespace My + + 'The following events are available for MyApplication + ' + 'Startup: Raised when the application starts, before the startup form is created. + 'Shutdown: Raised after all application forms are closed. This event is not raised if the application is terminating abnormally. + 'UnhandledException: Raised if the application encounters an unhandled exception. + 'StartupNextInstance: Raised when launching a single-instance application and the application is already active. + 'NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. + + Class MyApplication + + End Class + +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..297073b22f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,36 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Resources.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Resources.Designer.vb new file mode 100644 index 0000000000..0c1117df04 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Resources.Designer.vb @@ -0,0 +1,64 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50304.0 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ''' + ''' A strongly-typed resource class, for looking up localized strings, etc. + ''' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ''' + ''' Returns the cached ResourceManager instance used by this class. + ''' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If (resourceMan Is Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ManagedDOMStylesVB.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ''' + ''' Overrides the current thread's CurrentUICulture property for all + ''' resource lookups using this strongly typed resource class. + ''' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Resources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Settings.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Settings.Designer.vb new file mode 100644 index 0000000000..af1100fc9a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Settings.Designer.vb @@ -0,0 +1,66 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50304.0 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + + + + _ +Partial Friend NotInheritable Class Settings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As Settings = New Settings + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Object, ByVal e As EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As Settings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If +#End If + Return defaultInstance + End Get + End Property +End Class + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.ManagedDOMStylesVB.Settings + Get + Return Global.ManagedDOMStylesVB.Settings.Default + End Get + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Settings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Settings.settings new file mode 100644 index 0000000000..39645652af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/StyleGenerator.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/StyleGenerator.vb new file mode 100644 index 0000000000..1a3009a4b6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ManagedDOMStyles/VB/StyleGenerator.vb @@ -0,0 +1,90 @@ +' +Imports System.Collections.Generic +Imports System.Text + +Public Class StyleGenerator + Dim styleDB As Dictionary(Of String, String) + + Public Sub New() + styleDB = New Dictionary(Of String, String)() + End Sub + + + Public Function ContainsStyle(ByVal name As String) As Boolean + Return styleDB.ContainsKey(name) + End Function + + + Public Function SetStyle(ByVal name As String, ByVal value As String) As String + Dim oldValue As String = "" + + If (Not name.Length > 0) Then + Throw New ArgumentException("Parameter name cannot be zero-length.") + End If + If (Not value.Length > 0) Then + Throw New ArgumentException("Parameter value cannot be zero-length.") + End If + + If (styleDB.ContainsKey(name)) Then + oldValue = styleDB(name) + End If + + styleDB(name) = value + + Return oldValue + End Function + + Public Function GetStyle(ByVal name As String) As String + If (Not name.Length > 0) Then + Throw New ArgumentException("Parameter name cannot be zero-length.") + End If + + If (styleDB.ContainsKey(name)) Then + Return styleDB(name) + Else + Return "" + End If + End Function + + Public Sub RemoveStyle(ByVal name As String) + If (styleDB.ContainsKey(name)) Then + styleDB.Remove(name) + End If + End Sub + + Public Function GetStyleString() As String + If (styleDB.Count > 0) Then + Dim styleString As New StringBuilder("") + Dim key As String + For Each key In styleDB.Keys + styleString.Append(String.Format("{0}:{1};", CType(key, Object), CType(styleDB(key), Object))) + Next key + + Return styleString.ToString() + Else + Return "" + End If + End Function + + Public Sub ParseStyleString(ByVal styles As String) + If (styles.Length) > 0 Then + Dim stylePairs As String() = styles.Split(New Char() {";"c}) + Dim stylePair As String + For Each stylePair In stylePairs + If (stylePairs.Length > 0) Then + Dim styleNameValue As String() = stylePair.Split(New Char() {":"c}) + If (styleNameValue.Length = 2) Then + styleDB(styleNameValue(0)) = styleNameValue(1) + End If + End If + Next stylePair + End If + End Sub + + + Public Sub Clear() + styleDB.Clear() + End Sub +End Class +' + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/Form1.Designer.vb new file mode 100644 index 0000000000..03d16f9aab --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/Form1.Designer.vb @@ -0,0 +1,95 @@ +Partial Public Class Form1 + Inherits System.Windows.Forms.Form + + _ + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.firstName = New System.Windows.Forms.TextBox + Me.lastName = New System.Windows.Forms.TextBox + Me.PhoneMask = New System.Windows.Forms.MaskedTextBox + Me.NextButton = New System.Windows.Forms.Button + Me.PreviousButton = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + 'firstName + ' + Me.firstName.Location = New System.Drawing.Point(26, 13) + Me.firstName.Name = "firstName" + Me.firstName.Size = New System.Drawing.Size(189, 20) + Me.firstName.TabIndex = 0 + ' + 'lastName + ' + Me.lastName.Location = New System.Drawing.Point(222, 13) + Me.lastName.Name = "lastName" + Me.lastName.Size = New System.Drawing.Size(207, 20) + Me.lastName.TabIndex = 1 + ' + 'PhoneMask + ' + Me.PhoneMask.Location = New System.Drawing.Point(436, 13) + Me.PhoneMask.Mask = "(009)-000-0000 x9999" + Me.PhoneMask.Name = "PhoneMask" + Me.PhoneMask.Size = New System.Drawing.Size(133, 20) + Me.PhoneMask.TabIndex = 2 + ' + 'NextButton + ' + Me.NextButton.Location = New System.Drawing.Point(685, 10) + Me.NextButton.Name = "NextButton" + Me.NextButton.Size = New System.Drawing.Size(104, 23) + Me.NextButton.TabIndex = 3 + Me.NextButton.Text = "Next" + ' + 'PreviousButton + ' + Me.PreviousButton.Location = New System.Drawing.Point(576, 10) + Me.PreviousButton.Name = "PreviousButton" + Me.PreviousButton.Size = New System.Drawing.Size(102, 23) + Me.PreviousButton.TabIndex = 4 + Me.PreviousButton.Text = "Previous" + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(840, 57) + Me.Controls.Add(Me.PreviousButton) + Me.Controls.Add(Me.NextButton) + Me.Controls.Add(Me.PhoneMask) + Me.Controls.Add(Me.lastName) + Me.Controls.Add(Me.firstName) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + Friend WithEvents firstName As System.Windows.Forms.TextBox + Friend WithEvents lastName As System.Windows.Forms.TextBox + Friend WithEvents PhoneMask As System.Windows.Forms.MaskedTextBox + Friend WithEvents NextButton As System.Windows.Forms.Button + Friend WithEvents PreviousButton As System.Windows.Forms.Button + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/form1.vb new file mode 100644 index 0000000000..0e0e6c58ce --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/form1.vb @@ -0,0 +1,79 @@ +' +Imports System.Data.SqlClient + +Public Class Form1 + Dim WithEvents CurrentBinding, PhoneBinding As Binding + Dim EmployeesTable As New DataSet() + Dim sc As SqlConnection + Dim DataConnect As SqlDataAdapter + + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + DoMaskedBinding() + End Sub + + Private Sub DoMaskedBinding() + Try + sc = New SqlConnection("Data Source=localhost;Initial Catalog=NORTHWIND;Integrated Security=SSPI") + sc.Open() + Catch ex As Exception + MessageBox.Show(ex.Message) + Application.Exit() + End Try + + DataConnect = New SqlDataAdapter("SELECT * FROM Employees", sc) + DataConnect.Fill(EmployeesTable, "Employees") + + ' Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects + ' before adding them to the control - otherwise, we won't get a Format event on the + ' initial load. + Try + CurrentBinding = New Binding("Text", EmployeesTable, "Employees.FirstName") + firstName.DataBindings.Add(CurrentBinding) + CurrentBinding = New Binding("Text", EmployeesTable, "Employees.LastName") + lastName.DataBindings.Add(CurrentBinding) + PhoneBinding = New Binding("Text", EmployeesTable, "Employees.HomePhone") + PhoneMask.DataBindings.Add(PhoneBinding) + Catch ex As Exception + MessageBox.Show(ex.Message) + Application.Exit() + End Try + End Sub + + Private Sub PhoneBinding_Format(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Format + Dim Ext As String + + Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView) + If (CurrentRow("Extension") Is Nothing) Then + Ext = "" + Else + Ext = CurrentRow("Extension").ToString() + End If + + e.Value = e.Value.ToString().Trim() & " x" & Ext + End Sub + + Private Sub PhoneBinding_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Parse + Dim PhoneNumberAndExt As String = e.Value.ToString() + + Dim ExtIndex As Integer = PhoneNumberAndExt.IndexOf("x") + Dim Ext As String = PhoneNumberAndExt.Substring(ExtIndex).Trim() + Dim PhoneNumber As String = PhoneNumberAndExt.Substring(0, ExtIndex).Trim() + + ' Get the current binding object, and set the new extension manually. + Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView) + ' Remove the "x" from the extension. + CurrentRow("Extension") = CObj(Ext.Substring(1)) + + ' Return the phone number. + e.Value = PhoneNumber + End Sub + + Private Sub NextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextButton.Click + Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position + 1 + End Sub + + Private Sub PreviousButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousButton.Click + Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position - 1 + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/makefile new file mode 100644 index 0000000000..fa36106805 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/MaskedTextBoxData/VB/makefile @@ -0,0 +1,2 @@ +all: + vbc /t:library /out:mydll.dll Form1.Designer.vb form1.vb /imports:system.windows.forms,system.drawing,system.data \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AsyncOperationManager/VB/primenumbercalculatormain.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AsyncOperationManager/VB/primenumbercalculatormain.vb new file mode 100644 index 0000000000..b436086a6b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AsyncOperationManager/VB/primenumbercalculatormain.vb @@ -0,0 +1,983 @@ +' +' +Imports System.Collections +Imports System.Collections.Specialized +Imports System.ComponentModel +Imports System.Drawing +Imports System.Globalization +Imports System.Threading +Imports System.Windows.Forms +' + +' This form tests the PrimeNumberCalculator component. +Public Class PrimeNumberCalculatorMain + Inherits System.Windows.Forms.Form + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + ' Private fields + ' + #Region "Private fields" + + Private WithEvents primeNumberCalculator1 As PrimeNumberCalculator + Private taskGroupBox As System.Windows.Forms.GroupBox + Private WithEvents listView1 As System.Windows.Forms.ListView + Private taskIdColHeader As System.Windows.Forms.ColumnHeader + Private progressColHeader As System.Windows.Forms.ColumnHeader + Private currentColHeader As System.Windows.Forms.ColumnHeader + Private buttonPanel As System.Windows.Forms.Panel + Private panel2 As System.Windows.Forms.Panel + Private WithEvents startAsyncButton As System.Windows.Forms.Button + Private WithEvents cancelAsyncButton As System.Windows.Forms.Button + Private testNumberColHeader As System.Windows.Forms.ColumnHeader + Private resultColHeader As System.Windows.Forms.ColumnHeader + Private firstDivisorColHeader As System.Windows.Forms.ColumnHeader + Private components As System.ComponentModel.IContainer + Private progressCounter As Integer + Private progressInterval As Integer = 100 + + +#End Region + + + Public Sub New() + + InitializeComponent() + + End Sub + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + + End Sub + + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Implementation" + + ' This event handler selects a number randomly to test + ' for primality. It then starts the asynchronous + ' calculation by calling the PrimeNumberCalculator + ' component's CalculatePrimeAsync method. + Private Sub startAsyncButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles startAsyncButton.Click + + ' Randomly choose test numbers + ' up to 200,000 for primality. + Dim rand As New Random + Dim testNumber As Integer = rand.Next(200000) + + ' Task IDs are Guids. + Dim taskId As Guid = Guid.NewGuid() + Me.AddListViewItem(taskId, testNumber) + + ' Start the asynchronous task. + Me.primeNumberCalculator1.CalculatePrimeAsync( _ + testNumber, _ + taskId) + + End Sub + + + Private Sub listView1_SelectedIndexChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles listView1.SelectedIndexChanged + + Me.cancelAsyncButton.Enabled = CanCancel() + + End Sub + + + ' This event handler cancels all pending tasks that are + ' selected in the ListView control. + Private Sub cancelAsyncButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles cancelAsyncButton.Click + + Dim taskId As Guid = Guid.Empty + + ' Cancel all selected tasks. + Dim lvi As ListViewItem + For Each lvi In Me.listView1.SelectedItems + ' Tasks that have been completed or canceled have + ' their corresponding ListViewItem.Tag property + ' set to Nothing. + If (lvi.Tag IsNot Nothing) Then + taskId = CType(lvi.Tag, Guid) + Me.primeNumberCalculator1.CancelAsync(taskId) + lvi.Selected = False + End If + Next lvi + + cancelAsyncButton.Enabled = False + + End Sub + + ' + ' This event handler updates the ListView control when the + ' PrimeNumberCalculator raises the ProgressChanged event. + ' + ' On fast computers, the PrimeNumberCalculator can raise many + ' successive ProgressChanged events, so the user interface + ' may be flooded with messages. To prevent the user interface + ' from hanging, progress is only reported at intervals. + Private Sub primeNumberCalculator1_ProgressChanged( _ + ByVal e As ProgressChangedEventArgs) _ + Handles primeNumberCalculator1.ProgressChanged + + Me.progressCounter += 1 + + If Me.progressCounter Mod Me.progressInterval = 0 Then + + Dim taskId As Guid = CType(e.UserState, Guid) + + If TypeOf e Is CalculatePrimeProgressChangedEventArgs Then + Dim cppcea As CalculatePrimeProgressChangedEventArgs = e + Me.UpdateListViewItem( _ + taskId, _ + cppcea.ProgressPercentage, _ + cppcea.LatestPrimeNumber) + Else + Me.UpdateListViewItem( _ + taskId, e.ProgressPercentage) + End If + ElseIf Me.progressCounter > Me.progressInterval Then + Me.progressCounter = 0 + End If + + End Sub + ' + + ' + ' This event handler updates the ListView control when the + ' PrimeNumberCalculator raises the CalculatePrimeCompleted + ' event. The ListView item is updated with the appropriate + ' outcome of the calculation: Canceled, Error, or result. + Private Sub primeNumberCalculator1_CalculatePrimeCompleted( _ + ByVal sender As Object, _ + ByVal e As CalculatePrimeCompletedEventArgs) _ + Handles primeNumberCalculator1.CalculatePrimeCompleted + + Dim taskId As Guid = CType(e.UserState, Guid) + + If e.Cancelled Then + Dim result As String = "Canceled" + + Dim lvi As ListViewItem = UpdateListViewItem( _ + taskId, _ + result) + + If (lvi IsNot Nothing) Then + lvi.BackColor = Color.Pink + lvi.Tag = Nothing + End If + + ElseIf e.Error IsNot Nothing Then + + Dim result As String = "Error" + + Dim lvi As ListViewItem = UpdateListViewItem( _ + taskId, result) + + If (lvi IsNot Nothing) Then + lvi.BackColor = Color.Red + lvi.ForeColor = Color.White + lvi.Tag = Nothing + End If + Else + Dim result As Boolean = e.IsPrime + + Dim lvi As ListViewItem = UpdateListViewItem( _ + taskId, _ + result, _ + e.FirstDivisor) + + If (lvi IsNot Nothing) Then + lvi.BackColor = Color.LightGray + lvi.Tag = Nothing + End If + End If + + End Sub + ' + +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Private Methods" + + Private Function AddListViewItem( _ + ByVal guid As Guid, _ + ByVal testNumber As Integer) As ListViewItem + + Dim lvi As New ListViewItem + lvi.Text = testNumber.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + + lvi.SubItems.Add("Not Started") + lvi.SubItems.Add("1") + lvi.SubItems.Add(guid.ToString()) + lvi.SubItems.Add("---") + lvi.SubItems.Add("---") + lvi.Tag = guid + + Me.listView1.Items.Add(lvi) + + Return lvi + + End Function + + Private Overloads Function UpdateListViewItem( _ + ByVal guid As Guid, _ + ByVal percentComplete As Integer, _ + ByVal current As Integer) As ListViewItem + + Dim lviRet As ListViewItem = Nothing + + Dim lvi As ListViewItem + For Each lvi In Me.listView1.Items + If (lvi.Tag IsNot Nothing) Then + If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then + lvi.SubItems(1).Text = percentComplete.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + lvi.SubItems(2).Text = current.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + lviRet = lvi + Exit For + End If + End If + Next lvi + + Return lviRet + + End Function + + + Private Overloads Function UpdateListViewItem( _ + ByVal guid As Guid, _ + ByVal percentComplete As Integer, _ + ByVal current As Integer, _ + ByVal result As Boolean, _ + ByVal firstDivisor As Integer) As ListViewItem + + Dim lviRet As ListViewItem = Nothing + + Dim lvi As ListViewItem + For Each lvi In Me.listView1.Items + If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then + lvi.SubItems(1).Text = percentComplete.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + lvi.SubItems(2).Text = current.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + lvi.SubItems(4).Text = _ + IIf(result, "Prime", "Composite") + lvi.SubItems(5).Text = firstDivisor.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + + lviRet = lvi + + Exit For + End If + Next lvi + + Return lviRet + + End Function + + + Private Overloads Function UpdateListViewItem( _ + ByVal guid As Guid, _ + ByVal percentComplete As Integer) As ListViewItem + + Dim lviRet As ListViewItem = Nothing + + Dim lvi As ListViewItem + For Each lvi In Me.listView1.Items + If (lvi.Tag IsNot Nothing) Then + If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then + lvi.SubItems(1).Text = percentComplete.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + lviRet = lvi + Exit For + End If + End If + Next lvi + + Return lviRet + + End Function + + + Private Overloads Function UpdateListViewItem( _ + ByVal guid As Guid, _ + ByVal result As Boolean, _ + ByVal firstDivisor As Integer) As ListViewItem + + Dim lviRet As ListViewItem = Nothing + + Dim lvi As ListViewItem + For Each lvi In Me.listView1.Items + If (lvi.Tag IsNot Nothing) Then + If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then + lvi.SubItems(4).Text = _ + IIf(result, "Prime", "Composite") + lvi.SubItems(5).Text = firstDivisor.ToString( _ + CultureInfo.CurrentCulture.NumberFormat) + lviRet = lvi + Exit For + End If + End If + Next lvi + + Return lviRet + + End Function + + + Private Overloads Function UpdateListViewItem( _ + ByVal guid As Guid, _ + ByVal result As String) As ListViewItem + + Dim lviRet As ListViewItem = Nothing + + Dim lvi As ListViewItem + For Each lvi In Me.listView1.Items + If (lvi.Tag IsNot Nothing) Then + If guid.CompareTo(CType(lvi.Tag, Guid)) = 0 Then + lvi.SubItems(4).Text = result + lviRet = lvi + Exit For + End If + End If + Next lvi + + Return lviRet + + End Function + + + Private Function CanCancel() As Boolean + Dim oneIsActive As Boolean = False + + Dim lvi As ListViewItem + For Each lvi In Me.listView1.SelectedItems + If (lvi.Tag IsNot Nothing) Then + oneIsActive = True + Exit For + End If + Next lvi + + Return oneIsActive = True + + End Function + +#End Region + + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container + Me.taskGroupBox = New System.Windows.Forms.GroupBox + Me.buttonPanel = New System.Windows.Forms.Panel + Me.cancelAsyncButton = New System.Windows.Forms.Button + Me.startAsyncButton = New System.Windows.Forms.Button + Me.listView1 = New System.Windows.Forms.ListView + Me.testNumberColHeader = New System.Windows.Forms.ColumnHeader + Me.progressColHeader = New System.Windows.Forms.ColumnHeader + Me.currentColHeader = New System.Windows.Forms.ColumnHeader + Me.taskIdColHeader = New System.Windows.Forms.ColumnHeader + Me.resultColHeader = New System.Windows.Forms.ColumnHeader + Me.firstDivisorColHeader = New System.Windows.Forms.ColumnHeader + Me.panel2 = New System.Windows.Forms.Panel + Me.primeNumberCalculator1 = New PrimeNumberCalculator(Me.components) + Me.taskGroupBox.SuspendLayout() + Me.buttonPanel.SuspendLayout() + Me.SuspendLayout() + ' + ' taskGroupBox + ' + Me.taskGroupBox.Controls.Add(Me.buttonPanel) + Me.taskGroupBox.Controls.Add(Me.listView1) + Me.taskGroupBox.Dock = System.Windows.Forms.DockStyle.Fill + Me.taskGroupBox.Location = New System.Drawing.Point(0, 0) + Me.taskGroupBox.Name = "taskGroupBox" + Me.taskGroupBox.Size = New System.Drawing.Size(608, 254) + Me.taskGroupBox.TabIndex = 1 + Me.taskGroupBox.TabStop = False + Me.taskGroupBox.Text = "Tasks" + ' + ' buttonPanel + ' + Me.buttonPanel.Controls.Add(Me.cancelAsyncButton) + Me.buttonPanel.Controls.Add(Me.startAsyncButton) + Me.buttonPanel.Dock = System.Windows.Forms.DockStyle.Bottom + Me.buttonPanel.Location = New System.Drawing.Point(3, 176) + Me.buttonPanel.Name = "buttonPanel" + Me.buttonPanel.Size = New System.Drawing.Size(602, 75) + Me.buttonPanel.TabIndex = 1 + ' + ' cancelAsyncButton + ' + Me.cancelAsyncButton.Enabled = False + Me.cancelAsyncButton.Location = New System.Drawing.Point(128, 24) + Me.cancelAsyncButton.Name = "cancelAsyncButton" + Me.cancelAsyncButton.Size = New System.Drawing.Size(88, 23) + Me.cancelAsyncButton.TabIndex = 1 + Me.cancelAsyncButton.Text = "Cancel" + ' + ' startAsyncButton + ' + Me.startAsyncButton.Location = New System.Drawing.Point(24, 24) + Me.startAsyncButton.Name = "startAsyncButton" + Me.startAsyncButton.Size = New System.Drawing.Size(88, 23) + Me.startAsyncButton.TabIndex = 0 + Me.startAsyncButton.Text = "Start New Task" + ' + ' listView1 + ' + Me.listView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.testNumberColHeader, Me.progressColHeader, Me.currentColHeader, Me.taskIdColHeader, Me.resultColHeader, Me.firstDivisorColHeader}) + Me.listView1.Dock = System.Windows.Forms.DockStyle.Fill + Me.listView1.FullRowSelect = True + Me.listView1.GridLines = True + Me.listView1.Location = New System.Drawing.Point(3, 16) + Me.listView1.Name = "listView1" + Me.listView1.Size = New System.Drawing.Size(602, 160) + Me.listView1.TabIndex = 0 + Me.listView1.View = System.Windows.Forms.View.Details + ' + ' testNumberColHeader + ' + Me.testNumberColHeader.Text = "Test Number" + Me.testNumberColHeader.Width = 80 + ' + ' progressColHeader + ' + Me.progressColHeader.Text = "Progress" + ' + ' currentColHeader + ' + Me.currentColHeader.Text = "Current" + ' + ' taskIdColHeader + ' + Me.taskIdColHeader.Text = "Task ID" + Me.taskIdColHeader.Width = 200 + ' + ' resultColHeader + ' + Me.resultColHeader.Text = "Result" + Me.resultColHeader.Width = 80 + ' + ' firstDivisorColHeader + ' + Me.firstDivisorColHeader.Text = "First Divisor" + Me.firstDivisorColHeader.Width = 80 + ' + ' panel2 + ' + Me.panel2.Location = New System.Drawing.Point(200, 128) + Me.panel2.Name = "panel2" + Me.panel2.TabIndex = 2 + ' + ' PrimeNumberCalculatorMain + ' + Me.ClientSize = New System.Drawing.Size(608, 254) + Me.Controls.Add(taskGroupBox) + Me.Name = "PrimeNumberCalculatorMain" + Me.Text = "Prime Number Calculator" + Me.taskGroupBox.ResumeLayout(False) + Me.buttonPanel.ResumeLayout(False) + Me.ResumeLayout(False) + + End Sub + + + _ + Shared Sub Main() + Application.Run(New PrimeNumberCalculatorMain()) + + End Sub +End Class + +' + +' +Public Delegate Sub ProgressChangedEventHandler( _ + ByVal e As ProgressChangedEventArgs) + +Public Delegate Sub CalculatePrimeCompletedEventHandler( _ + ByVal sender As Object, _ + ByVal e As CalculatePrimeCompletedEventArgs) +' + +' This class implements the Event-based Asynchronous Pattern. +' It asynchronously computes whether a number is prime or +' composite (not prime). +Public Class PrimeNumberCalculator + Inherits System.ComponentModel.Component + + ' + Private Delegate Sub WorkerEventHandler( _ + ByVal numberToCheck As Integer, _ + ByVal asyncOp As AsyncOperation) + ' + + ' + Private onProgressReportDelegate As SendOrPostCallback + Private onCompletedDelegate As SendOrPostCallback + ' + + ' + Private userStateToLifetime As New HybridDictionary() + ' + + Private components As System.ComponentModel.Container = Nothing + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Public events" + + ' + Public Event ProgressChanged _ + As ProgressChangedEventHandler + Public Event CalculatePrimeCompleted _ + As CalculatePrimeCompletedEventHandler + ' + +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Construction and destruction" + + + Public Sub New(ByVal container As System.ComponentModel.IContainer) + + container.Add(Me) + InitializeComponent() + + InitializeDelegates() + + End Sub + + + ' + Public Sub New() + + InitializeComponent() + + InitializeDelegates() + + End Sub + ' + + + ' + Protected Overridable Sub InitializeDelegates() + onProgressReportDelegate = _ + New SendOrPostCallback(AddressOf ReportProgress) + onCompletedDelegate = _ + New SendOrPostCallback(AddressOf CalculateCompleted) + End Sub + ' + + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + + End Sub + +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Implementation" + + + ' + ' This method starts an asynchronous calculation. + ' First, it checks the supplied task ID for uniqueness. + ' If taskId is unique, it creates a new WorkerEventHandler + ' and calls its BeginInvoke method to start the calculation. + Public Overridable Sub CalculatePrimeAsync( _ + ByVal numberToTest As Integer, _ + ByVal taskId As Object) + + ' Create an AsyncOperation for taskId. + Dim asyncOp As AsyncOperation = _ + AsyncOperationManager.CreateOperation(taskId) + + ' Multiple threads will access the task dictionary, + ' so it must be locked to serialize access. + SyncLock userStateToLifetime.SyncRoot + If userStateToLifetime.Contains(taskId) Then + Throw New ArgumentException( _ + "Task ID parameter must be unique", _ + "taskId") + End If + + userStateToLifetime(taskId) = asyncOp + End SyncLock + + ' Start the asynchronous operation. + Dim workerDelegate As New WorkerEventHandler( _ + AddressOf CalculateWorker) + + workerDelegate.BeginInvoke( _ + numberToTest, _ + asyncOp, _ + Nothing, _ + Nothing) + + End Sub + ' + + ' + ' Utility method for determining if a + ' task has been canceled. + Private Function TaskCanceled(ByVal taskId As Object) As Boolean + Return (userStateToLifetime(taskId) Is Nothing) + End Function + ' + + ' + ' This method cancels a pending asynchronous operation. + Public Sub CancelAsync(ByVal taskId As Object) + + Dim obj As Object = userStateToLifetime(taskId) + If (obj IsNot Nothing) Then + + SyncLock userStateToLifetime.SyncRoot + + userStateToLifetime.Remove(taskId) + + End SyncLock + + End If + + End Sub + ' + + ' + ' This method performs the actual prime number computation. + ' It is executed on the worker thread. + Private Sub CalculateWorker( _ + ByVal numberToTest As Integer, _ + ByVal asyncOp As AsyncOperation) + + Dim prime As Boolean = False + Dim firstDivisor As Integer = 1 + Dim exc As Exception = Nothing + + ' Check that the task is still active. + ' The operation may have been canceled before + ' the thread was scheduled. + If Not Me.TaskCanceled(asyncOp.UserSuppliedState) Then + + Try + ' Find all the prime numbers up to the + ' square root of numberToTest. + Dim primes As ArrayList = BuildPrimeNumberList( _ + numberToTest, asyncOp) + + ' Now we have a list of primes less than + 'numberToTest. + prime = IsPrime( _ + primes, _ + numberToTest, _ + firstDivisor) + + Catch ex As Exception + exc = ex + End Try + + End If + + Me.CompletionMethod( _ + numberToTest, _ + firstDivisor, _ + prime, _ + exc, _ + TaskCanceled(asyncOp.UserSuppliedState), _ + asyncOp) + + End Sub + ' + + ' + ' This method computes the list of prime numbers used by the + ' IsPrime method. + Private Function BuildPrimeNumberList( _ + ByVal numberToTest As Integer, _ + ByVal asyncOp As AsyncOperation) As ArrayList + + Dim e As ProgressChangedEventArgs = Nothing + Dim primes As New ArrayList + Dim firstDivisor As Integer + Dim n As Integer = 5 + + ' Add the first prime numbers. + primes.Add(2) + primes.Add(3) + + ' Do the work. + While n < numberToTest And _ + Not Me.TaskCanceled(asyncOp.UserSuppliedState) + + If IsPrime(primes, n, firstDivisor) Then + ' Report to the client that you found a prime. + e = New CalculatePrimeProgressChangedEventArgs( _ + n, _ + CSng(n) / CSng(numberToTest) * 100, _ + asyncOp.UserSuppliedState) + + asyncOp.Post(Me.onProgressReportDelegate, e) + + primes.Add(n) + + ' Yield the rest of this time slice. + Thread.Sleep(0) + End If + + ' Skip even numbers. + n += 2 + + End While + + Return primes + + End Function + ' + + + ' + ' This method tests n for primality against the list of + ' prime numbers contained in the primes parameter. + Private Function IsPrime( _ + ByVal primes As ArrayList, _ + ByVal n As Integer, _ + ByRef firstDivisor As Integer) As Boolean + + Dim foundDivisor As Boolean = False + Dim exceedsSquareRoot As Boolean = False + + Dim i As Integer = 0 + Dim divisor As Integer = 0 + firstDivisor = 1 + + ' Stop the search if: + ' there are no more primes in the list, + ' there is a divisor of n in the list, or + ' there is a prime that is larger than + ' the square root of n. + While i < primes.Count AndAlso _ + Not foundDivisor AndAlso _ + Not exceedsSquareRoot + + ' The divisor variable will be the smallest prime number + ' not yet tried. + divisor = primes(i) + i = i + 1 + + ' Determine whether the divisor is greater than the + ' square root of n. + If divisor * divisor > n Then + exceedsSquareRoot = True + ' Determine whether the divisor is a factor of n. + ElseIf n Mod divisor = 0 Then + firstDivisor = divisor + foundDivisor = True + End If + End While + + Return Not foundDivisor + + End Function + ' + + + ' + ' This method is invoked via the AsyncOperation object, + ' so it is guaranteed to be executed on the correct thread. + Private Sub CalculateCompleted(ByVal operationState As Object) + Dim e As CalculatePrimeCompletedEventArgs = operationState + + OnCalculatePrimeCompleted(e) + + End Sub + + + ' This method is invoked via the AsyncOperation object, + ' so it is guaranteed to be executed on the correct thread. + Private Sub ReportProgress(ByVal state As Object) + Dim e As ProgressChangedEventArgs = state + + OnProgressChanged(e) + + End Sub + + Protected Sub OnCalculatePrimeCompleted( _ + ByVal e As CalculatePrimeCompletedEventArgs) + + RaiseEvent CalculatePrimeCompleted(Me, e) + + End Sub + + + Protected Sub OnProgressChanged( _ + ByVal e As ProgressChangedEventArgs) + + RaiseEvent ProgressChanged(e) + + End Sub + ' + + + ' + ' This is the method that the underlying, free-threaded + ' asynchronous behavior will invoke. This will happen on + ' an arbitrary thread. + Private Sub CompletionMethod( _ + ByVal numberToTest As Integer, _ + ByVal firstDivisor As Integer, _ + ByVal prime As Boolean, _ + ByVal exc As Exception, _ + ByVal canceled As Boolean, _ + ByVal asyncOp As AsyncOperation) + + ' If the task was not previously canceled, + ' remove the task from the lifetime collection. + If Not canceled Then + SyncLock userStateToLifetime.SyncRoot + userStateToLifetime.Remove(asyncOp.UserSuppliedState) + End SyncLock + End If + + ' Package the results of the operation in a + ' CalculatePrimeCompletedEventArgs. + Dim e As New CalculatePrimeCompletedEventArgs( _ + numberToTest, _ + firstDivisor, _ + prime, _ + exc, _ + canceled, _ + asyncOp.UserSuppliedState) + + ' End the task. The asyncOp object is responsible + ' for marshaling the call. + asyncOp.PostOperationCompleted(onCompletedDelegate, e) + + ' Note that after the call to PostOperationCompleted, asyncOp + ' is no longer usable, and any attempt to use it will cause. + ' an exception to be thrown. + + End Sub + ' + +#End Region + + + Private Sub InitializeComponent() + + End Sub + + +End Class + +' +Public Class CalculatePrimeProgressChangedEventArgs + Inherits ProgressChangedEventArgs + Private latestPrimeNumberValue As Integer = 1 + + + Public Sub New( _ + ByVal latestPrime As Integer, _ + ByVal progressPercentage As Integer, _ + ByVal UserState As Object) + + MyBase.New(progressPercentage, UserState) + Me.latestPrimeNumberValue = latestPrime + + End Sub + + Public ReadOnly Property LatestPrimeNumber() As Integer + Get + Return latestPrimeNumberValue + End Get + End Property +End Class +' + +' +Public Class CalculatePrimeCompletedEventArgs + Inherits AsyncCompletedEventArgs + Private numberToTestValue As Integer = 0 + Private firstDivisorValue As Integer = 1 + Private isPrimeValue As Boolean + + + Public Sub New( _ + ByVal numberToTest As Integer, _ + ByVal firstDivisor As Integer, _ + ByVal isPrime As Boolean, _ + ByVal e As Exception, _ + ByVal canceled As Boolean, _ + ByVal state As Object) + + MyBase.New(e, canceled, state) + Me.numberToTestValue = numberToTest + Me.firstDivisorValue = firstDivisor + Me.isPrimeValue = isPrime + + End Sub + + + Public ReadOnly Property NumberToTest() As Integer + Get + ' Raise an exception if the operation failed + ' or was canceled. + RaiseExceptionIfNecessary() + + ' If the operation was successful, return + ' the property value. + Return numberToTestValue + End Get + End Property + + + Public ReadOnly Property FirstDivisor() As Integer + Get + ' Raise an exception if the operation failed + ' or was canceled. + RaiseExceptionIfNecessary() + + ' If the operation was successful, return + ' the property value. + Return firstDivisorValue + End Get + End Property + + + Public ReadOnly Property IsPrime() As Boolean + Get + ' Raise an exception if the operation failed + ' or was canceled. + RaiseExceptionIfNecessary() + + ' If the operation was successful, return + ' the property value. + Return isPrimeValue + End Get + End Property +End Class +' +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb new file mode 100644 index 0000000000..a1d5a78277 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/attributesdemocontrol.vb @@ -0,0 +1,549 @@ +' +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Diagnostics +Imports System.Drawing +Imports System.Data +Imports System.Reflection +Imports System.Text +Imports System.Windows.Forms +' + +' This sample demonstrates the use of various attributes for +' authoring a control. +Namespace AttributesDemoControlLibrary + + ' This is the event handler delegate for the ThresholdExceeded event. + Delegate Sub ThresholdExceededEventHandler(ByVal e As ThresholdExceededEventArgs) + + ' + ' + ' This control demonstrates a simple logging capability. + _ + Public Class AttributesDemoControl + Inherits UserControl + ' + + ' This backs the Threshold property. + Private thresholdValue As Object + + ' The default fore color value for DataGridView cells that + ' contain values that exceed the threshold. + Private Shared defaultAlertForeColorValue As Color = Color.White + + ' The default back color value for DataGridView cells that + ' contain values that exceed the threshold. + Private Shared defaultAlertBackColorValue As Color = Color.Red + + ' The ambient color value. + Private Shared ambientColorValue As Color = Color.Empty + + ' The fore color value for DataGridView cells that + ' contain values that exceed the threshold. + Private alertForeColorValue As Color = defaultAlertForeColorValue + + ' The back color value for DataGridView cells that + ' contain values that exceed the threshold. + Private alertBackColorValue As Color = defaultAlertBackColorValue + + ' Child controls that comprise this UserControl. + Private tableLayoutPanel1 As TableLayoutPanel + Private WithEvents dataGridView1 As DataGridView + Private label1 As Label + + ' Required for designer support. + Private components As System.ComponentModel.IContainer = Nothing + + ' Default constructor. + Public Sub New() + InitializeComponent() + End Sub + ' + + _ + Public Property TitleText() As String + Get + Return Me.label1.Text + End Get + + Set(ByVal value As String) + Me.label1.Text = value + End Set + End Property + ' + + ' + ' The inherited Text property is hidden at design time and + ' raises an exception at run time. This enforces a requirement + ' that client code uses the TitleText property instead. + _ + Public Overrides Property Text() As String + Get + Throw New NotSupportedException() + End Get + Set(ByVal value As String) + Throw New NotSupportedException() + End Set + End Property + ' + + ' + _ + Public Property AlertForeColor() As Color + Get + If Me.alertForeColorValue = Color.Empty AndAlso (Me.Parent IsNot Nothing) Then + Return Parent.ForeColor + End If + + Return Me.alertForeColorValue + End Get + + Set(ByVal value As Color) + Me.alertForeColorValue = value + End Set + End Property + + ' This method is used by designers to enable resetting the + ' property to its default value. + Public Sub ResetAlertForeColor() + Me.AlertForeColor = AttributesDemoControl.defaultAlertForeColorValue + End Sub + + ' This method indicates to designers whether the property + ' value is different from the ambient value, in which case + ' the designer should persist the value. + Private Function ShouldSerializeAlertForeColor() As Boolean + Return Me.alertForeColorValue <> AttributesDemoControl.ambientColorValue + End Function + ' + + ' + _ + Public Property AlertBackColor() As Color + Get + If Me.alertBackColorValue = Color.Empty AndAlso (Me.Parent IsNot Nothing) Then + Return Parent.BackColor + End If + + Return Me.alertBackColorValue + End Get + + Set(ByVal value As Color) + Me.alertBackColorValue = value + End Set + End Property + + ' This method is used by designers to enable resetting the + ' property to its default value. + Public Sub ResetAlertBackColor() + Me.AlertBackColor = AttributesDemoControl.defaultAlertBackColorValue + End Sub + + ' This method indicates to designers whether the property + ' value is different from the ambient value, in which case + ' the designer should persist the value. + Private Function ShouldSerializeAlertBackColor() As Boolean + Return Me.alertBackColorValue <> AttributesDemoControl.ambientColorValue + End Function 'ShouldSerializeAlertBackColor + ' + + ' + _ + Public Property DataSource() As Object + Get + Return Me.dataGridView1.DataSource + End Get + + Set(ByVal value As Object) + Me.dataGridView1.DataSource = value + End Set + End Property + ' + + ' + _ + Public Property DataMember() As String + Get + Return Me.dataGridView1.DataMember + End Get + + Set(ByVal value As String) + Me.dataGridView1.DataMember = value + End Set + End Property + ' + + ' + ' This property would normally have its BrowsableAttribute + ' set to false, but this code demonstrates using + ' ReadOnlyAttribute, so BrowsableAttribute is true to show + ' it in any attached PropertyGrid control. + _ + Public Property CurrentLogTime() As DateTime + Get + Dim lastRowIndex As Integer = _ + Me.dataGridView1.Rows.GetLastRow(DataGridViewElementStates.Visible) + + If lastRowIndex > -1 Then + Dim lastRow As DataGridViewRow = Me.dataGridView1.Rows(lastRowIndex) + Dim lastCell As DataGridViewCell = lastRow.Cells("EntryTime") + Return CType(lastCell.Value, DateTime) + Else + Return DateTime.MinValue + End If + End Get + + Set(ByVal value As DateTime) + End Set + End Property + ' + + ' + _ + Public Property Threshold() As Object + Get + Return Me.thresholdValue + End Get + + Set(ByVal value As Object) + Me.thresholdValue = value + End Set + End Property + ' + + ' + ' This property exists only to demonstrate the + ' PasswordPropertyText attribute. When this control + ' is attached to a PropertyGrid control, the returned + ' string will be displayed with obscuring characters + ' such as asterisks. This property has no other effect. + _ + Public ReadOnly Property Password() As String + Get + Return "This is a demo password." + End Get + End Property + ' + + ' + ' This property exists only to demonstrate the + ' DisplayName attribute. When this control + ' is attached to a PropertyGrid control, the + ' property will be appear as "RenamedProperty" + ' instead of "MisnamedProperty". + _ + Public ReadOnly Property MisnamedProperty() As Boolean + Get + Return True + End Get + End Property + ' + + ' This is the declaration for the ThresholdExceeded event. + 'Public Event ThresholdExceeded As ThresholdExceededEventHandler + Public Event ThresholdExceeded(ByVal e As ThresholdExceededEventArgs) + +#Region "Implementation" + + ' + ' This is the event handler for the DataGridView control's + ' CellFormatting event. Handling this event allows the + ' AttributesDemoControl to examine the incoming log entries + ' from the data source as they arrive. + ' + ' If the cell for which this event is raised holds the + ' log entry's timestamp, the cell value is formatted with + ' the full date/time pattern. + ' + ' Otherwise, the cell's value is assumed to hold the log + ' entry value. If the value exceeds the threshold value, + ' the cell is painted with the colors specified by the + ' AlertForeColor and AlertBackColor properties, after which + ' the ThresholdExceeded is raised. For this comparison to + ' succeed, the log entry's type must implement the IComparable + ' interface. + Private Sub dataGridView1_CellFormatting( _ + ByVal sender As Object, _ + ByVal e As DataGridViewCellFormattingEventArgs) _ + Handles dataGridView1.CellFormatting + Try + If (e.Value IsNot Nothing) Then + If TypeOf e.Value Is DateTime Then + ' Display the log entry time with the + ' full date/time pattern (long time). + e.CellStyle.Format = "F" + Else + ' Scroll to the most recent entry. + Dim row As DataGridViewRow = Me.dataGridView1.Rows(e.RowIndex) + Dim cell As DataGridViewCell = row.Cells(e.ColumnIndex) + Me.dataGridView1.FirstDisplayedCell = cell + + If (Me.thresholdValue IsNot Nothing) Then + ' Get the type of the log entry. + Dim val As Object = e.Value + Dim paramType As Type = val.GetType() + + ' Compare the log entry value to the threshold value. + ' Use reflection to call the CompareTo method on the + ' template parameter's type. + Dim compareVal As Integer = _ + Fix(paramType.InvokeMember("CompareTo", _ + BindingFlags.Default Or BindingFlags.InvokeMethod, _ + Nothing, _ + e.Value, _ + New Object() {Me.thresholdValue}, _ + System.Globalization.CultureInfo.InvariantCulture)) + + ' If the log entry value exceeds the threshold value, + ' set the cell's fore color and back color properties + ' and raise the ThresholdExceeded event. + If compareVal > 0 Then + e.CellStyle.BackColor = Me.alertBackColorValue + e.CellStyle.ForeColor = Me.alertForeColorValue + + Dim teea As New ThresholdExceededEventArgs(Me.thresholdValue, e.Value) + RaiseEvent ThresholdExceeded(teea) + End If + End If + End If + End If + Catch ex As Exception + Trace.WriteLine(ex.Message) + End Try + End Sub + ' + + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + + Private Sub InitializeComponent() + Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle + Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel + Me.dataGridView1 = New System.Windows.Forms.DataGridView + Me.label1 = New System.Windows.Forms.Label + Me.tableLayoutPanel1.SuspendLayout() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + 'tableLayoutPanel1 + ' + Me.tableLayoutPanel1.AutoSize = True + Me.tableLayoutPanel1.ColumnCount = 1 + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!)) + Me.tableLayoutPanel1.Controls.Add(Me.dataGridView1, 0, 1) + Me.tableLayoutPanel1.Controls.Add(Me.label1, 0, 0) + Me.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill + Me.tableLayoutPanel1.Location = New System.Drawing.Point(10, 10) + Me.tableLayoutPanel1.Name = "tableLayoutPanel1" + Me.tableLayoutPanel1.Padding = New System.Windows.Forms.Padding(10) + Me.tableLayoutPanel1.RowCount = 2 + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!)) + Me.tableLayoutPanel1.Size = New System.Drawing.Size(425, 424) + Me.tableLayoutPanel1.TabIndex = 0 + ' + 'dataGridView1 + ' + Me.dataGridView1.AllowUserToAddRows = False + Me.dataGridView1.AllowUserToDeleteRows = False + Me.dataGridView1.AllowUserToOrderColumns = True + Me.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells + DataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft + DataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control + DataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText + DataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight + DataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText + DataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] + Me.dataGridView1.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle1 + Me.dataGridView1.ColumnHeadersHeight = 4 + Me.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill + Me.dataGridView1.Location = New System.Drawing.Point(13, 57) + Me.dataGridView1.Name = "dataGridView1" + Me.dataGridView1.ReadOnly = True + Me.dataGridView1.RowHeadersVisible = False + Me.dataGridView1.Size = New System.Drawing.Size(399, 354) + Me.dataGridView1.TabIndex = 1 + ' + 'label1 + ' + Me.label1.AutoSize = True + Me.label1.BackColor = System.Drawing.SystemColors.Control + Me.label1.Dock = System.Windows.Forms.DockStyle.Fill + Me.label1.Location = New System.Drawing.Point(13, 13) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(399, 38) + Me.label1.TabIndex = 2 + Me.label1.Text = "label1" + Me.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter + ' + 'AttributesDemoControl + ' + Me.Controls.Add(Me.tableLayoutPanel1) + Me.Name = "AttributesDemoControl" + Me.Padding = New System.Windows.Forms.Padding(10) + Me.Size = New System.Drawing.Size(445, 444) + Me.tableLayoutPanel1.ResumeLayout(False) + Me.tableLayoutPanel1.PerformLayout() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + +#End Region + + End Class + ' + + ' + ' This is the EventArgs class for the ThresholdExceeded event. + Public Class ThresholdExceededEventArgs + Inherits EventArgs + Private thresholdVal As Object = Nothing + Private exceedingVal As Object = Nothing + + Public Sub New(ByVal thresholdValue As Object, ByVal exceedingValue As Object) + Me.thresholdVal = thresholdValue + Me.exceedingVal = exceedingValue + End Sub + + Public ReadOnly Property ThresholdValue() As Object + Get + Return Me.thresholdVal + End Get + End Property + + Public ReadOnly Property ExceedingValue() As Object + Get + Return Me.exceedingVal + End Get + End Property + End Class + ' + + ' + ' This class encapsulates a log entry. It is a parameterized + ' type (also known as a template class). The parameter type T + ' defines the type of data being logged. For threshold detection + ' to work, this type must implement the IComparable interface. + _ + Public Class LogEntry(Of T As IComparable) + + Private entryValue As T + + Private entryTimeValue As DateTime + + + Public Sub New(ByVal value As T, ByVal time As DateTime) + Me.entryValue = value + Me.entryTimeValue = time + End Sub + + + Public ReadOnly Property Entry() As T + Get + Return Me.entryValue + End Get + End Property + + + Public ReadOnly Property EntryTime() As DateTime + Get + Return Me.entryTimeValue + End Get + End Property + + ' + ' This is the TypeConverter for the LogEntry class. + Public Class LogEntryTypeConverter + Inherits TypeConverter + + ' + Public Overrides Function CanConvertFrom( _ + ByVal context As ITypeDescriptorContext, _ + ByVal sourceType As Type) As Boolean + If sourceType Is GetType(String) Then + Return True + End If + + Return MyBase.CanConvertFrom(context, sourceType) + End Function + ' + + ' + Public Overrides Function ConvertFrom( _ + ByVal context As ITypeDescriptorContext, _ + ByVal culture As System.Globalization.CultureInfo, _ + ByVal value As Object) As Object + If TypeOf value Is String Then + Dim v As String() = CStr(value).Split(New Char() {"|"c}) + + Dim paramType As Type = GetType(T) + Dim entryValue As T = CType(paramType.InvokeMember("Parse", BindingFlags.Static Or BindingFlags.Public Or BindingFlags.InvokeMethod, Nothing, Nothing, New String() {v(0)}, culture), T) + + Return New LogEntry(Of T)(entryValue, DateTime.Parse(v(2))) ' + + End If + + Return MyBase.ConvertFrom(context, culture, value) + End Function + ' + + ' + Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As System.Globalization.CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object + If destinationType Is GetType(String) Then + + Dim le As LogEntry(Of T) = CType(value, LogEntry(Of T)) + + Dim stringRepresentation As String = String.Format("{0} | {1}", le.Entry, le.EntryTime) + + Return stringRepresentation + End If + + Return MyBase.ConvertTo(context, culture, value, destinationType) + End Function + End Class + ' + End Class + ' + ' + +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/form1.vb new file mode 100644 index 0000000000..39840b2fe5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/form1.vb @@ -0,0 +1,280 @@ +' +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Diagnostics +Imports System.Drawing +Imports System.Windows.Forms +Imports AttributesDemoControlLibrary +' + +' This sample demonstrates using the AttributesDemoControl to log +' data from a data source. +Public Class Form1 + Inherits Form + Private bindingSource1 As BindingSource + Private performanceCounter1 As System.Diagnostics.PerformanceCounter + Private WithEvents startButton As Button + Private WithEvents stopButton As Button + Private WithEvents timer1 As System.Timers.Timer + Private statusStrip1 As ToolStripStatusLabel + Private statusStripPanel1 As ToolStripStatusLabel + Private WithEvents numericUpDown1 As NumericUpDown + Private groupBox1 As GroupBox + Private groupBox2 As GroupBox + Private tableLayoutPanel1 As TableLayoutPanel + Private WithEvents attributesDemoControl1 As AttributesDemoControl + Private components As System.ComponentModel.IContainer = Nothing + + ' This form uses an AttributesDemoControl to display a stream + ' of LogEntry objects. The data stream is generated by polling + ' a performance counter and communicating the counter values + ' to the control with data binding. + Public Sub New() + InitializeComponent() + + ' Set the initial value of the threshold up/down control + ' to the control's threshold value. + Me.numericUpDown1.Value = _ + System.Convert.ToDecimal( _ + System.Convert.ToSingle(Me.attributesDemoControl1.Threshold)) + + ' Assign the performance counter's name to the control's + ' title text. + Me.attributesDemoControl1.TitleText = _ + Me.performanceCounter1.CounterName + End Sub + + + ' This method handles the ThresholdExceeded event. It posts + ' a the value that exceeded the threshold to the status strip. + Private Sub attributesDemoControl1_ThresholdExceeded( _ + ByVal e As ThresholdExceededEventArgs) _ + Handles attributesDemoControl1.ThresholdExceeded + Dim msg As String = String.Format( _ + "{0}: Value {1} exceeded threshold {2}", _ + Me.attributesDemoControl1.CurrentLogTime, _ + e.ExceedingValue, _ + e.ThresholdValue) + + Me.ReportStatus(msg) + End Sub + + ' + ' This method handles the timer's Elapsed event. It queries + ' the performance counter for the next value, packs the + ' value in a LogEntry object, and adds the new LogEntry to + ' the list managed by the BindingSource. + Private Sub timer1_Elapsed( _ + ByVal sender As Object, _ + ByVal e As System.Timers.ElapsedEventArgs) _ + Handles timer1.Elapsed + + ' Get the latest value from the performance counter. + Dim val As Single = Me.performanceCounter1.NextValue() + + ' The performance counter returns values of type float, + ' but any type that implements the IComparable interface + ' will work. + Dim entry As LogEntry(Of Single) = _ + New LogEntry(Of Single)(val, DateTime.Now) + + ' Add the new LogEntry to the BindingSource list. + Me.bindingSource1.Add(entry) + End Sub + ' + + Private Sub numericUpDown1_ValueChanged( _ + ByVal sender As Object, _ + ByVal e As EventArgs) _ + Handles numericUpDown1.ValueChanged + + Me.attributesDemoControl1.Threshold = _ + System.Convert.ToSingle(Me.numericUpDown1.Value) + + Dim msg As String = String.Format( _ + "Threshold changed to {0}", _ + Me.attributesDemoControl1.Threshold) + + Me.ReportStatus(msg) + End Sub + + Private Sub startButton_Click( _ + ByVal sender As Object, _ + ByVal e As EventArgs) _ + Handles startButton.Click + + Me.ReportStatus((DateTime.Now.ToString() + ": Starting")) + + Me.timer1.Start() + End Sub + + + Private Sub stopButton_Click( _ + ByVal sender As Object, _ + ByVal e As EventArgs) _ + Handles stopButton.Click + + Me.ReportStatus((DateTime.Now.ToString() + ": Stopping")) + + Me.timer1.Stop() + End Sub + + + Private Sub ReportStatus(msg As String) + If (msg IsNot Nothing) Then + Me.statusStripPanel1.Text = msg + End If + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container() + Me.bindingSource1 = New System.Windows.Forms.BindingSource(Me.components) + Me.performanceCounter1 = New System.Diagnostics.PerformanceCounter() + Me.startButton = New System.Windows.Forms.Button() + Me.stopButton = New System.Windows.Forms.Button() + Me.timer1 = New System.Timers.Timer() + Me.statusStripPanel1 = New System.Windows.Forms.ToolStripStatusLabel() + Me.numericUpDown1 = New System.Windows.Forms.NumericUpDown() + Me.groupBox1 = New System.Windows.Forms.GroupBox() + Me.groupBox2 = New System.Windows.Forms.GroupBox() + Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel() + Me.attributesDemoControl1 = New AttributesDemoControlLibrary.AttributesDemoControl() + CType(Me.bindingSource1, System.ComponentModel.ISupportInitialize).BeginInit() + CType(Me.performanceCounter1, System.ComponentModel.ISupportInitialize).BeginInit() + CType(Me.timer1, System.ComponentModel.ISupportInitialize).BeginInit() + CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.groupBox1.SuspendLayout() + Me.groupBox2.SuspendLayout() + Me.tableLayoutPanel1.SuspendLayout() + Me.SuspendLayout() + ' + ' performanceCounter1 + ' + Me.performanceCounter1.CategoryName = ".NET CLR Memory" + Me.performanceCounter1.CounterName = "Gen 0 heap size" + Me.performanceCounter1.InstanceName = "_Global_" + ' + ' startButton + ' + Me.startButton.Location = New System.Drawing.Point(31, 25) + Me.startButton.Name = "startButton" + Me.startButton.TabIndex = 1 + Me.startButton.Text = "Start" + ' + ' stopButton + ' + Me.stopButton.Location = New System.Drawing.Point(112, 25) + Me.stopButton.Name = "stopButton" + Me.stopButton.TabIndex = 2 + Me.stopButton.Text = "Stop" + ' + ' timer1 + ' + Me.timer1.Interval = 1000 + Me.timer1.SynchronizingObject = Me + ' + ' statusStripPanel1 + ' + Me.statusStripPanel1.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter + Me.statusStripPanel1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text + Me.statusStripPanel1.Name = "statusStripPanel1" + Me.statusStripPanel1.Text = "Ready" + ' + ' numericUpDown1 + ' + Me.numericUpDown1.Location = New System.Drawing.Point(37, 29) + Me.numericUpDown1.Maximum = New Decimal(New Integer() {1410065408, 2, 0, 0}) + Me.numericUpDown1.Name = "numericUpDown1" + Me.numericUpDown1.TabIndex = 7 + ' + ' groupBox1 + ' + Me.groupBox1.Anchor = System.Windows.Forms.AnchorStyles.None + Me.groupBox1.Controls.Add(Me.numericUpDown1) + Me.groupBox1.Location = New System.Drawing.Point(280, 326) + Me.groupBox1.Name = "groupBox1" + Me.groupBox1.Size = New System.Drawing.Size(200, 70) + Me.groupBox1.TabIndex = 13 + Me.groupBox1.TabStop = False + Me.groupBox1.Text = "Threshold Value" + ' + ' groupBox2 + ' + Me.groupBox2.Anchor = System.Windows.Forms.AnchorStyles.None + Me.groupBox2.Controls.Add(Me.startButton) + Me.groupBox2.Controls.Add(Me.stopButton) + Me.groupBox2.Location = New System.Drawing.Point(26, 327) + Me.groupBox2.Name = "groupBox2" + Me.groupBox2.Size = New System.Drawing.Size(214, 68) + Me.groupBox2.TabIndex = 14 + Me.groupBox2.TabStop = False + Me.groupBox2.Text = "Logging" + ' + ' tableLayoutPanel1 + ' + Me.tableLayoutPanel1.ColumnCount = 2 + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)) + Me.tableLayoutPanel1.Controls.Add(Me.groupBox2, 0, 1) + Me.tableLayoutPanel1.Controls.Add(Me.groupBox1, 1, 1) + Me.tableLayoutPanel1.Controls.Add(Me.attributesDemoControl1, 0, 0) + Me.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill + Me.tableLayoutPanel1.Location = New System.Drawing.Point(0, 0) + Me.tableLayoutPanel1.Name = "tableLayoutPanel1" + Me.tableLayoutPanel1.Padding = New System.Windows.Forms.Padding(10) + Me.tableLayoutPanel1.RowCount = 2 + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)) + Me.tableLayoutPanel1.Size = New System.Drawing.Size(514, 411) + Me.tableLayoutPanel1.TabIndex = 15 + ' + ' attributesDemoControl1 + ' + Me.tableLayoutPanel1.SetColumnSpan(Me.attributesDemoControl1, 2) + Me.attributesDemoControl1.DataMember = "" + Me.attributesDemoControl1.DataSource = Me.bindingSource1 + Me.attributesDemoControl1.Dock = System.Windows.Forms.DockStyle.Fill + Me.attributesDemoControl1.Location = New System.Drawing.Point(13, 13) + Me.attributesDemoControl1.Name = "attributesDemoControl1" + Me.attributesDemoControl1.Padding = New System.Windows.Forms.Padding(10) + Me.attributesDemoControl1.Size = New System.Drawing.Size(488, 306) + Me.attributesDemoControl1.TabIndex = 0 + Me.attributesDemoControl1.Threshold = 200000F + Me.attributesDemoControl1.TitleText = "TITLE" + ' + ' Form1 + ' + Me.BackColor = System.Drawing.SystemColors.Control + Me.ClientSize = New System.Drawing.Size(514, 430) + Me.Controls.Add(tableLayoutPanel1) + Me.Name = "Form1" + Me.Text = "Form1" + CType(Me.bindingSource1, System.ComponentModel.ISupportInitialize).EndInit() + CType(Me.performanceCounter1, System.ComponentModel.ISupportInitialize).EndInit() + CType(Me.timer1, System.ComponentModel.ISupportInitialize).EndInit() + CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).EndInit() + Me.groupBox1.ResumeLayout(False) + Me.groupBox2.ResumeLayout(False) + Me.tableLayoutPanel1.ResumeLayout(False) + Me.ResumeLayout(False) + Me.PerformLayout() + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/makefile new file mode 100644 index 0000000000..2e0dd49406 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.AttributesDemoControl/VB/makefile @@ -0,0 +1,10 @@ +all: AttributesDemoControl.dll form1.exe + +AttributesDemoControl.dll: AttributesDemoControl.vb + vbc /target:library AttributesDemoControl.vb + +Form1.exe: AttributesDemoControl.dll + vbc form1.vb /r:AttributesDemoControl.dll + +clean: + del *.exe *.dll *.bin *.obj \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb new file mode 100644 index 0000000000..2d886bd7a2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.Example/VB/Form1.vb @@ -0,0 +1,210 @@ +' +' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Threading +Imports System.Windows.Forms +' + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeComponent() + End Sub + + + ' + Private Sub backgroundWorker1_DoWork( _ + sender As Object, e As DoWorkEventArgs) _ + Handles backgroundWorker1.DoWork + + ' Do not access the form's BackgroundWorker reference directly. + ' Instead, use the reference provided by the sender parameter. + Dim bw As BackgroundWorker = CType( sender, BackgroundWorker ) + + ' Extract the argument. + Dim arg As Integer = Fix(e.Argument) + + ' Start the time-consuming operation. + e.Result = TimeConsumingOperation(bw, arg) + + ' If the operation was canceled by the user, + ' set the DoWorkEventArgs.Cancel property to true. + If bw.CancellationPending Then + e.Cancel = True + End If + + End Sub + ' + + ' + ' This event handler demonstrates how to interpret + ' the outcome of the asynchronous operation implemented + ' in the DoWork event handler. + Private Sub backgroundWorker1_RunWorkerCompleted( _ + sender As Object, e As RunWorkerCompletedEventArgs) _ + Handles backgroundWorker1.RunWorkerCompleted + + If e.Cancelled Then + ' The user canceled the operation. + MessageBox.Show("Operation was canceled") + ElseIf (e.Error IsNot Nothing) Then + ' There was an error during the operation. + Dim msg As String = String.Format("An error occurred: {0}", e.Error.Message) + MessageBox.Show(msg) + Else + ' The operation completed normally. + Dim msg As String = String.Format("Result = {0}", e.Result) + MessageBox.Show(msg) + End If + End Sub + ' + + ' + ' This method models an operation that may take a long time + ' to run. It can be cancelled, it can raise an exception, + ' or it can exit normally and return a result. These outcomes + ' are chosen randomly. + Private Function TimeConsumingOperation( _ + bw As BackgroundWorker, _ + sleepPeriod As Integer) As Integer + + Dim result As Integer = 0 + + Dim rand As New Random() + + While Not bw.CancellationPending + Dim [exit] As Boolean = False + + Select Case rand.Next(3) + ' Raise an exception. + Case 0 + Throw New Exception("An error condition occurred.") + Exit While + + ' Sleep for the number of milliseconds + ' specified by the sleepPeriod parameter. + Case 1 + Thread.Sleep(sleepPeriod) + Exit While + + ' Exit and return normally. + Case 2 + result = 23 + [exit] = True + Exit While + + Case Else + Exit While + End Select + + If [exit] Then + Exit While + End If + End While + + Return result + End Function + ' + + ' + Private Sub startButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles startBtn.Click + Me.backgroundWorker1.RunWorkerAsync(2000) + End Sub + ' + + ' + Private Sub cancelButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cancelBtn.Click + Me.backgroundWorker1.CancelAsync() + End Sub + ' + + ' + ' Required designer variable. + ' + Private components As System.ComponentModel.IContainer = Nothing + + + ' + ' Clean up any resources being used. + ' + ' true if managed resources should be disposed; otherwise, false. + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + +#Region "Windows Form Designer generated code" + + + ' + ' Required method for Designer support - do not modify + ' the contents of this method with the code editor. + ' + Private Sub InitializeComponent() + Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker() + Me.startBtn = New System.Windows.Forms.Button() + Me.cancelBtn = New System.Windows.Forms.Button() + Me.SuspendLayout() + ' + ' backgroundWorker1 + ' + Me.backgroundWorker1.WorkerSupportsCancellation = True + ' + ' startButton + ' + Me.startBtn.Location = New System.Drawing.Point(12, 12) + Me.startBtn.Name = "startButton" + Me.startBtn.Size = New System.Drawing.Size(75, 23) + Me.startBtn.TabIndex = 0 + Me.startBtn.Text = "Start" + ' + ' cancelButton + ' + Me.cancelBtn.Location = New System.Drawing.Point(94, 11) + Me.cancelBtn.Name = "cancelButton" + Me.cancelBtn.Size = New System.Drawing.Size(75, 23) + Me.cancelBtn.TabIndex = 1 + Me.cancelBtn.Text = "Cancel" + ' + ' Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(183, 49) + Me.Controls.Add(cancelBtn) + Me.Controls.Add(startBtn) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + End Sub + +#End Region + + Private WithEvents backgroundWorker1 As System.ComponentModel.BackgroundWorker + Private WithEvents startBtn As System.Windows.Forms.Button + Private WithEvents cancelBtn As System.Windows.Forms.Button +End Class + + +Public Class Program + + Private Sub New() + + End Sub + + ' + ' The main entry point for the application. + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb new file mode 100644 index 0000000000..b150635c69 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker.IsBusy/VB/Form1.vb @@ -0,0 +1,159 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Threading +Imports System.Windows.Forms +Imports System.Xml + +Public Class Form1 + Inherits Form + + Private WithEvents downloadButton As Button + Private WithEvents progressBar1 As ProgressBar + Private WithEvents backgroundWorker1 As BackgroundWorker + Private document As XmlDocument = Nothing + + Public Sub New() + InitializeComponent() + Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker() + End Sub + + ' + Private Sub downloadButton_Click( _ + ByVal sender As Object, _ + ByVal e As EventArgs) _ + Handles downloadButton.Click + + ' Start the download operation in the background. + Me.backgroundWorker1.RunWorkerAsync() + + ' Disable the button for the duration of the download. + Me.downloadButton.Enabled = False + + ' Once you have started the background thread you + ' can exit the handler and the application will + ' wait until the RunWorkerCompleted event is raised. + + ' If you want to do something else in the main thread, + ' such as update a progress bar, you can do so in a loop + ' while checking IsBusy to see if the background task is + ' still running. + While Me.backgroundWorker1.IsBusy + progressBar1.Increment(1) + ' Keep UI messages moving, so the form remains + ' responsive during the asynchronous operation. + Application.DoEvents() + End While + End Sub + ' + + ' + Private Sub backgroundWorker1_DoWork( _ + ByVal sender As Object, _ + ByVal e As DoWorkEventArgs) _ + Handles backgroundWorker1.DoWork + + document = New XmlDocument() + + ' Replace this file name with a valid file name. + document.Load("http://www.tailspintoys.com/sample.xml") + + ' Uncomment the following line to + ' simulate a noticeable latency. + 'Thread.Sleep(5000); + End Sub + ' + + ' + Private Sub backgroundWorker1_RunWorkerCompleted( _ + ByVal sender As Object, _ + ByVal e As RunWorkerCompletedEventArgs) _ + Handles backgroundWorker1.RunWorkerCompleted + + ' Set progress bar to 100% in case it isn't already there. + progressBar1.Value = 100 + + If e.Error Is Nothing Then + MessageBox.Show(document.InnerXml, "Download Complete") + Else + MessageBox.Show("Failed to download file", "Download failed", MessageBoxButtons.OK, MessageBoxIcon.Error) + End If + + ' Enable the download button and reset the progress bar. + Me.downloadButton.Enabled = True + progressBar1.Value = 0 + End Sub + ' + +#Region "Windows Form Designer generated code" + ' + ' Required designer variable. + ' + Private components As System.ComponentModel.IContainer = Nothing + + ' + ' Clean up any resources being used. + ' + ' true if managed resources should be disposed; otherwise, false. + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + ' + ' Required method for Designer support - do not modify + ' the contents of this method with the code editor. + ' + Private Sub InitializeComponent() + Me.downloadButton = New System.Windows.Forms.Button + Me.progressBar1 = New System.Windows.Forms.ProgressBar + Me.SuspendLayout() + ' + 'downloadButton + ' + Me.downloadButton.Location = New System.Drawing.Point(12, 12) + Me.downloadButton.Name = "downloadButton" + Me.downloadButton.Size = New System.Drawing.Size(100, 23) + Me.downloadButton.TabIndex = 0 + Me.downloadButton.Text = "Download file" + Me.downloadButton.UseVisualStyleBackColor = True + ' + 'progressBar1 + ' + Me.progressBar1.Location = New System.Drawing.Point(12, 50) + Me.progressBar1.Name = "progressBar1" + Me.progressBar1.Size = New System.Drawing.Size(100, 26) + Me.progressBar1.TabIndex = 1 + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(136, 104) + Me.Controls.Add(Me.downloadButton) + Me.Controls.Add(Me.progressBar1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + +#End Region +End Class + + +Public Class Program + + ' + ' The main entry point for the application. + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb new file mode 100644 index 0000000000..06bcedb1a0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.BackgroundWorker/VB/fibonacciform.vb @@ -0,0 +1,282 @@ +' +' +Imports System.Collections +Imports System.ComponentModel +Imports System.Drawing +Imports System.Threading +Imports System.Windows.Forms +' + +Public Class FibonacciForm + Inherits System.Windows.Forms.Form + + ' + Private numberToCompute As Integer = 0 + Private highestPercentageReached As Integer = 0 + ' + + Private numericUpDown1 As System.Windows.Forms.NumericUpDown + Private WithEvents startAsyncButton As System.Windows.Forms.Button + Private WithEvents cancelAsyncButton As System.Windows.Forms.Button + Private progressBar1 As System.Windows.Forms.ProgressBar + Private resultLabel As System.Windows.Forms.Label + Private WithEvents backgroundWorker1 As System.ComponentModel.BackgroundWorker + + + Public Sub New() + InitializeComponent() + End Sub + + ' + Private Sub startAsyncButton_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles startAsyncButton.Click + + ' Reset the text in the result label. + resultLabel.Text = [String].Empty + + ' Disable the UpDown control until + ' the asynchronous operation is done. + Me.numericUpDown1.Enabled = False + + ' Disable the Start button until + ' the asynchronous operation is done. + Me.startAsyncButton.Enabled = False + + ' Enable the Cancel button while + ' the asynchronous operation runs. + Me.cancelAsyncButton.Enabled = True + + ' Get the value from the UpDown control. + numberToCompute = CInt(numericUpDown1.Value) + + ' Reset the variable for percentage tracking. + highestPercentageReached = 0 + + ' + + ' Start the asynchronous operation. + backgroundWorker1.RunWorkerAsync(numberToCompute) + ' + End Sub + ' + + ' + Private Sub cancelAsyncButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles cancelAsyncButton.Click + + ' Cancel the asynchronous operation. + Me.backgroundWorker1.CancelAsync() + + ' Disable the Cancel button. + cancelAsyncButton.Enabled = False + + End Sub + ' + + ' + ' This event handler is where the actual work is done. + Private Sub backgroundWorker1_DoWork( _ + ByVal sender As Object, _ + ByVal e As DoWorkEventArgs) _ + Handles backgroundWorker1.DoWork + + ' Get the BackgroundWorker object that raised this event. + Dim worker As BackgroundWorker = _ + CType(sender, BackgroundWorker) + + ' Assign the result of the computation + ' to the Result property of the DoWorkEventArgs + ' object. This is will be available to the + ' RunWorkerCompleted eventhandler. + e.Result = ComputeFibonacci(e.Argument, worker, e) + End Sub + ' + + ' + ' This event handler deals with the results of the + ' background operation. + Private Sub backgroundWorker1_RunWorkerCompleted( _ + ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _ + Handles backgroundWorker1.RunWorkerCompleted + + ' First, handle the case where an exception was thrown. + If (e.Error IsNot Nothing) Then + MessageBox.Show(e.Error.Message) + ElseIf e.Cancelled Then + ' Next, handle the case where the user canceled the + ' operation. + ' Note that due to a race condition in + ' the DoWork event handler, the Cancelled + ' flag may not have been set, even though + ' CancelAsync was called. + resultLabel.Text = "Canceled" + Else + ' Finally, handle the case where the operation succeeded. + resultLabel.Text = e.Result.ToString() + End If + + ' Enable the UpDown control. + Me.numericUpDown1.Enabled = True + + ' Enable the Start button. + startAsyncButton.Enabled = True + + ' Disable the Cancel button. + cancelAsyncButton.Enabled = False + End Sub + ' + + ' + ' This event handler updates the progress bar. + Private Sub backgroundWorker1_ProgressChanged( _ + ByVal sender As Object, ByVal e As ProgressChangedEventArgs) _ + Handles backgroundWorker1.ProgressChanged + + Me.progressBar1.Value = e.ProgressPercentage + + End Sub + ' + + ' + ' This is the method that does the actual work. For this + ' example, it computes a Fibonacci number and + ' reports progress as it does its work. + Function ComputeFibonacci( _ + ByVal n As Integer, _ + ByVal worker As BackgroundWorker, _ + ByVal e As DoWorkEventArgs) As Long + + ' The parameter n must be >= 0 and <= 91. + ' Fib(n), with n > 91, overflows a long. + If n < 0 OrElse n > 91 Then + Throw New ArgumentException( _ + "value must be >= 0 and <= 91", "n") + End If + + Dim result As Long = 0 + + ' + ' Abort the operation if the user has canceled. + ' Note that a call to CancelAsync may have set + ' CancellationPending to true just after the + ' last invocation of this method exits, so this + ' code will not have the opportunity to set the + ' DoWorkEventArgs.Cancel flag to true. This means + ' that RunWorkerCompletedEventArgs.Cancelled will + ' not be set to true in your RunWorkerCompleted + ' event handler. This is a race condition. + ' + If worker.CancellationPending Then + e.Cancel = True + ' + Else + If n < 2 Then + result = 1 + Else + result = ComputeFibonacci(n - 1, worker, e) + _ + ComputeFibonacci(n - 2, worker, e) + End If + + ' + ' Report progress as a percentage of the total task. + Dim percentComplete As Integer = _ + CSng(n) / CSng(numberToCompute) * 100 + If percentComplete > highestPercentageReached Then + highestPercentageReached = percentComplete + worker.ReportProgress(percentComplete) + End If + ' + + End If + ' + + Return result + + End Function + ' + + + Private Sub InitializeComponent() + Me.numericUpDown1 = New System.Windows.Forms.NumericUpDown + Me.startAsyncButton = New System.Windows.Forms.Button + Me.cancelAsyncButton = New System.Windows.Forms.Button + Me.resultLabel = New System.Windows.Forms.Label + Me.progressBar1 = New System.Windows.Forms.ProgressBar + Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker + CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + 'numericUpDown1 + ' + Me.numericUpDown1.Location = New System.Drawing.Point(16, 16) + Me.numericUpDown1.Maximum = New Decimal(New Integer() {91, 0, 0, 0}) + Me.numericUpDown1.Minimum = New Decimal(New Integer() {1, 0, 0, 0}) + Me.numericUpDown1.Name = "numericUpDown1" + Me.numericUpDown1.Size = New System.Drawing.Size(80, 20) + Me.numericUpDown1.TabIndex = 0 + Me.numericUpDown1.Value = New Decimal(New Integer() {1, 0, 0, 0}) + ' + 'startAsyncButton + ' + Me.startAsyncButton.Location = New System.Drawing.Point(16, 72) + Me.startAsyncButton.Name = "startAsyncButton" + Me.startAsyncButton.Size = New System.Drawing.Size(120, 23) + Me.startAsyncButton.TabIndex = 1 + Me.startAsyncButton.Text = "Start Async" + ' + 'cancelAsyncButton + ' + Me.cancelAsyncButton.Enabled = False + Me.cancelAsyncButton.Location = New System.Drawing.Point(153, 72) + Me.cancelAsyncButton.Name = "cancelAsyncButton" + Me.cancelAsyncButton.Size = New System.Drawing.Size(119, 23) + Me.cancelAsyncButton.TabIndex = 2 + Me.cancelAsyncButton.Text = "Cancel Async" + ' + 'resultLabel + ' + Me.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D + Me.resultLabel.Location = New System.Drawing.Point(112, 16) + Me.resultLabel.Name = "resultLabel" + Me.resultLabel.Size = New System.Drawing.Size(160, 23) + Me.resultLabel.TabIndex = 3 + Me.resultLabel.Text = "(no result)" + Me.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter + ' + 'progressBar1 + ' + Me.progressBar1.Location = New System.Drawing.Point(18, 48) + Me.progressBar1.Name = "progressBar1" + Me.progressBar1.Size = New System.Drawing.Size(256, 8) + Me.progressBar1.TabIndex = 4 + ' + 'backgroundWorker1 + ' + Me.backgroundWorker1.WorkerReportsProgress = True + Me.backgroundWorker1.WorkerSupportsCancellation = True + ' + 'FibonacciForm + ' + Me.ClientSize = New System.Drawing.Size(292, 118) + Me.Controls.Add(Me.progressBar1) + Me.Controls.Add(Me.resultLabel) + Me.Controls.Add(Me.cancelAsyncButton) + Me.Controls.Add(Me.startAsyncButton) + Me.Controls.Add(Me.numericUpDown1) + Me.Name = "FibonacciForm" + Me.Text = "Fibonacci Calculator" + CType(Me.numericUpDown1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + + End Sub + + _ + Shared Sub Main() + Application.Run(New FibonacciForm) + End Sub +End Class + +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/VB/form1.vb new file mode 100644 index 0000000000..e4149a3839 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.DesignerSerializationVisibilityAttribute/VB/form1.vb @@ -0,0 +1,125 @@ +' +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms +' + +' This sample demonstrates the use of the +' DesignerSerializationVisibility attribute +' to serialize a collection of strings +' at design time. +Class Form1 + Inherits Form + Private serializationDemoControl1 As SerializationDemoControl + + + Public Sub New() + InitializeComponent() + End Sub + + + ' The Windows Forms Designer emits code to this method. + ' If an instance of SerializationDemoControl is added + ' to the form, the Strings will be serialized here. + Private Sub InitializeComponent() + Me.serializationDemoControl1 = New SerializationDemoControl + Me.SuspendLayout() + ' + 'serializationDemoControl1 + ' + Me.serializationDemoControl1.Location = New System.Drawing.Point(0, 0) + Me.serializationDemoControl1.Name = "serializationDemoControl1" + Me.serializationDemoControl1.Padding = New System.Windows.Forms.Padding(5) + Me.serializationDemoControl1.TabIndex = 0 + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.serializationDemoControl1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class + +' +Public Class SerializationDemoControl + Inherits UserControl + ' This is the TextBox contained by + ' the SerializationDemoControl. + Private textBox1 As System.Windows.Forms.TextBox + + ' + ' This field backs the Strings property. + Private stringsValue(1) As String + ' + + Public Sub New() + InitializeComponent() + End Sub + + ' + ' When the DesignerSerializationVisibility attribute has + ' a value of "Content" or "Visible" the designer will + ' serialize the property. This property can also be edited + ' at design time with a CollectionEditor. + _ + Public Property Strings() As String() + Get + Return Me.stringsValue + End Get + Set(ByVal value As String()) + Me.stringsValue = Value + + ' Populate the contained TextBox with the values + ' in the stringsValue array. + Dim sb As New StringBuilder(Me.stringsValue.Length) + + Dim i As Integer + For i = 0 To (Me.stringsValue.Length) - 1 + sb.Append(Me.stringsValue(i)) + sb.Append(ControlChars.Cr + ControlChars.Lf) + Next i + + Me.textBox1.Text = sb.ToString() + End Set + End Property + ' + + Private Sub InitializeComponent() + Me.textBox1 = New System.Windows.Forms.TextBox() + Me.SuspendLayout() + + ' Settings for the contained TextBox control. + Me.textBox1.AutoSize = False + Me.textBox1.Dock = System.Windows.Forms.DockStyle.Fill + Me.textBox1.Location = New System.Drawing.Point(5, 5) + Me.textBox1.Margin = New System.Windows.Forms.Padding(0) + Me.textBox1.Multiline = True + Me.textBox1.Name = "textBox1" + Me.textBox1.ReadOnly = True + Me.textBox1.ScrollBars = ScrollBars.Vertical + Me.textBox1.Size = New System.Drawing.Size(140, 140) + Me.textBox1.TabIndex = 0 + + ' Settings for SerializationDemoControl. + Me.Controls.Add(textBox1) + Me.Name = "SerializationDemoControl" + Me.Padding = New System.Windows.Forms.Padding(5) + Me.ResumeLayout(False) + End Sub +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/BusinessObjectBase.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/BusinessObjectBase.vb new file mode 100644 index 0000000000..5eb8b634c3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/BusinessObjectBase.vb @@ -0,0 +1,22 @@ +' +Imports System.ComponentModel + +Public Class BusinessObjectBase + Implements INotifyPropertyChanged + +#Region "INotifyPropertyChanged Members" + + Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged + + Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) + OnPropertyChanged(New PropertyChangedEventArgs(propertyName)) + End Sub + + Private Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs) + RaiseEvent PropertyChanged(Me, e) + End Sub + +#End Region + +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Employee.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Employee.vb new file mode 100644 index 0000000000..a9fafebc59 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Employee.vb @@ -0,0 +1,54 @@ +' +Imports System.ComponentModel + +Public Class Employee + Inherits BusinessObjectBase + + Private _id As String + Private _name As String + Private _parkingId As Decimal + + Public Sub New(ByVal name As String, ByVal parkId As Decimal) + MyBase.New() + Me._id = System.Guid.NewGuid().ToString() + ' Set values + Me.Name = name + Me.ParkingID = parkId + End Sub + + Public ReadOnly Property ID() As String + Get + Return _id + End Get + End Property + + Const NAME_Const As String = "Name" + + Public Property Name() As String + Get + Return _name + End Get + Set(ByVal value As String) + If _name <> value Then + _name = value + OnPropertyChanged(NAME_Const) + End If + End Set + End Property + + Const PARKINGID_Const As String = "ParkingID" + + Public Property ParkingID() As Decimal + Get + Return _parkingId + End Get + Set(ByVal value As Decimal) + If _parkingId <> value Then + _parkingId = value + OnPropertyChanged(PARKINGID_Const) + End If + End Set + End Property + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/EmployeeListSource.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/EmployeeListSource.vb new file mode 100644 index 0000000000..e146a1f70b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/EmployeeListSource.vb @@ -0,0 +1,80 @@ +' +Imports System.ComponentModel + +Public Class EmployeeListSource + Inherits Component + Implements IListSource + + _ +Public Sub New(ByVal Container As System.ComponentModel.IContainer) + MyClass.New() + + 'Required for Windows.Forms Class Composition Designer support + Container.Add(Me) + + End Sub + + _ + Public Sub New() + MyBase.New() + + 'This call is required by the Component Designer. + InitializeComponent() + + End Sub + + 'Component overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + 'Required by the Component Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Component Designer + 'It can be modified using the Component Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + components = New System.ComponentModel.Container() + End Sub + + ' +#Region "IListSource Members" + + ' + Public ReadOnly Property ContainsListCollection() As Boolean Implements System.ComponentModel.IListSource.ContainsListCollection + Get + Return False + End Get + End Property + ' + + ' + Public Function GetList() As System.Collections.IList Implements System.ComponentModel.IListSource.GetList + + Dim ble As New BindingList(Of Employee) + + If Not Me.DesignMode Then + ble.Add(New Employee("Aaberg, Jesper", 26000000)) + ble.Add(New Employee("Cajhen, Janko", 19600000)) + ble.Add(New Employee("Furse, Kari", 19000000)) + ble.Add(New Employee("Langhorn, Carl", 16000000)) + ble.Add(New Employee("Todorov, Teodor", 15700000)) + ble.Add(New Employee("Verebélyi, Ágnes", 15700000)) + End If + + Return ble + + End Function + ' + +#End Region + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Form1.vb new file mode 100644 index 0000000000..23b80770ef --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/Form1.vb @@ -0,0 +1,140 @@ +' +Imports System.ComponentModel +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Friend WithEvents flowLayoutPanel1 As FlowLayoutPanel + Friend WithEvents label2 As Label + Friend WithEvents dataGridView1 As DataGridView + Friend WithEvents nameDataGridViewTextBoxColumn As DataGridViewTextBoxColumn + Friend WithEvents salaryDataGridViewTextBoxColumn As DataGridViewTextBoxColumn + Friend WithEvents iDDataGridViewTextBoxColumn As DataGridViewTextBoxColumn + Friend WithEvents employeeListSource1 As EmployeeListSource + + Public Sub New() + MyBase.New() + + Me.InitializeComponent() + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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() + + Dim dataGridViewCellStyle1 = New System.Windows.Forms.DataGridViewCellStyle() + Dim dataGridViewCellStyle2 = New System.Windows.Forms.DataGridViewCellStyle() + Me.flowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel() + Me.label2 = New System.Windows.Forms.Label() + Me.dataGridView1 = New System.Windows.Forms.DataGridView() + Me.nameDataGridViewTextBoxColumn = New System.Windows.Forms.DataGridViewTextBoxColumn() + Me.salaryDataGridViewTextBoxColumn = New System.Windows.Forms.DataGridViewTextBoxColumn() + Me.iDDataGridViewTextBoxColumn = New System.Windows.Forms.DataGridViewTextBoxColumn() + Me.employeeListSource1 = New EmployeeListSource(Me.components) + Me.flowLayoutPanel1.SuspendLayout() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + ' flowLayoutPanel1 + ' + Me.flowLayoutPanel1.AutoSize = True + Me.flowLayoutPanel1.Controls.Add(Me.label2) + Me.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top + Me.flowLayoutPanel1.Location = New System.Drawing.Point(0, 0) + Me.flowLayoutPanel1.Name = "flowLayoutPanel1" + Me.flowLayoutPanel1.Size = New System.Drawing.Size(416, 51) + Me.flowLayoutPanel1.TabIndex = 11 + ' + ' label2 + ' + Me.label2.AutoSize = True + Me.label2.Location = New System.Drawing.Point(3, 6) + Me.label2.Margin = New System.Windows.Forms.Padding(3, 6, 3, 6) + Me.label2.Name = "label2" + Me.label2.Size = New System.Drawing.Size(408, 39) + Me.label2.TabIndex = 0 + Me.label2.Text = "This sample demonstrates how to implement the IListSource interface. In this sam" + _ + "ple, a DataGridView is bound at design time to a Component (employeeListSource1)" + _ + " that implements IListSource." + ' + ' dataGridView1 + ' + Me.dataGridView1.AllowUserToAddRows = False + Me.dataGridView1.AllowUserToDeleteRows = False + dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192) + Me.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1 + Me.dataGridView1.AutoGenerateColumns = False + Me.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() { _ + Me.nameDataGridViewTextBoxColumn, Me.salaryDataGridViewTextBoxColumn, Me.iDDataGridViewTextBoxColumn}) + Me.dataGridView1.DataSource = Me.employeeListSource1 + Me.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill + Me.dataGridView1.Location = New System.Drawing.Point(0, 51) + Me.dataGridView1.Name = "dataGridView1" + Me.dataGridView1.RowHeadersVisible = False + Me.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect + Me.dataGridView1.Size = New System.Drawing.Size(416, 215) + Me.dataGridView1.TabIndex = 12 + ' + ' nameDataGridViewTextBoxColumn + ' + Me.nameDataGridViewTextBoxColumn.DataPropertyName = "Name" + Me.nameDataGridViewTextBoxColumn.FillWeight = 131.7987F + Me.nameDataGridViewTextBoxColumn.HeaderText = "Name" + Me.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn" + ' + ' salaryDataGridViewTextBoxColumn + ' + Me.salaryDataGridViewTextBoxColumn.DataPropertyName = "ParkingID" + Me.salaryDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2 + Me.salaryDataGridViewTextBoxColumn.FillWeight = 121.8274F + Me.salaryDataGridViewTextBoxColumn.HeaderText = "Parking ID" + Me.salaryDataGridViewTextBoxColumn.Name = "salaryDataGridViewTextBoxColumn" + ' + ' iDDataGridViewTextBoxColumn + ' + Me.iDDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill + Me.iDDataGridViewTextBoxColumn.DataPropertyName = "ID" + Me.iDDataGridViewTextBoxColumn.FillWeight = 46.37391F + Me.iDDataGridViewTextBoxColumn.HeaderText = "ID" + Me.iDDataGridViewTextBoxColumn.Name = "iDDataGridViewTextBoxColumn" + Me.iDDataGridViewTextBoxColumn.ReadOnly = True + ' + ' Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(416, 266) + Me.Controls.Add(Me.dataGridView1) + Me.Controls.Add(Me.flowLayoutPanel1) + Me.Name = "Form1" + Me.Text = "IListSource Sample" + Me.flowLayoutPanel1.ResumeLayout(False) + Me.flowLayoutPanel1.PerformLayout() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Shared Sub Main() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/makefile new file mode 100644 index 0000000000..920cd0d36f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IListSource/VB/makefile @@ -0,0 +1,5 @@ +ITypedList.exe: BusinessObjectBase.vb Employee.vb EmployeeListSource.vb Form1.vb + vbc /t:exe /out:ITypedList.exe BusinessObjectBase.vb Employee.vb EmployeeListSource.vb Form1.vb + +clean: + del *.dll *.bin *.exe \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/VB/Form1.vb new file mode 100644 index 0000000000..4ed0f0aeef --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.IPropertyChangeExample/VB/Form1.vb @@ -0,0 +1,139 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Runtime.CompilerServices +Imports System.Windows.Forms + +' This form demonstrates using a BindingSource to bind +' a list to a DataGridView control. The list does not +' raise change notifications. However the DemoCustomer type +' in the list does. + +Public Class Form1 + Inherits System.Windows.Forms.Form + ' This button causes the value of a list element to be changed. + Private changeItemBtn As New Button() + + ' This DataGridView control displays the contents of the list. + Private customersDataGridView As New DataGridView() + + ' This BindingSource binds the list to the DataGridView control. + Private customersBindingSource As New BindingSource() + + Public Sub New() + InitializeComponent() + + ' Set up the "Change Item" button. + Me.changeItemBtn.Text = "Change Item" + Me.changeItemBtn.Dock = DockStyle.Bottom + AddHandler Me.changeItemBtn.Click, AddressOf changeItemBtn_Click + Me.Controls.Add(Me.changeItemBtn) + + ' Set up the DataGridView. + customersDataGridView.Dock = DockStyle.Top + Me.Controls.Add(customersDataGridView) + + Me.Size = New Size(400, 200) + End Sub + + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Me.Load + + ' Create and populate the list of DemoCustomer objects + ' which will supply data to the DataGridView. + Dim customerList As New BindingList(Of DemoCustomer) + + customerList.Add(DemoCustomer.CreateNewCustomer()) + customerList.Add(DemoCustomer.CreateNewCustomer()) + customerList.Add(DemoCustomer.CreateNewCustomer()) + + ' Bind the list to the BindingSource. + Me.customersBindingSource.DataSource = customerList + + ' Attach the BindingSource to the DataGridView. + Me.customersDataGridView.DataSource = Me.customersBindingSource + End Sub + + ' This event handler changes the value of the CompanyName + ' property for the first item in the list. + Private Sub changeItemBtn_Click(ByVal sender As Object, ByVal e As EventArgs) + ' Get a reference to the list from the BindingSource. + Dim customerList As BindingList(Of DemoCustomer) = _ + CType(customersBindingSource.DataSource, BindingList(Of DemoCustomer)) + + ' Change the value of the CompanyName property for the + ' first item in the list. + customerList(0).CustomerName = "Tailspin Toys" + customerList(0).PhoneNumber = "(708)555-0150" + End Sub +End Class + +' +' This class implements a simple customer type +' that implements the IPropertyChange interface. +Public Class DemoCustomer + Implements INotifyPropertyChanged + + ' These fields hold the values for the public properties. + Private idValue As Guid = Guid.NewGuid() + Private customerNameValue As String = String.Empty + Private phoneNumberValue As String = String.Empty + + Public Event PropertyChanged As PropertyChangedEventHandler _ + Implements INotifyPropertyChanged.PropertyChanged + + ' This method is called by the Set accessor of each property. + ' The CallerMemberName attribute that is applied to the optional propertyName + ' parameter causes the property name of the caller to be substituted as an argument. + Private Sub NotifyPropertyChanged( Optional ByVal propertyName As String = Nothing) + RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) + End Sub + + ' The constructor is private to enforce the factory pattern. + Private Sub New() + customerNameValue = "Customer" + phoneNumberValue = "(312)555-0100" + End Sub + + ' This is the public factory method. + Public Shared Function CreateNewCustomer() As DemoCustomer + Return New DemoCustomer() + End Function + + ' This property represents an ID, suitable + ' for use as a primary key in a database. + Public ReadOnly Property ID() As Guid + Get + Return Me.idValue + End Get + End Property + + Public Property CustomerName() As String + Get + Return Me.customerNameValue + End Get + + Set(ByVal value As String) + If Not (value = customerNameValue) Then + Me.customerNameValue = value + NotifyPropertyChanged() + End If + End Set + End Property + + Public Property PhoneNumber() As String + Get + Return Me.phoneNumberValue + End Get + + Set(ByVal value As String) + If Not (value = phoneNumberValue) Then + Me.phoneNumberValue = value + NotifyPropertyChanged() + End If + End Set + End Property +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Customer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Customer.vb new file mode 100644 index 0000000000..b2c769bc64 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Customer.vb @@ -0,0 +1,138 @@ +' +Imports System.ComponentModel + +Public Class Customer + Implements INotifyPropertyChanged + + Public Sub New() + + End Sub + + Public Sub New(ByVal id As Integer, ByVal name As String, ByVal company As String, ByVal address As String, ByVal city As String, ByVal state As String, ByVal zip As String) + Me._id = id + Me._name = name + Me._company = company + Me._address = address + Me._city = city + Me._state = state + Me._zip = zip + + End Sub + +#Region "Public Properties" + + Private _id As Integer + Public Property ID() As Integer + Get + Return _id + End Get + Set(ByVal value As Integer) + If _id <> value Then + _id = value + OnPropertyChanged(New PropertyChangedEventArgs("ID")) + End If + End Set + End Property + + Private _name As String + + Public Property Name() As String + Get + Return _name + End Get + Set(ByVal value As String) + If _name <> value Then + _name = value + OnPropertyChanged(New PropertyChangedEventArgs("Name")) + End If + End Set + End Property + + Private _company As String + + Public Property Company() As String + Get + Return _company + End Get + Set(ByVal value As String) + If _company <> value Then + _company = value + OnPropertyChanged(New PropertyChangedEventArgs("Company")) + End If + End Set + End Property + + + Private _address As String + + Public Property Address() As String + Get + Return _address + End Get + Set(ByVal value As String) + If _address <> value Then + _address = value + OnPropertyChanged(New PropertyChangedEventArgs("Address")) + End If + End Set + End Property + + + Private _city As String + + Public Property City() As String + Get + Return _city + End Get + Set(ByVal value As String) + If _city <> value Then + _city = value + OnPropertyChanged(New PropertyChangedEventArgs("City")) + End If + End Set + End Property + + + Private _state As String + + Public Property State() As String + Get + Return _state + End Get + Set(ByVal value As String) + If _state <> value Then + _state = value + OnPropertyChanged(New PropertyChangedEventArgs("State")) + End If + End Set + End Property + + Private _zip As String + + Public Property ZipCode() As String + Get + Return _zip + End Get + Set(ByVal value As String) + If _zip <> value Then + _zip = value + OnPropertyChanged(New PropertyChangedEventArgs("ZipCode")) + End If + End Set + End Property + +#End Region + + +#Region "INotifyPropertyChanged Members" + + Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged + + Protected Overridable Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs) + RaiseEvent PropertyChanged(Me, e) + End Sub + +#End Region + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Form1.vb new file mode 100644 index 0000000000..d9377b1d50 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/Form1.vb @@ -0,0 +1,150 @@ +' +Imports System.ComponentModel +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Friend WithEvents flowLayoutPanel1 As FlowLayoutPanel + Friend WithEvents label2 As System.Windows.Forms.Label + Friend WithEvents dataGridView1 As DataGridView + Friend WithEvents button1 As Button + Friend WithEvents button2 As Button + + Dim sortableBindingListOfCustomers As SortableBindingList(Of Customer) + Dim bindingListOfCustomers As BindingList(Of Customer) + + Public Sub New() + MyBase.New() + + Me.InitializeComponent() + End Sub + + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + + sortableBindingListOfCustomers = New SortableBindingList(Of Customer)() + bindingListOfCustomers = New BindingList(Of Customer)() + + Me.dataGridView1.DataSource = bindingListOfCustomers + End Sub + + + Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click + Me.dataGridView1.DataSource = Nothing + Me.dataGridView1.DataSource = sortableBindingListOfCustomers + End Sub + + + Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click + Me.dataGridView1.DataSource = Nothing + Me.dataGridView1.DataSource = bindingListOfCustomers + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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() + Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1)) + Me.flowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel + Me.label2 = New System.Windows.Forms.Label + Me.dataGridView1 = New System.Windows.Forms.DataGridView + Me.button1 = New System.Windows.Forms.Button + Me.button2 = New System.Windows.Forms.Button + Me.flowLayoutPanel1.SuspendLayout() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + 'flowLayoutPanel1 + ' + Me.flowLayoutPanel1.AutoSize = True + Me.flowLayoutPanel1.Controls.Add(Me.label2) + Me.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top + Me.flowLayoutPanel1.Location = New System.Drawing.Point(0, 0) + Me.flowLayoutPanel1.Name = "flowLayoutPanel1" + Me.flowLayoutPanel1.Size = New System.Drawing.Size(566, 51) + Me.flowLayoutPanel1.TabIndex = 13 + ' + 'label2 + ' + Me.label2.AutoSize = True + Me.label2.Location = New System.Drawing.Point(3, 6) + Me.label2.Margin = New System.Windows.Forms.Padding(3, 6, 3, 6) + Me.label2.Name = "label2" + Me.label2.Size = New System.Drawing.Size(558, 39) + Me.label2.TabIndex = 0 + Me.label2.Text = "This sample demonstrates how to implement the ITypedList interface. Clicking on the 'Sort Columns' button will bind the DataGridView to a sub-classed BindingList that implements ITypedList to provide a sorted list of columns. Clicking on the 'Reset' button will bind the DataGridView to a normal BindingList." + ' + 'dataGridView1 + ' + Me.dataGridView1.AllowUserToAddRows = False + Me.dataGridView1.AllowUserToDeleteRows = False + Me.dataGridView1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ + Or System.Windows.Forms.AnchorStyles.Left) _ + Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill + Me.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.Location = New System.Drawing.Point(6, 57) + Me.dataGridView1.Name = "dataGridView1" + Me.dataGridView1.ReadOnly = True + Me.dataGridView1.RowHeadersVisible = False + Me.dataGridView1.Size = New System.Drawing.Size(465, 51) + Me.dataGridView1.TabIndex = 14 + ' + 'button1 + ' + Me.button1.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.button1.Location = New System.Drawing.Point(477, 57) + Me.button1.Name = "button1" + Me.button1.Size = New System.Drawing.Size(82, 23) + Me.button1.TabIndex = 15 + Me.button1.Text = "Sort Columns" + Me.button1.UseVisualStyleBackColor = True + ' + 'button2 + ' + Me.button2.Location = New System.Drawing.Point(477, 86) + Me.button2.Name = "button2" + Me.button2.Size = New System.Drawing.Size(82, 23) + Me.button2.TabIndex = 16 + Me.button2.Text = "Reset" + Me.button2.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(566, 120) + Me.Controls.Add(Me.button2) + Me.Controls.Add(Me.button1) + Me.Controls.Add(Me.dataGridView1) + Me.Controls.Add(Me.flowLayoutPanel1) + Me.Name = "Form1" + Me.Text = "ITypedList Sample" + Me.flowLayoutPanel1.ResumeLayout(False) + Me.flowLayoutPanel1.PerformLayout() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + Me.PerformLayout() + End Sub + + Shared Sub Main() + Application.Run(New Form1()) + End Sub + +End Class + + +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/SortableBindingList.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/SortableBindingList.vb new file mode 100644 index 0000000000..d51d26dd61 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/SortableBindingList.vb @@ -0,0 +1,63 @@ +' +Imports System.ComponentModel +Imports System.Collections.Generic +Imports System.Windows.Forms + + _ +Public Class SortableBindingList(Of Tkey) + Inherits BindingList(Of Tkey) + Implements ITypedList + + _ + Private properties As PropertyDescriptorCollection + + Public Sub New() + MyBase.New() + + ' Get the 'shape' of the list. + ' Only get the public properties marked with Browsable = true. + Dim pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(Tkey), New Attribute() {New BrowsableAttribute(True)}) + + ' Sort the properties. + properties = pdc.Sort() + + End Sub + + ' +#Region "ITypedList Implementation" + + ' + Public Function GetItemProperties(ByVal listAccessors() As System.ComponentModel.PropertyDescriptor) As System.ComponentModel.PropertyDescriptorCollection Implements System.ComponentModel.ITypedList.GetItemProperties + + Dim pdc As PropertyDescriptorCollection + + If (Not (listAccessors Is Nothing)) And (listAccessors.Length > 0) Then + ' Return child list shape + pdc = ListBindingHelper.GetListItemProperties(listAccessors(0).PropertyType) + Else + ' Return properties in sort order + pdc = properties + End If + + Return pdc + + End Function + ' + + ' + ' This method is only used in the design-time framework + ' and by the obsolete DataGrid control. + Public Function GetListName( _ + ByVal listAccessors() As PropertyDescriptor) As String _ + Implements System.ComponentModel.ITypedList.GetListName + + Return GetType(Tkey).Name + + End Function + ' + +#End Region + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/makefile new file mode 100644 index 0000000000..ae8e78c822 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.ComponentModel.ITypedList/VB/makefile @@ -0,0 +1,5 @@ +ITypedList.exe: SortableBindingList.vb Customer.vb Form1.vb + vbc /t:exe /out:ITypedList.exe SortableBindingList.vb Customer.vb Form1.vb + +clean: + del *.dll *.bin *.exe \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb new file mode 100644 index 0000000000..e9778a6c45 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlignDrawnText/VB/Form1.vb @@ -0,0 +1,143 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + + + +Public Class Form1 + Inherits Form + + Public Sub New() + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + + Private Sub AlignTextWithTextRenderer(ByVal e As PaintEventArgs) + ' + Dim text2 As String = "Use TextFormatFlags and Rectangle objects to" & _ + " center text in a rectangle." + + Dim font2 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) + Try + Dim rect2 As New Rectangle(150, 10, 130, 140) + + ' Create a TextFormatFlags with word wrapping, horizontal center and + ' vertical center specified. + Dim flags As TextFormatFlags = TextFormatFlags.HorizontalCenter Or _ + TextFormatFlags.VerticalCenter Or TextFormatFlags.WordBreak + + ' Draw the text and the surrounding rectangle. + TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags) + e.Graphics.DrawRectangle(Pens.Black, rect2) + Finally + font2.Dispose() + End Try + ' + End Sub + + + + + Private Sub AlignTextWithDrawString(ByVal e As PaintEventArgs) + ' + Dim text1 As String = "Use StringFormat and Rectangle objects to" & _ + " center text in a rectangle." + Dim font1 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) + Try + Dim rect1 As New Rectangle(10, 10, 130, 140) + + ' Create a StringFormat object with the each line of text, and the block + ' of text centered on the page. + Dim stringFormat As New StringFormat() + stringFormat.Alignment = StringAlignment.Center + stringFormat.LineAlignment = StringAlignment.Center + + ' Draw the text and the surrounding rectangle. + e.Graphics.DrawString(text1, font1, Brushes.Blue, rect1, stringFormat) + e.Graphics.DrawRectangle(Pens.Black, rect1) + Finally + font1.Dispose() + End Try + ' + End Sub + + Private Sub DrawTextAtLocation1(ByVal e As PaintEventArgs) + ' + Dim font1 As New Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel) + Try + Dim pointF1 As New PointF(30, 10) + e.Graphics.DrawString("Hello", font1, Brushes.Blue, pointF1) + Finally + font1.Dispose() + End Try + ' + End Sub + + + Private Sub DrawTextAtLocation2(ByVal e As PaintEventArgs) + ' + Dim font As New Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel) + Try + Dim point1 As New Point(30, 10) + TextRenderer.DrawText(e.Graphics, "Hello", font, point1, Color.Blue) + Finally + font.Dispose() + End Try + ' + End Sub + + + Private Sub DrawTextInARectangle1(ByVal e As PaintEventArgs) + ' + Dim text1 As String = "Draw text in a rectangle by passing a RectF to the DrawString method." + Dim font1 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) + Try + Dim rectF1 As New RectangleF(30, 10, 100, 122) + e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1) + e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1)) + Finally + font1.Dispose() + End Try + ' + End Sub + + + Private Sub DrawTextInARectangle2(ByVal e As PaintEventArgs) + ' + Dim text2 As String = _ + "Draw text in a rectangle by passing a RectF to the DrawString method." + Dim font2 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) + Try + Dim rect2 As New Rectangle(30, 10, 100, 122) + + ' Specify the text is wrapped. + Dim flags As TextFormatFlags = TextFormatFlags.WordBreak + TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags) + e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2)) + Finally + font2.Dispose() + End Try + ' + End Sub + + + Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _ + Handles Me.Paint + 'AlignTextWithDrawString(e); + 'AlignTextWithTextRenderer(e); + 'DrawTextAtLocation1(e); + 'DrawTextAtLocation2(e); + DrawTextInARectangle1(e) + + End Sub +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb new file mode 100644 index 0000000000..7071d3ca10 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.AlphaBlending/VB/Class1.vb @@ -0,0 +1,167 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Drawing2D +Imports System.Drawing.Imaging + +Public Class SystemDrawingAlphaBlending + +' 8f2508af-f495-4223-b5cc-646cbbb520eb +' How to: Draw Opaque and Semitransparent Lines + Public Sub Method11(ByVal e As PaintEventArgs) + ' + Dim bitmap As New Bitmap("Texture1.jpg") + e.Graphics.DrawImage(bitmap, 10, 5, bitmap.Width, bitmap.Height) + + Dim opaquePen As New Pen(Color.FromArgb(255, 0, 0, 255), 15) + Dim semiTransPen As New Pen(Color.FromArgb(128, 0, 0, 255), 15) + + e.Graphics.DrawLine(opaquePen, 0, 20, 100, 20) + e.Graphics.DrawLine(semiTransPen, 0, 40, 100, 40) + + e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected + e.Graphics.DrawLine(semiTransPen, 0, 60, 100, 60) + + ' + End Sub +' a27121e6-f7e9-4c09-84e2-f05aa9d2a1bb +' How to: Use a Color Matrix to Set Alpha Values in Images + Public Sub Method21(ByVal e As PaintEventArgs) + ' + ' Create the Bitmap object and load it with the texture image. + Dim bitmap As New Bitmap("Texture.jpg") + + ' Initialize the color matrix. + ' Note the value 0.8 in row 4, column 4. + Dim matrixItems As Single()() = { _ + New Single() {1, 0, 0, 0, 0}, _ + New Single() {0, 1, 0, 0, 0}, _ + New Single() {0, 0, 1, 0, 0}, _ + New Single() {0, 0, 0, 0.8F, 0}, _ + New Single() {0, 0, 0, 0, 1}} + + Dim colorMatrix As New ColorMatrix(matrixItems) + + ' Create an ImageAttributes object and set its color matrix. + Dim imageAtt As New ImageAttributes() + imageAtt.SetColorMatrix( _ + colorMatrix, _ + ColorMatrixFlag.Default, _ + ColorAdjustType.Bitmap) + + ' First draw a wide black line. + e.Graphics.DrawLine( _ + New Pen(Color.Black, 25), _ + New Point(10, 35), _ + New Point(200, 35)) + + ' Now draw the semitransparent bitmap image. + Dim iWidth As Integer = bitmap.Width + Dim iHeight As Integer = bitmap.Height + + ' Pass in the destination rectangle (2nd argument) and the x _ + ' coordinate (3rd argument), x coordinate (4th argument), width _ + ' (5th argument), and height (6th argument) of the source rectangle. + e.Graphics.DrawImage( _ + bitmap, _ + New Rectangle(30, 0, iWidth, iHeight), _ + 0.0F, _ + 0.0F, _ + iWidth, _ + iHeight, _ + GraphicsUnit.Pixel, _ + imageAtt) + + ' + End Sub +' a4f6f6b8-3bc8-440a-84af-d62ef0f8ff40 +' How to: Draw with Opaque and Semitransparent Brushes + Public Sub Method31(ByVal e As PaintEventArgs) + ' + Dim bitmap As New Bitmap("Texture1.jpg") + e.Graphics.DrawImage(bitmap, 50, 50, bitmap.Width, bitmap.Height) + + Dim opaqueBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255)) + Dim semiTransBrush As New SolidBrush(Color.FromArgb(128, 0, 0, 255)) + + e.Graphics.FillEllipse(opaqueBrush, 35, 45, 45, 30) + e.Graphics.FillEllipse(semiTransBrush, 86, 45, 45, 30) + + e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected + e.Graphics.FillEllipse(semiTransBrush, 40, 90, 86, 30) + + ' + End Sub +' f331df2d-b395-4b0a-95be-24fec8c9bbb5 +' How to: Use Compositing Mode to Control Alpha Blending + Public Sub Method41() + ' Create a blank bitmap. + Dim myBitmap As New Bitmap(180, 100) + + ' Create a Graphics object that we can use to draw on the bitmap. + Dim bitmapGraphics As Graphics = Graphics.FromImage(myBitmap) + ' + bitmapGraphics.CompositingMode = CompositingMode.SourceCopy + + ' + End Sub + Public Sub Method42() + ' Create a blank bitmap. + Dim myBitmap As New Bitmap(180, 100) + + ' Create a Graphics object that we can use to draw on the bitmap. + Dim bitmapGraphics As Graphics = Graphics.FromImage(myBitmap) + ' + bitmapGraphics.CompositingMode = CompositingMode.SourceOver + + ' + End Sub + Public Sub Method43(ByVal e As PaintEventArgs) + ' + ' Create a blank bitmap. + Dim myBitmap As New Bitmap(180, 100) + + ' Create a Graphics object that we can use to draw on the bitmap. + Dim bitmapGraphics As Graphics = Graphics.FromImage(myBitmap) + + ' Create a red brush and a green brush, each with an alpha value of 160. + Dim redBrush As New SolidBrush(Color.FromArgb(160, 255, 0, 0)) + Dim greenBrush As New SolidBrush(Color.FromArgb(160, 0, 255, 0)) + + ' Set the compositing mode so that when we draw overlapping ellipses, + ' the colors of the ellipses are not blended. + bitmapGraphics.CompositingMode = CompositingMode.SourceCopy + + ' Fill an ellipse using a red brush that has an alpha value of 160. + bitmapGraphics.FillEllipse(redBrush, 0, 0, 150, 70) + + ' Fill a second ellipse using a green brush that has an alpha value of + ' 160. The green ellipse overlaps the red ellipse, but the green is not + ' blended with the red. + bitmapGraphics.FillEllipse(greenBrush, 30, 30, 150, 70) + + 'Set the compositing quality of the form's Graphics object. + e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected + + ' Draw a multicolored background. + Dim colorBrush As New SolidBrush(Color.Aqua) + e.Graphics.FillRectangle(colorBrush, 200, 0, 60, 100) + colorBrush.Color = Color.Yellow + e.Graphics.FillRectangle(colorBrush, 260, 0, 60, 100) + colorBrush.Color = Color.Fuchsia + e.Graphics.FillRectangle(colorBrush, 320, 0, 60, 100) + + 'Display the bitmap on a white background. + e.Graphics.DrawImage(myBitmap, 0, 0) + + ' Display the bitmap on a multicolored background. + e.Graphics.DrawImage(myBitmap, 200, 0) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb new file mode 100644 index 0000000000..facd42ee9d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConceptualHowTos/VB/form1.vb @@ -0,0 +1,143 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing + + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Private Sub DoSomething1() + ' Snippet for: \vbtskcodeexampledrawingfilledellipseonform.xml + ' + Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red) + Dim formGraphics As System.Drawing.Graphics + formGraphics = Me.CreateGraphics() + formGraphics.FillEllipse(myBrush, New Rectangle(0, 0, 200, 300)) + myBrush.Dispose() + formGraphics.Dispose() + ' + End Sub + + Private Sub DoSomething2() + ' Snippet for: \vbtskcodeexampledrawingfilledrectangleonform.xml + ' + Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red) + Dim formGraphics As System.Drawing.Graphics + formGraphics = Me.CreateGraphics() + formGraphics.FillRectangle(myBrush, New Rectangle(0, 0, 200, 300)) + myBrush.Dispose() + formGraphics.Dispose() + ' + End Sub + + Private Sub DoSomething3() + ' Snippet for: \vbtskcodeexamplecreatingpen.xml + ' + Dim myPen As System.Drawing.Pen + myPen = New System.Drawing.Pen(System.Drawing.Color.Tomato) + ' + End Sub + + Private Sub DoSomething4() + ' Snippet for: \vbtskcodeexamplecreatingsolidbrush.xml + ' + Dim myBrush As System.Drawing.SolidBrush + myBrush = New System.Drawing.SolidBrush(System.Drawing.Color.PeachPuff) + ' + End Sub + + Private Sub DoSomething5() + ' Snippet for: \vbtskcodeexampledrawinglineonform.xml + ' + Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red) + Dim formGraphics As System.Drawing.Graphics + formGraphics = Me.CreateGraphics() + formGraphics.DrawLine(myPen, 0, 0, 200, 200) + myPen.Dispose() + formGraphics.Dispose() + ' + End Sub + + ' Snippet for: \vbtskcodeexampledrawingoutlinedshapes.xml + ' + Private Sub DrawEllipse() + Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red) + Dim formGraphics As System.Drawing.Graphics + formGraphics = Me.CreateGraphics() + formGraphics.DrawEllipse(myPen, New Rectangle(0, 0, 200, 300)) + myPen.Dispose() + formGraphics.Dispose() + End Sub + + Private Sub DrawRectangle() + Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red) + Dim formGraphics As System.Drawing.Graphics + formGraphics = Me.CreateGraphics() + formGraphics.DrawRectangle(myPen, New Rectangle(0, 0, 200, 300)) + myPen.Dispose() + formGraphics.Dispose() + End Sub + + ' + ' Snippet for: \vbtskcodeexampledrawingtextonform2.xml + ' + Public Sub DrawString() + Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics() + Dim drawString As String = "Sample Text" + Dim drawFont As New System.Drawing.Font("Arial", 16) + Dim drawBrush As New _ + System.Drawing.SolidBrush(System.Drawing.Color.Black) + Dim x As Single = 150.0 + Dim y As Single = 50.0 + Dim drawFormat As New System.Drawing.StringFormat + formGraphics.DrawString(drawString, drawFont, drawBrush, _ + x, y, drawFormat) + drawFont.Dispose() + drawBrush.Dispose() + formGraphics.Dispose() + End Sub + + ' + ' Snippet for: \vbtskcodeexampledrawingtextonform.xml + ' + Public Sub DrawVerticalString() + Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics() + Dim drawString As String = "Sample Text" + Dim drawFont As New System.Drawing.Font("Arial", 16) + Dim drawBrush As New _ + System.Drawing.SolidBrush(System.Drawing.Color.Black) + Dim x As Single = 150.0 + Dim y As Single = 50.0 + Dim drawFormat As New System.Drawing.StringFormat + drawFormat.FormatFlags = StringFormatFlags.DirectionVertical + formGraphics.DrawString(drawString, drawFont, drawBrush, _ + x, y, drawFormat) + drawFont.Dispose() + drawBrush.Dispose() + formGraphics.Dispose() + End Sub + + ' + Private Sub DoSomething9() + Dim myPen As New Pen(Color.Red) + ' Snippet for: \vbtskcodeexamplesetcolorofpen.xml + ' + myPen.Color = System.Drawing.Color.PeachPuff + ' + End Sub + ' Snippet for: \vbtskcreateashapedwindowsform.xml + ' + Protected Overrides Sub OnPaint( _ + ByVal e As System.Windows.Forms.PaintEventArgs) + Dim shape As New System.Drawing.Drawing2D.GraphicsPath + shape.AddEllipse(0, 0, Me.Width, Me.Height) + Me.Region = New System.Drawing.Region(shape) + End Sub + ' + + Public Shared Sub Main() + Application.Run(New Form1) + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb new file mode 100644 index 0000000000..b3c0274e17 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingCurves/VB/Class1.vb @@ -0,0 +1,102 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Drawing2D + +Public Class SystemDrawingConstructingDrawingCurves + +' 37a0bedb-20c2-4cf0-91fa-a5509e826b30 +' How to: Draw a Sequence of Bézier Splines + Private Sub Method11(ByVal e As PaintEventArgs) + + ' + ' Point(10, 100) = start point of first spline + ' Point(75, 10) = first control point of first spline + ' Point(80, 50) = second control point of first spline + + ' Point(100, 150) = endpoint of first spline and start point of second spline + + ' Point(125, 80) = first control point of second spline + ' Point(175, 200) = second control point of second spline + ' Point(200, 80)} = endpoint of second spline + Dim p As Point() = { _ + New Point(10, 100), _ + New Point(75, 10), _ + New Point(80, 50), _ + New Point(100, 150), _ + New Point(125, 80), _ + New Point(175, 200), _ + New Point(200, 80)} + + Dim pen As New Pen(Color.Blue) + e.Graphics.DrawBeziers(pen, p) + + ' + End Sub +' a4a41e80-4461-4b47-b6bd-2c5e68881994 +' How to: Draw Cardinal Splines + Private Sub Method21(ByVal e As PaintEventArgs) + ' + Dim points As Point() = { _ + New Point(0, 100), _ + New Point(50, 80), _ + New Point(100, 20), _ + New Point(150, 80), _ + New Point(200, 100)} + + Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255)) + e.Graphics.DrawCurve(pen, points) + + ' + End Sub + Private Sub Method22(ByVal e As PaintEventArgs) + ' + Dim points As Point() = { _ + New Point(60, 60), _ + New Point(150, 80), _ + New Point(200, 40), _ + New Point(180, 120), _ + New Point(120, 100), _ + New Point(80, 160)} + + Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255)) + e.Graphics.DrawClosedCurve(pen, points) + + ' + End Sub + Private Sub Method23(ByVal e As PaintEventArgs) + ' + Dim points As Point() = { _ + New Point(20, 50), _ + New Point(100, 10), _ + New Point(200, 100), _ + New Point(300, 50), _ + New Point(400, 80)} + + Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255)) + e.Graphics.DrawCurve(pen, points, 0.0F) + e.Graphics.DrawCurve(pen, points, 0.6F) + e.Graphics.DrawCurve(pen, points, 1.0F) + + ' + End Sub +' f4f3fe30-f0a6-4743-ac91-11310cebea9f +' How to: Draw a Single Bézier Spline + Private Sub Method31(ByVal e As PaintEventArgs) + ' + Dim p1 As New Point(10, 100) ' Start point + Dim c1 As New Point(100, 10) ' First control point + Dim c2 As New Point(150, 150) ' Second control point + Dim p2 As New Point(200, 100) ' Endpoint + + Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255)) + e.Graphics.DrawBezier(pen, p1, c1, c2, p2) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/VB/Class1.vb new file mode 100644 index 0000000000..762f6eadd6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ConstructingDrawingPaths/VB/Class1.vb @@ -0,0 +1,68 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Drawing2D + +Public Class SystemDrawingConstructingDrawingPaths + +' 5a36b0e4-f1f4-46c0-a85a-22ae98491950 +' How to: Fill Open Figures + Private Sub Method11(ByVal e As PaintEventArgs) + ' + Dim path As New GraphicsPath() + + ' Add an open figure. + path.AddArc(0, 0, 150, 120, 30, 120) + + ' Add an intrinsically closed figure. + path.AddEllipse(50, 50, 50, 100) + + Dim pen As New Pen(Color.FromArgb(128, 0, 0, 255), 5) + Dim brush As New SolidBrush(Color.Red) + + ' The fill mode is FillMode.Alternate by default. + e.Graphics.FillPath(brush, path) + e.Graphics.DrawPath(pen, path) + + ' + End Sub +' 82fd56c7-b443-4765-9b7c-62ce030656ec +' How to: Create Figures from Lines, Curves, and Shapes + Private Sub Method21(ByVal e As PaintEventArgs) + ' + Dim path As New GraphicsPath() + path.AddArc(175, 50, 50, 50, 0, -180) + e.Graphics.DrawPath(New Pen(Color.FromArgb(128, 255, 0, 0), 4), path) + + ' + End Sub + Private Sub Method22(ByVal e As PaintEventArgs) + ' + ' Create an array of points for the curve in the second figure. + Dim points As Point() = { _ + New Point(40, 60), _ + New Point(50, 70), _ + New Point(30, 90)} + + Dim path As New GraphicsPath() + + path.StartFigure() ' Start the first figure. + path.AddArc(175, 50, 50, 50, 0, -180) + path.AddLine(100, 0, 250, 20) + ' First figure is not closed. + + path.StartFigure() ' Start the second figure. + path.AddLine(50, 20, 5, 90) + path.AddCurve(points, 3) + path.AddLine(50, 150, 150, 180) + path.CloseFigure() ' Second figure is closed. + e.Graphics.DrawPath(New Pen(Color.FromArgb(255, 255, 0, 0), 2), path) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb new file mode 100644 index 0000000000..6a43c75764 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CoordinateSystems/VB/Class1.vb @@ -0,0 +1,128 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Imaging +Imports System.Drawing.Drawing2D + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Dim myPen As Pen = Pens.Black + ' 0659fe00-9e0c-41c4-9118-016f2404c905 + ' Matrix Representation of Transformations + Public Sub Method11() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myMatrix As New Matrix() + myMatrix.Rotate(30) + myMatrix.Scale(1, 2, MatrixOrder.Append) + myMatrix.Translate(5, 0, MatrixOrder.Append) + + ' + End Sub + ' b601d66d-d572-4f11-9d2e-92f0dc8893f3 + ' Global and Local Transformations + Public Sub Method21() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + myGraphics.DrawEllipse(myPen, 0, 0, 100, 50) + myGraphics.ScaleTransform(1, 0.5F) + myGraphics.TranslateTransform(50, 0, MatrixOrder.Append) + myGraphics.RotateTransform(30, MatrixOrder.Append) + myGraphics.DrawEllipse(myPen, 0, 0, 100, 50) + + ' + End Sub + Public Sub Method22() + Dim myGraphics As Graphics = Me.CreateGraphics() + Dim myGraphicsPath As New GraphicsPath() + ' + Dim myMatrix As New Matrix() + myMatrix.Rotate(45) + myGraphicsPath.Transform(myMatrix) + myGraphics.DrawRectangle(myPen, 10, 10, 100, 50) + myGraphics.DrawPath(myPen, myGraphicsPath) + + ' + End Sub + Public Sub Method23() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myMatrix As New Matrix(1, 0, 0, -1, 0, 0) + myGraphics.Transform = myMatrix + myGraphics.TranslateTransform(200, 150, MatrixOrder.Append) + + ' + End Sub + Public Sub Method24() + Dim myGraphics As Graphics = Me.CreateGraphics() + Dim mySolidBrush1 As New SolidBrush(Color.Red) + Dim mySolidBrush2 As New SolidBrush(Color.Black) + + ' + ' Create the path. + Dim myGraphicsPath As New GraphicsPath() + Dim myRectangle As New Rectangle(0, 0, 60, 60) + myGraphicsPath.AddRectangle(myRectangle) + + ' Fill the path on the new coordinate system. + ' No local transformation + myGraphics.FillPath(mySolidBrush1, myGraphicsPath) + + ' Set the local transformation of the GraphicsPath object. + Dim myPathMatrix As New Matrix() + myPathMatrix.Scale(2, 1) + myPathMatrix.Rotate(30, MatrixOrder.Append) + myGraphicsPath.Transform(myPathMatrix) + + ' Fill the transformed path on the new coordinate system. + myGraphics.FillPath(mySolidBrush2, myGraphicsPath) + + ' + End Sub + ' c61ff50a-eb1d-4e6c-83cd-f7e9764cfa9f + ' Types of Coordinate Systems + Public Sub Method31() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + myGraphics.TranslateTransform(100, 50) + myGraphics.DrawLine(myPen, 0, 0, 160, 80) + + ' + End Sub + Public Sub Method32() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + myGraphics.PageUnit = GraphicsUnit.Inch + myGraphics.DrawLine(myPen, 0, 0, 2, 1) + + ' + End Sub + Public Sub Method33() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myPen As New Pen(Color.Black, 1 / myGraphics.DpiX) + + ' + End Sub + Public Sub Method34() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + myGraphics.TranslateTransform(2, 0.5F) + myGraphics.PageUnit = GraphicsUnit.Inch + myGraphics.DrawLine(myPen, 0, 0, 2, 1) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/VB/Form1.vb new file mode 100644 index 0000000000..9ec5b41bb9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.CreateBitmapAtRuntime/VB/Form1.vb @@ -0,0 +1,54 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + + + +Public Class Form1 + Inherits Form + + Public Sub New() + + CreateBitmapAtRuntime() + + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + + End Sub + + + + + ' + Private pictureBox1 As New PictureBox() + + Public Sub CreateBitmapAtRuntime() + pictureBox1.Size = New Size(210, 110) + Me.Controls.Add(pictureBox1) + + + Dim flag As New Bitmap(200, 100) + Dim flagGraphics As Graphics = Graphics.FromImage(flag) + Dim red As Integer = 0 + Dim white As Integer = 11 + While white <= 100 + flagGraphics.FillRectangle(Brushes.Red, 0, red, 200, 10) + flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10) + red += 20 + white += 20 + End While + pictureBox1.Image = flag + + End Sub +' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb new file mode 100644 index 0000000000..4187fda147 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.FontsAndText/VB/Class1.vb @@ -0,0 +1,392 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Text + +Public Class SystemDrawingFontsAndText + +' 26d74ef5-0f39-4eeb-8d20-00e66e014abe +' How to: Enumerate Installed Fonts + Public Sub Method11(ByVal e As PaintEventArgs) + ' + Dim fontFamily As New FontFamily("Arial") + Dim font As New Font( _ + fontFamily, _ + 8, _ + FontStyle.Regular, _ + GraphicsUnit.Point) + Dim rectF As New RectangleF(10, 10, 500, 500) + Dim solidBrush As New SolidBrush(Color.Black) + + Dim familyName As String + Dim familyList As String = "" + Dim fontFamilies() As FontFamily + + Dim installedFontCollection As New InstalledFontCollection() + + ' Get the array of FontFamily objects. + fontFamilies = installedFontCollection.Families + + ' The loop below creates a large string that is a comma-separated + ' list of all font family names. + Dim count As Integer = fontFamilies.Length + Dim j As Integer + + While j < count + familyName = fontFamilies(j).Name + familyList = familyList & familyName + familyList = familyList & ", " + j += 1 + End While + + ' Draw the large string (list of all families) in a rectangle. + e.Graphics.DrawString(familyList, font, solidBrush, rectF) + + ' + End Sub +' 48fc34f3-f236-4b01-a0cb-f0752e6d22ae +' How to: Use Antialiasing with Text + Public Sub Method21(ByVal e As PaintEventArgs) + ' + Dim fontFamily As New FontFamily("Times New Roman") + Dim font As New Font( _ + fontFamily, _ + 32, _ + FontStyle.Regular, _ + GraphicsUnit.Pixel) + Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255)) + Dim string1 As String = "SingleBitPerPixel" + Dim string2 As String = "AntiAlias" + + e.Graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel + e.Graphics.DrawString(string1, font, solidBrush, New PointF(10, 10)) + + e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias + e.Graphics.DrawString(string2, font, solidBrush, New PointF(10, 60)) + + ' + End Sub +' 50c69046-4188-47d9-b949-cc2610ffd337 +' How to: Create Vertical Text + Public Sub Method31(ByVal e As PaintEventArgs) + ' + Dim myText As String = "Vertical text" + + Dim fontFamily As New FontFamily("Lucida Console") + Dim font As New Font( _ + fontFamily, _ + 14, _ + FontStyle.Regular, _ + GraphicsUnit.Point) + Dim pointF As New PointF(40, 10) + Dim stringFormat As New StringFormat() + Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255)) + + stringFormat.FormatFlags = StringFormatFlags.DirectionVertical + + e.Graphics.DrawString(myText, font, solidBrush, pointF, stringFormat) + + ' + End Sub +' 64878f98-39ba-4303-b63f-0859ab682eeb +' How to: Set Tab Stops in Drawn Text + Public Sub Method41(ByVal e As PaintEventArgs) + ' + Dim myText As String = _ + "Name" & ControlChars.Tab & _ + "Test 1" & ControlChars.Tab & _ + "Test 2" & ControlChars.Tab & _ + "Test 3" & ControlChars.Cr + + myText = myText & "Joe" & ControlChars.Tab & _ + "95" & ControlChars.Tab & _ + "88" & ControlChars.Tab & _ + "91" & ControlChars.Cr + myText = myText & "Mary" & ControlChars.Tab & _ + "98" & ControlChars.Tab & _ + "84" & ControlChars.Tab & _ + "90" & ControlChars.Cr + myText = myText & "Sam" & ControlChars.Tab & _ + "42" & ControlChars.Tab & _ + "76" & ControlChars.Tab & _ + "98" & ControlChars.Cr + myText = myText & "Jane" & ControlChars.Tab & _ + "65" & ControlChars.Tab & _ + "73" & ControlChars.Tab & _ + "92" & ControlChars.Cr + + Dim fontFamily As New FontFamily("Courier New") + Dim font As New Font( _ + fontFamily, _ + 12, _ + FontStyle.Regular, _ + GraphicsUnit.Point) + Dim rect As New Rectangle(10, 10, 450, 100) + Dim stringFormat As New StringFormat() + Dim solidBrush As New SolidBrush(Color.FromArgb(255, 0, 0, 255)) + Dim tabs As Single() = {150, 100, 100, 100} + + stringFormat.SetTabStops(0, tabs) + + e.Graphics.DrawString(myText, font, solidBrush, RectangleF.op_implicit(rect), stringFormat) + + Dim pen As Pen = Pens.Black + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub +' 6533d5e5-a8dc-4b76-9fc4-3bf75c8b9212 +' How to: Create a Private Font Collection + Public Sub Method51(ByVal e As PaintEventArgs) + ' + Dim pointF As New PointF(10, 0) + Dim solidBrush As New SolidBrush(Color.Black) + + Dim count As Integer = 0 + Dim familyName As String = "" + Dim familyNameAndStyle As String + Dim fontFamilies() As FontFamily + Dim privateFontCollection As New PrivateFontCollection() + + ' Add three font files to the private collection. + privateFontCollection.AddFontFile("D:\systemroot\Fonts\Arial.ttf") + privateFontCollection.AddFontFile("D:\systemroot\Fonts\CourBI.ttf") + privateFontCollection.AddFontFile("D:\systemroot\Fonts\TimesBD.ttf") + + ' Get the array of FontFamily objects. + fontFamilies = privateFontCollection.Families + + ' How many objects in the fontFamilies array? + count = fontFamilies.Length + + ' Display the name of each font family in the private collection + ' along with the available styles for that font family. + Dim j As Integer + + While j < count + ' Get the font family name. + familyName = fontFamilies(j).Name + + ' Is the regular style available? + If fontFamilies(j).IsStyleAvailable(FontStyle.Regular) Then + familyNameAndStyle = "" + familyNameAndStyle = familyNameAndStyle & familyName + familyNameAndStyle = familyNameAndStyle & " Regular" + + Dim regFont As New Font( _ + familyName, _ + 16, _ + FontStyle.Regular, _ + GraphicsUnit.Pixel) + + e.Graphics.DrawString( _ + familyNameAndStyle, _ + regFont, _ + solidBrush, _ + pointF) + + pointF.Y += regFont.Height + End If + + ' Is the bold style available? + If fontFamilies(j).IsStyleAvailable(FontStyle.Bold) Then + familyNameAndStyle = "" + familyNameAndStyle = familyNameAndStyle & familyName + familyNameAndStyle = familyNameAndStyle & " Bold" + + Dim boldFont As New Font( _ + familyName, _ + 16, _ + FontStyle.Bold, _ + GraphicsUnit.Pixel) + + e.Graphics.DrawString( _ + familyNameAndStyle, _ + boldFont, _ + solidBrush, _ + pointF) + + pointF.Y += boldFont.Height + End If + + ' Is the italic style available? + If fontFamilies(j).IsStyleAvailable(FontStyle.Italic) Then + familyNameAndStyle = "" + familyNameAndStyle = familyNameAndStyle & familyName + familyNameAndStyle = familyNameAndStyle & " Italic" + + Dim italicFont As New Font( _ + familyName, _ + 16, _ + FontStyle.Italic, _ + GraphicsUnit.Pixel) + + e.Graphics.DrawString( _ + familyNameAndStyle, _ + italicFont, _ + solidBrush, pointF) + + pointF.Y += italicFont.Height + End If + + ' Is the bold italic style available? + If fontFamilies(j).IsStyleAvailable(FontStyle.Italic) And _ + fontFamilies(j).IsStyleAvailable(FontStyle.Bold) Then + familyNameAndStyle = "" + familyNameAndStyle = familyNameAndStyle & familyName + familyNameAndStyle = familyNameAndStyle & "BoldItalic" + + Dim italicFont As New Font( _ + familyName, _ + 16, _ + FontStyle.Italic Or FontStyle.Bold, _ + GraphicsUnit.Pixel) + + e.Graphics.DrawString( _ + familyNameAndStyle, _ + italicFont, _ + solidBrush, _ + pointF) + + pointF.Y += italicFont.Height + End If + ' Is the underline style available? + If fontFamilies(j).IsStyleAvailable(FontStyle.Underline) Then + familyNameAndStyle = "" + familyNameAndStyle = familyNameAndStyle & familyName + familyNameAndStyle = familyNameAndStyle & " Underline" + + Dim underlineFont As New Font( _ + familyName, _ + 16, _ + FontStyle.Underline, _ + GraphicsUnit.Pixel) + + e.Graphics.DrawString( _ + familyNameAndStyle, _ + underlineFont, _ + solidBrush, _ + pointF) + + pointF.Y += underlineFont.Height + End If + + ' Is the strikeout style available? + If fontFamilies(j).IsStyleAvailable(FontStyle.Strikeout) Then + familyNameAndStyle = "" + familyNameAndStyle = familyNameAndStyle & familyName + familyNameAndStyle = familyNameAndStyle & " Strikeout" + + Dim strikeFont As New Font( _ + familyName, _ + 16, _ + FontStyle.Strikeout, _ + GraphicsUnit.Pixel) + + e.Graphics.DrawString( _ + familyNameAndStyle, _ + strikeFont, _ + solidBrush, _ + pointF) + + pointF.Y += strikeFont.Height + End If + + ' Separate the families with white space. + pointF.Y += 10 + End While + + ' + End Sub + ' d3a4a223-9492-4b54-9afd-db1c31c3cefd + ' How to: Construct Font Families and Fonts + Public Sub Method61(ByVal e As PaintEventArgs) + ' + Dim fontFamily As New FontFamily("Arial") + Dim font As New Font( _ + fontFamily, _ + 16, _ + FontStyle.Regular, _ + GraphicsUnit.Pixel) + + ' + End Sub + ' ff7c0616-67f7-4fa2-84ee-b8d642f2b09b + ' How to: Obtain Font Metrics + Public Sub Method71(ByVal e As PaintEventArgs) + ' + Dim infoString As String = "" ' enough space for one line of output + Dim ascent As Integer ' font family ascent in design units + Dim ascentPixel As Single ' ascent converted to pixels + Dim descent As Integer ' font family descent in design units + Dim descentPixel As Single ' descent converted to pixels + Dim lineSpacing As Integer ' font family line spacing in design units + Dim lineSpacingPixel As Single ' line spacing converted to pixels + Dim fontFamily As New FontFamily("Arial") + Dim font As New Font( _ + fontFamily, _ + 16, _ + FontStyle.Regular, _ + GraphicsUnit.Pixel) + Dim pointF As New PointF(10, 10) + Dim solidBrush As New SolidBrush(Color.Black) + + ' Display the font size in pixels. + infoString = "font.Size returns " & font.Size.ToString() & "." + e.Graphics.DrawString(infoString, font, solidBrush, pointF) + + ' Move down one line. + pointF.Y += font.Height + + ' Display the font family em height in design units. + infoString = "fontFamily.GetEmHeight() returns " & _ + fontFamily.GetEmHeight(FontStyle.Regular) & "." + e.Graphics.DrawString(infoString, font, solidBrush, pointF) + + ' Move down two lines. + pointF.Y += 2 * font.Height + + ' Display the ascent in design units and pixels. + ascent = fontFamily.GetCellAscent(FontStyle.Regular) + + ' 14.484375 = 16.0 * 1854 / 2048 + ascentPixel = _ + font.Size * ascent / fontFamily.GetEmHeight(FontStyle.Regular) + infoString = "The ascent is " & ascent & " design units, " & ascentPixel _ + & " pixels." + e.Graphics.DrawString(infoString, font, solidBrush, pointF) + + ' Move down one line. + pointF.Y += font.Height + + ' Display the descent in design units and pixels. + descent = fontFamily.GetCellDescent(FontStyle.Regular) + + ' 3.390625 = 16.0 * 434 / 2048 + descentPixel = _ + font.Size * descent / fontFamily.GetEmHeight(FontStyle.Regular) + infoString = "The descent is " & descent & " design units, " & _ + descentPixel & " pixels." + e.Graphics.DrawString(infoString, font, solidBrush, pointF) + + ' Move down one line. + pointF.Y += font.Height + + ' Display the line spacing in design units and pixels. + lineSpacing = fontFamily.GetLineSpacing(FontStyle.Regular) + + ' 18.398438 = 16.0 * 2355 / 2048 + lineSpacingPixel = _ + font.Size * lineSpacing / fontFamily.GetEmHeight(FontStyle.Regular) + infoString = "The line spacing is " & lineSpacing & " design units, " & _ + lineSpacingPixel & " pixels." + e.Graphics.DrawString(infoString, font, solidBrush, pointF) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/VB/Form1.vb new file mode 100644 index 0000000000..3004f3c0d3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Graphics.CopyFromScreen/VB/Form1.vb @@ -0,0 +1,42 @@ +' +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Drawing.Printing + +Public Class Form1 + Inherits Form + Private WithEvents printButton As New Button + Private WithEvents printDocument1 As New PrintDocument + + Public Sub New() + printButton.Text = "Print Form" + Me.Controls.Add(printButton) + End Sub + + Dim memoryImage As Bitmap + + Private Sub CaptureScreen() + Dim myGraphics As Graphics = Me.CreateGraphics() + Dim s As Size = Me.Size + memoryImage = New Bitmap(s.Width, s.Height, myGraphics) + Dim memoryGraphics As Graphics = Graphics.FromImage(memoryImage) + memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s) + End Sub + + Private Sub printDocument1_PrintPage(ByVal sender As System.Object, _ + ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _ + printDocument1.PrintPage + e.Graphics.DrawImage(memoryImage, 0, 0) + End Sub + + Private Sub printButton_Click(ByVal sender As System.Object, ByVal e As _ + System.EventArgs) Handles printButton.Click + CaptureScreen() + printDocument1.Print() + End Sub + + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/VB/Form1.vb new file mode 100644 index 0000000000..9b82830e71 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Icon.ExtractAssociatedIconEx/VB/Form1.vb @@ -0,0 +1,65 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms +Imports System.IO + + + +Public Class Form1 + Inherits Form + + Public Sub New() + ExtractAssociatedIconEx() + + End Sub + ' + Private listView1 As ListView + Private imageList1 As ImageList + + + Public Sub ExtractAssociatedIconEx() + + ' Initialize the ListView, ImageList and Form. + listView1 = New ListView() + imageList1 = New ImageList() + listView1.Location = New Point(37, 12) + listView1.Size = New Size(161, 242) + listView1.SmallImageList = imageList1 + listView1.View = View.SmallIcon + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(Me.listView1) + Me.Text = "Form1" + + ' Get the c:\ directory. + Dim dir As New System.IO.DirectoryInfo("c:\") + + Dim item As ListViewItem + listView1.BeginUpdate() + Dim file As System.IO.FileInfo + For Each file In dir.GetFiles() + + ' Set a default icon for the file. + Dim iconForFile As Icon = SystemIcons.WinLogo + + item = New ListViewItem(file.Name, 1) + + ' Check to see if the image collection contains an image + ' for this extension, using the extension as a key. + If Not (imageList1.Images.ContainsKey(file.Extension)) Then + + ' If not, add the image to the image list. + iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName) + imageList1.Images.Add(file.Extension, iconForFile) + End If + item.ImageKey = file.Extension + listView1.Items.Add(item) + + Next file + listView1.EndUpdate() + End Sub + ' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb new file mode 100644 index 0000000000..b3a1532c4b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.ImagesBitmapsMetafiles/VB/Class1.vb @@ -0,0 +1,118 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Imaging + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + ' 09f0c07a-19c0-43b4-90a2-862a10545ce8 + ' Drawing, Positioning, and Cloning Images in GDI+ + Public Sub Method11() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myBitmap As New Bitmap("Climber.jpg") + myGraphics.DrawImage(myBitmap, 10, 10) + + ' + End Sub + Public Sub Method12() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myBMP As New Bitmap("SpaceCadet.bmp") + Dim myGIF As New Bitmap("Soda.gif") + Dim myJPEG As New Bitmap("Mango.jpg") + Dim myPNG As New Bitmap("Flowers.png") + Dim myTIFF As New Bitmap("MS.tif") + + myGraphics.DrawImage(myBMP, 10, 10) + myGraphics.DrawImage(myGIF, 220, 10) + myGraphics.DrawImage(myJPEG, 280, 10) + myGraphics.DrawImage(myPNG, 150, 200) + myGraphics.DrawImage(myTIFF, 300, 200) + + ' + End Sub + Public Sub Method13() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim originalBitmap As New Bitmap("Spiral.png") + Dim sourceRectangle As New Rectangle(0, 0, originalBitmap.Width, _ + CType(originalBitmap.Height / 2, Integer)) + + Dim secondBitmap As Bitmap = originalBitmap.Clone(sourceRectangle, _ + PixelFormat.DontCare) + + myGraphics.DrawImage(originalBitmap, 10, 10) + myGraphics.DrawImage(secondBitmap, 150, 10) + + ' + End Sub + ' 51da872c-c783-440f-8bf6-1e580a966c31 + ' Metafiles in GDI+ + ' + Public Sub Example_DisplayMetafile(ByVal e As PaintEventArgs) + Dim myGraphics As Graphics = e.Graphics + Dim myMetafile As New Metafile("SampleMetafile.emf") + myGraphics.DrawImage(myMetafile, 100, 100) + End Sub + + ' + ' ad5daf26-005f-45bc-a2af-e0e97777a21a + ' Cropping and Scaling Images in GDI+ + Public Sub Method31() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myBitmap As New Bitmap("Spiral.png") + + Dim expansionRectangle As New Rectangle(135, 10, _ + myBitmap.Width, myBitmap.Height) + + Dim compressionRectangle As New Rectangle(300, 10, _ + CType(myBitmap.Width / 2, Integer), CType(myBitmap.Height / 2, Integer)) + + myGraphics.DrawImage(myBitmap, 10, 10) + myGraphics.DrawImage(myBitmap, expansionRectangle) + myGraphics.DrawImage(myBitmap, compressionRectangle) + + ' + End Sub + Public Sub Method32() + Dim myGraphics As Graphics = Me.CreateGraphics() + ' + Dim myBitmap As New Bitmap("Runner.jpg") + + ' One hand of the runner + Dim sourceRectangle As New Rectangle(80, 70, 80, 45) + + ' Compressed hand + Dim destRectangle1 As New Rectangle(200, 10, 20, 16) + + ' Expanded hand + Dim destRectangle2 As New Rectangle(200, 40, 200, 160) + + ' Draw the original image at (0, 0). + myGraphics.DrawImage(myBitmap, 0, 0) + + ' Draw the compressed hand. + myGraphics.DrawImage( _ + myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel) + + ' Draw the expanded hand. + myGraphics.DrawImage( _ + myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Misc3/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Misc3/VB/Form1.vb new file mode 100644 index 0000000000..c5b54dec49 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Misc3/VB/Form1.vb @@ -0,0 +1,288 @@ + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Drawing.Imaging +Imports System.ComponentModel +Imports System.Drawing.Text + + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Public Sub New() + 'This call is required by the Windows Form Designer. + InitializeComponent() + ExtractAssociatedIconEx() + End Sub + + '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.ClientSize = New System.Drawing.Size(292, 266) + + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + ' + Protected Sub DrawCaps(ByVal e As PaintEventArgs) + Dim hPath As New GraphicsPath() + + ' Create the outline for our custom end cap. + hPath.AddLine(New Point(0, 0), New Point(0, 5)) + hPath.AddLine(New Point(0, 5), New Point(5, 1)) + hPath.AddLine(New Point(5, 1), New Point(3, 1)) + + ' Construct the hook-shaped end cap. + Dim HookCap As New CustomLineCap(Nothing, hPath) + + ' Set the start cap and end cap of the HookCap to be rounded. + HookCap.SetStrokeCaps(LineCap.Round, LineCap.Round) + + ' Create a pen and set end custom start and end + ' caps to the hook cap. + Dim customCapPen As New Pen(Color.Black, 5) + customCapPen.CustomStartCap = HookCap + customCapPen.CustomEndCap = HookCap + + ' Create a second pen using the start and end caps from + ' the hook cap. + Dim capPen As New Pen(Color.Red, 10) + Dim startCap As LineCap + Dim endCap As LineCap + HookCap.GetStrokeCaps(startCap, endCap) + capPen.StartCap = startCap + capPen.EndCap = endCap + + ' Create a line to draw. + Dim points As Point() = {New Point(100, 100), New Point(200, 50), _ + New Point(250, 300)} + + ' Draw the lines. + e.Graphics.DrawLines(capPen, points) + e.Graphics.DrawLines(customCapPen, points) + + End Sub + ' + + ' + Private Sub ExtractAssociatedIconEx() + Dim ico As Icon = Icon.ExtractAssociatedIcon("C:\WINDOWS\system32\notepad.exe") + Me.Icon = ico + + End Sub + ' + + ' + Private Sub ConstructAnIconFromAType(ByVal e As PaintEventArgs) + + Dim icon1 As New Icon(GetType(Control), "Error.ico") + e.Graphics.DrawIcon(icon1, New Rectangle(10, 10, 50, 50)) + + End Sub + ' + + ' + Private Sub ShowOutputChannels(ByVal e As PaintEventArgs) + + 'Create a bitmap from a file. + Dim bmp1 As New Bitmap("c:\fakePhoto.jpg") + + ' Create a new bitmap from the original, resizing it for this example. + Dim bmp2 As New Bitmap(bmp1, New Size(80, 80)) + + bmp1.Dispose() + + ' Create an ImageAttributes object. + Dim imgAttributes As New System.Drawing.Imaging.ImageAttributes() + + ' Draw the image unaltered. + e.Graphics.DrawImage(bmp2, 10, 10) + + ' Draw the image, showing the intensity of the cyan channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelC, ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(bmp2, New Rectangle(100, 10, bmp2.Width, bmp2.Height), _ + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes) + + ' Draw the image, showing the intensity of the magenta channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelM, ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(bmp2, New Rectangle(10, 100, bmp2.Width, bmp2.Height), _ + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes) + + ' Draw the image, showing the intensity of the yellow channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelY, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(bmp2, New Rectangle(100, 100, bmp2.Width, bmp2.Height), _ + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes) + + ' Draw the image, showing the intensity of the black channel. + imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelK, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(bmp2, New Rectangle(10, 190, bmp2.Width, bmp2.Height), _ + 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes) + + 'Dispose of the bitmap. + bmp2.Dispose() + + End Sub + + ' + +' + Private Sub OpAdditionExample(ByVal e As PaintEventArgs) + Dim size1 As New SizeF(120.5F, 30.5F) + Dim point1 As New PointF(20.5F, 20F) + Dim rect1 As New RectangleF(point1, size1) + If New PointF(rect1.Right, rect1.Bottom) = point1 + size1 Then + e.Graphics.DrawString("They are equal", Me.Font, Brushes.Black, rect1) + Else + e.Graphics.DrawString("They are not equal", Me.Font, Brushes.Red, rect1) + End If + + End Sub + ' + + ' + Private Sub AddExample(ByVal e As PaintEventArgs) + Dim size1 As New SizeF(120.5F, 30.5F) + Dim point1 As New PointF(20.5F, 20F) + Dim rect1 As New RectangleF(point1, size1) + Dim point2 As New PointF(rect1.Right, rect1.Bottom) + If point2 <> PointF.Add(point1, size1) Then + e.Graphics.DrawString("They are not equal", Me.Font, Brushes.Red, rect1) + Else + e.Graphics.DrawString("They are equal", Me.Font, Brushes.Black, rect1) + End If + + End Sub + ' + + ' + Private Sub SubtractExample(ByVal e As PaintEventArgs) + Dim point1 As New PointF(120.5F, 120F) + Dim size1 As New SizeF(120.5F, 30.5F) + Dim point2 As PointF = PointF.Subtract(point1, size1) + e.Graphics.DrawLine(Pens.Blue, point1, point2) + + End Sub + ' + + ' + Private Sub OpSubtractionExample(ByVal e As PaintEventArgs) + Dim point1 As New PointF(120.5F, 120F) + Dim size1 As New SizeF(120.5F, 30.5F) + Dim point2 As PointF = point1 - size1 + e.Graphics.DrawLine(Pens.Blue, point1, point2) + + End Sub + ' + + Private Sub ShearColors(ByVal e As PaintEventArgs) + ' + Dim image = New Bitmap("ColorBars.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + + Dim colorMatrixElements As Single()() = _ + {New Single() {1, 0, 0, 0, 0}, _ + New Single() {0, 1, 0, 0, 0}, _ + New Single() {0.5F, 0, 1, 0, 0}, _ + New Single() {0, 0, 0, 1, 0}, _ + New Single() {0, 0, 0, 0, 1}} + + Dim colorMatrix As New ColorMatrix(colorMatrixElements) + + imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10, width, height) + + e.Graphics.DrawImage(image, New Rectangle(150, 10, width, height), 0, 0, _ + width, height, GraphicsUnit.Pixel, imageAttributes) + ' + End Sub + + ' + Private ifc As New InstalledFontCollection() + + Private Sub EnumerateInstalledFonts(ByVal e As PaintEventArgs) + Dim families As FontFamily() = ifc.Families + Dim x As Single = 0.0F + Dim y As Single = 0.0F + For i As Integer = 0 To ifc.Families.Length - 1 + If ifc.Families(i).IsStyleAvailable(FontStyle.Regular) Then + e.Graphics.DrawString(ifc.Families(i).Name, New Font(ifc.Families(i), 12), _ + Brushes.Black, x, y) + y += 20 + If y Mod 700 = 0 Then + x += 140 + y = 0 + End If + End If + Next + End Sub + ' + + ' + Private Sub ConstructFontWithString(ByVal e As PaintEventArgs) + Dim font1 As New Font("Arial", 20) + e.Graphics.DrawString("Arial Font", font1, Brushes.Red, New PointF(10, 10)) + End Sub + ' + + Private Shared Function ResizeImage(ByVal image As System.Drawing.Image) As Bitmap + ' + Dim bitmap As New Bitmap(100, 100) + bitmap.SetResolution(96F, 96F) + ' + + Using graphics__1 As Graphics = Graphics.FromImage(bitmap) + graphics__1.DrawImage(image, New Rectangle(0, 0, 100, 100), New Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel) + End Using + + Return bitmap + End Function + ' + + Public Function ThumbnailCallback() As Boolean + Return False + End Function + + Public Sub Example_GetThumb(ByVal e As PaintEventArgs) + Dim myCallback As New Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback) + Dim myBitmap As New Bitmap("Climber.jpg") + Dim myThumbnail As Image = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero) + e.Graphics.DrawImage(myThumbnail, 150, 75) + End Sub + +' + + Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint + DrawCaps(e) + 'ConstructAnIconFromAType(e); + ShowOutputChannels(e) + + End Sub +End Class + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb new file mode 100644 index 0000000000..712f9d482d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.MiscLegacyTopics/VB/Class1.vb @@ -0,0 +1,258 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Imaging +Imports System.Drawing.Drawing2D + +Public Class SystemDrawingMiscLegacyTopics + + ' 1e717711-1361-448e-aa49-0f3ec43110c9 + ' Using the World Transformation + Private Sub Method11(ByVal e As PaintEventArgs) + + ' + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + Private Sub Method12(ByVal e As PaintEventArgs) + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + ' + e.Graphics.ScaleTransform(1.75F, 0.5F) + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + Private Sub Method13(ByVal e As PaintEventArgs) + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + ' + e.Graphics.ResetTransform() + e.Graphics.RotateTransform(28) ' 28 degrees + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + Private Sub Method14(ByVal e As PaintEventArgs) + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + ' + e.Graphics.ResetTransform() + e.Graphics.TranslateTransform(150, 150) + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + ' 37d5f9dc-a5cf-4475-aa5d-34d714e808a9 + ' Why Transformation Order Is Significant + Private Sub Method21(ByVal e As PaintEventArgs) + ' + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + e.Graphics.ResetTransform() + e.Graphics.ScaleTransform(1.75F, 0.5F) + e.Graphics.RotateTransform(28, MatrixOrder.Append) + e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append) + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + Private Sub Method22(ByVal e As PaintEventArgs) + ' + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + e.Graphics.ResetTransform() + e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append) + e.Graphics.RotateTransform(28, MatrixOrder.Append) + e.Graphics.ScaleTransform(1.75F, 0.5F) + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + Private Sub Method23(ByVal e As PaintEventArgs) + ' + Dim rect As New Rectangle(0, 0, 50, 50) + Dim pen As New Pen(Color.FromArgb(128, 200, 0, 200), 2) + e.Graphics.ResetTransform() + e.Graphics.TranslateTransform(150, 150, MatrixOrder.Prepend) + e.Graphics.RotateTransform(28, MatrixOrder.Prepend) + e.Graphics.ScaleTransform(1.75F, 0.5F) + e.Graphics.DrawRectangle(pen, rect) + + ' + End Sub + ' 3a4c07cb-a40a-4d14-ad35-008f531910a8 + ' How to: Use Hit Testing with a Region + Private Sub Method31(ByVal e As PaintEventArgs) + ' + Dim point As New Point(60, 10) + + ' Assume that the variable "point" contains the location of the + ' most recent mouse click. + ' To simulate a hit, assign (60, 10) to point. + ' To simulate a miss, assign (0, 0) to point. + + Dim solidBrush As New SolidBrush(Color.Black) + Dim region1 As New [Region](New Rectangle(50, 0, 50, 150)) + Dim region2 As New [Region](New Rectangle(0, 50, 150, 50)) + + ' Create a plus-shaped region by forming the union of region1 and region2. + ' The union replaces region1. + region1.Union(region2) + + If region1.IsVisible(point, e.Graphics) Then + ' The point is in the region. Use an opaque brush. + solidBrush.Color = Color.FromArgb(255, 255, 0, 0) + Else + ' The point is not in the region. Use a semitransparent brush. + solidBrush.Color = Color.FromArgb(64, 255, 0, 0) + End If + + e.Graphics.FillRegion(solidBrush, region1) + + ' + End Sub + ' 43d121b4-e14c-4901-b25c-2d6c25ba4e29 + ' How to: Use Clipping with a Region + Private Sub Method41(ByVal e As PaintEventArgs) + ' + ' Create a path that consists of a single polygon. + Dim polyPoints As Point() = { _ + New Point(10, 10), _ + New Point(150, 10), _ + New Point(100, 75), _ + New Point(100, 150)} + Dim path As New GraphicsPath() + path.AddPolygon(polyPoints) + + ' Construct a region based on the path. + Dim [region] As New [Region](path) + + ' Draw the outline of the region. + Dim pen As Pen = Pens.Black + e.Graphics.DrawPath(pen, path) + + ' Set the clipping region of the Graphics object. + e.Graphics.SetClip([region], CombineMode.Replace) + + ' Draw some clipped strings. + Dim fontFamily As New FontFamily("Arial") + Dim font As New Font( _ + fontFamily, _ + 36, _ + FontStyle.Bold, _ + GraphicsUnit.Pixel) + Dim solidBrush As New SolidBrush(Color.FromArgb(255, 255, 0, 0)) + + e.Graphics.DrawString( _ + "A Clipping Region", _ + font, _ + solidBrush, _ + New PointF(15, 25)) + + e.Graphics.DrawString( _ + "A Clipping Region", _ + font, _ + solidBrush, _ + New PointF(15, 68)) + + ' + End Sub + + ' a0d9f178-43a4-4323-bb5a-d3e3f77ae6c1 + ' Using Nested Graphics Containers + Private Sub Method61(ByVal e As PaintEventArgs) + ' + Dim graphics As Graphics = e.Graphics + Dim pen As New Pen(Color.Red) + Dim graphicsContainer As GraphicsContainer + graphics.FillRectangle(Brushes.Black, 100, 80, 3, 3) + + graphics.TranslateTransform(100, 80) + + graphicsContainer = graphics.BeginContainer() + graphics.RotateTransform(30) + graphics.DrawRectangle(pen, -60, -30, 120, 60) + graphics.EndContainer(graphicsContainer) + + graphics.DrawRectangle(pen, -60, -30, 120, 60) + + ' + End Sub + Private Sub Method62(ByVal e As PaintEventArgs) + ' + Dim graphics As Graphics = e.Graphics + Dim graphicsContainer As GraphicsContainer + Dim redPen As New Pen(Color.Red, 2) + Dim bluePen As New Pen(Color.Blue, 2) + Dim aquaBrush As New SolidBrush(Color.FromArgb(255, 180, 255, 255)) + Dim greenBrush As New SolidBrush(Color.FromArgb(255, 150, 250, 130)) + + graphics.SetClip(New Rectangle(50, 65, 150, 120)) + graphics.FillRectangle(aquaBrush, 50, 65, 150, 120) + + graphicsContainer = graphics.BeginContainer() + ' Create a path that consists of a single ellipse. + Dim path As New GraphicsPath() + path.AddEllipse(75, 50, 100, 150) + + ' Construct a region based on the path. + Dim [region] As New [Region](path) + graphics.FillRegion(greenBrush, [region]) + + graphics.SetClip([region], CombineMode.Replace) + graphics.DrawLine(redPen, 50, 0, 350, 300) + graphics.EndContainer(graphicsContainer) + + graphics.DrawLine(bluePen, 70, 0, 370, 300) + + ' + End Sub + Private Sub Method63(ByVal e As PaintEventArgs) + ' + Dim graphics As Graphics = e.Graphics + Dim innerContainer As GraphicsContainer + Dim outerContainer As GraphicsContainer + Dim brush As New SolidBrush(Color.Blue) + Dim fontFamily As New FontFamily("Times New Roman") + Dim font As New Font( _ + fontFamily, _ + 36, _ + FontStyle.Regular, _ + GraphicsUnit.Pixel) + + graphics.TextRenderingHint = _ + System.Drawing.Text.TextRenderingHint.AntiAlias + + outerContainer = graphics.BeginContainer() + + graphics.TextRenderingHint = _ + System.Drawing.Text.TextRenderingHint.SingleBitPerPixel + + innerContainer = graphics.BeginContainer() + graphics.TextRenderingHint = _ + System.Drawing.Text.TextRenderingHint.AntiAlias + graphics.DrawString( _ + "Inner Container", _ + font, _ + brush, _ + New PointF(20, 10)) + graphics.EndContainer(innerContainer) + + graphics.DrawString("Outer Container", font, brush, New PointF(20, 50)) + + graphics.EndContainer(outerContainer) + + graphics.DrawString("Graphics Object", font, brush, New PointF(20, 90)) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb new file mode 100644 index 0000000000..d1bec66b57 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintExamples/VB/Form1.vb @@ -0,0 +1,83 @@ + ' +Imports System.Drawing +Imports System.IO +Imports System.Drawing.Printing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + Private printButton As Button + + ' + Private printDocument1 As New PrintDocument() + Private stringToPrint As String + ' + + Public Sub New() + Me.printButton = New System.Windows.Forms.Button() + Me.printButton.Location = New System.Drawing.Point(12, 51) + Me.printButton.Size = New System.Drawing.Size(75, 23) + Me.printButton.Text = "Print" + Me.ClientSize = New System.Drawing.Size(292, 266) + End Sub + + Private Sub ReadFile() + ' + Dim docName As String = "testPage.txt" + Dim docPath As String = "c:\" + printDocument1.DocumentName = docName + Dim stream As New FileStream(docPath + docName, FileMode.Open) + Try + Dim reader As New StreamReader(stream) + Try + stringToPrint = reader.ReadToEnd() + Finally + reader.Dispose() + End Try + Finally + stream.Dispose() + End Try + ' + End Sub + + ' + Private Sub printDocument1_PrintPage(ByVal sender As Object, _ + ByVal e As PrintPageEventArgs) + + Dim charactersOnPage As Integer = 0 + Dim linesPerPage As Integer = 0 + + ' Sets the value of charactersOnPage to the number of characters + ' of stringToPrint that will fit within the bounds of the page. + e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _ + StringFormat.GenericTypographic, charactersOnPage, linesPerPage) + + ' Draws the string within the bounds of the page + e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _ + e.MarginBounds, StringFormat.GenericTypographic) + + ' Remove the portion of the string that has been printed. + stringToPrint = stringToPrint.Substring(charactersOnPage) + + ' Check to see if more pages are to be printed. + e.HasMorePages = stringToPrint.Length > 0 + + End Sub + ' + + Private Sub printButton_Click(ByVal sender As Object, ByVal e As EventArgs) + ReadFile() + ' + printDocument1.Print() + ' + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb new file mode 100644 index 0000000000..c003bc5b29 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.Printing.PrintPreviewExample/VB/Form1.vb @@ -0,0 +1,107 @@ + ' +Imports System.Drawing +Imports System.IO +Imports System.Drawing.Printing +Imports System.Windows.Forms + + + +Class Form1 + Inherits Form + + Private WithEvents printPreviewButton As Button + + ' + Private printPreviewDialog1 As New PrintPreviewDialog() + Private WithEvents printDocument1 As New PrintDocument() + + ' Declare a string to hold the entire document contents. + Private documentContents As String + + ' Declare a variable to hold the portion of the document that + ' is not printed. + Private stringToPrint As String + ' + + Public Sub New() + Me.printPreviewButton = New System.Windows.Forms.Button() + Me.printPreviewButton.Location = New System.Drawing.Point(12, 12) + Me.printPreviewButton.Size = New System.Drawing.Size(125, 23) + Me.printPreviewButton.Text = "Print Preview" + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(Me.printPreviewButton) + + End Sub + + ' + Private Sub ReadDocument() + Dim docName As String = "testPage.txt" + Dim docPath As String = "c:\" + printDocument1.DocumentName = docName + Dim stream As New FileStream(docPath + docName, FileMode.Open) + Try + Dim reader As New StreamReader(stream) + Try + documentContents = reader.ReadToEnd() + Finally + reader.Dispose() + End Try + Finally + stream.Dispose() + End Try + stringToPrint = documentContents + + End Sub + ' + + ' + Sub printDocument1_PrintPage(ByVal sender As Object, _ + ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage + + Dim charactersOnPage As Integer = 0 + Dim linesPerPage As Integer = 0 + + ' Sets the value of charactersOnPage to the number of characters + ' of stringToPrint that will fit within the bounds of the page. + e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _ + StringFormat.GenericTypographic, charactersOnPage, linesPerPage) + + ' Draws the string within the bounds of the page. + e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _ + e.MarginBounds, StringFormat.GenericTypographic) + + ' Remove the portion of the string that has been printed. + stringToPrint = stringToPrint.Substring(charactersOnPage) + + ' Check to see if more pages are to be printed. + e.HasMorePages = stringToPrint.Length > 0 + + ' If there are no more pages, reset the string to be printed. + If Not e.HasMorePages Then + stringToPrint = documentContents + End If + + End Sub + ' + + ' + Private Sub printPreviewButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles printPreviewButton.Click + + ReadDocument() + ' + printPreviewDialog1.Document = printDocument1 + ' + printPreviewDialog1.ShowDialog() + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb new file mode 100644 index 0000000000..338d248ad5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RecoloringImages/VB/Class1.vb @@ -0,0 +1,200 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Imaging + + +Public Class SystemDrawingRecoloringImages + +' 2106fb9a-4d60-4dcf-9220-9f189a6c4d19 +' How to: Translate Image Colors + Private Sub Method11(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("ColorBars.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + + Dim colorMatrixElements As Single()() = { _ + New Single() {1, 0, 0, 0, 0}, _ + New Single() {0, 1, 0, 0, 0}, _ + New Single() {0, 0, 1, 0, 0}, _ + New Single() {0, 0, 0, 1, 0}, _ + New Single() {0.75F, 0, 0, 0, 1}} + + Dim colorMatrix As New ColorMatrix(colorMatrixElements) + + imageAttributes.SetColorMatrix( _ + colorMatrix, _ + ColorMatrixFlag.Default, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10, width, height) + + ' Pass in the destination rectangle (2nd argument), the upper-left corner + ' (3rd and 4th arguments), width (5th argument), and height (6th + ' argument) of the source rectangle. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(150, 10, width, height), _ + 0, 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + imageAttributes) + + ' + End Sub +' 44df4556-a433-49c0-ac0f-9a12063a5860 +' How to: Use a Color Matrix to Transform a Single Color + Private Sub Method21(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("InputColor.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + + ' The following matrix consists of the following transformations: + ' red scaling factor of 2 + ' green scaling factor of 1 + ' blue scaling factor of 1 + ' alpha scaling factor of 1 + ' three translations of 0.2 + Dim colorMatrixElements As Single()() = { _ + New Single() {2, 0, 0, 0, 0}, _ + New Single() {0, 1, 0, 0, 0}, _ + New Single() {0, 0, 1, 0, 0}, _ + New Single() {0, 0, 0, 1, 0}, _ + New Single() {0.2F, 0.2F, 0.2F, 0, 1}} + + Dim colorMatrix As New ColorMatrix(colorMatrixElements) + + imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10) + + e.Graphics.DrawImage( _ + image, _ + New Rectangle(120, 10, width, height), _ + 0, _ + 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + imageAttributes) + + ' + End Sub +' 977df1ce-8665-42d4-9fb1-ef7f0ff63419 +' How to: Use a Color Remap Table + Private Sub Method31(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("RemapInput.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + Dim colorMap As New ColorMap() + + colorMap.OldColor = Color.FromArgb(255, 255, 0, 0) ' opaque red + colorMap.NewColor = Color.FromArgb(255, 0, 0, 255) ' opaque blue + Dim remapTable As ColorMap() = {colorMap} + + imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10, width, height) + + ' Pass in the destination rectangle (2nd argument), the upper-left corner + ' (3rd and 4th arguments), width (5th argument), and height (6th + ' argument) of the source rectangle. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(150, 10, width, height), _ + 0, 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + imageAttributes) + + ' + End Sub +' df23c887-7fd6-4b15-ad94-e30b5bd4b849 +' Using Transformations to Scale Colors + Private Sub Method41(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("ColorBars2.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + + Dim colorMatrixElements As Single()() = { _ + New Single() {1, 0, 0, 0, 0}, _ + New Single() {0, 1, 0, 0, 0}, _ + New Single() {0, 0, 2, 0, 0}, _ + New Single() {0, 0, 0, 1, 0}, _ + New Single() {0, 0, 0, 0, 1}} + + Dim colorMatrix As New ColorMatrix(colorMatrixElements) + + imageAttributes.SetColorMatrix( _ + colorMatrix, _ + ColorMatrixFlag.Default, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10, width, height) + + ' Pass in the destination rectangle (2nd argument), the upper-left corner + ' (3rd and 4th arguments), width (5th argument), and height (6th + ' argument) of the source rectangle. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(150, 10, width, height), _ + 0, 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + imageAttributes) + + ' + End Sub + Private Sub Method42(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("ColorBars.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + + Dim colorMatrixElements As Single()() = { _ + New Single() {0.75F, 0, 0, 0, 0}, _ + New Single() {0, 0.65F, 0, 0, 0}, _ + New Single() {0, 0, 0.5F, 0, 0}, _ + New Single() {0, 0, 0, 1, 0}, _ + New Single() {0, 0, 0, 0, 1}} + + Dim colorMatrix As New ColorMatrix(colorMatrixElements) + + imageAttributes.SetColorMatrix( _ + colorMatrix, _ + ColorMatrixFlag.Default, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10, width, height) + + ' Pass in the destination rectangle, and the upper-left corner, width, + ' and height of the source rectangle as in the previous example. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(150, 10, width, height), _ + 0, 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + imageAttributes) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RotateColors/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RotateColors/VB/Form1.vb new file mode 100644 index 0000000000..11dbdc4013 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.RotateColors/VB/Form1.vb @@ -0,0 +1,66 @@ +Imports System.Drawing.Imaging +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Public Sub New() + MyBase.New() + End Sub + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Private Sub Me_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _ + Handles Me.Paint + + RotateColors(e) + End Sub + + ' + Private Sub RotateColors(ByVal e As PaintEventArgs) + Dim image As Bitmap = New Bitmap("RotationInput.bmp") + Dim imageAttributes As New ImageAttributes() + Dim width As Integer = image.Width + Dim height As Integer = image.Height + Dim degrees As Single = 60.0F + Dim r As Double = degrees * System.Math.PI / 180 ' degrees to radians + Dim colorMatrixElements As Single()() = { _ + New Single() {CSng(System.Math.Cos(r)), _ + CSng(System.Math.Sin(r)), 0, 0, 0}, _ + New Single() {CSng(-System.Math.Sin(r)), _ + CSng(-System.Math.Cos(r)), 0, 0, 0}, _ + New Single() {0, 0, 2, 0, 0}, _ + New Single() {0, 0, 0, 1, 0}, _ + New Single() {0, 0, 0, 0, 1}} + + Dim colorMatrix As New ColorMatrix(colorMatrixElements) + + imageAttributes.SetColorMatrix( _ + colorMatrix, _ + ColorMatrixFlag.Default, _ + ColorAdjustType.Bitmap) + + e.Graphics.DrawImage(image, 10, 10, width, height) + + ' Pass in the destination rectangle (2nd argument), the upper-left corner + ' (3rd and 4th arguments), width (5th argument), and height (6th + ' argument) of the source rectangle. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(150, 10, width, height), _ + 0, 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + imageAttributes) + End Sub + ' + + + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb new file mode 100644 index 0000000000..b2a0f3cbf0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingABrush/VB/Class1.vb @@ -0,0 +1,98 @@ +Option Explicit On +Option Strict On + +Imports System.Diagnostics +Imports System.Windows.Forms +Imports System.Xml +Imports System.Data +Imports System.Collections +Imports System.Drawing +Imports System.Drawing.Drawing2D + +Public Class class1 + ' 06088b31-bac9-4ef3-9ebe-06c2c764d6df + ' How to: Fill a Shape with a Solid Color + Public Sub Method11(ByVal e As PaintEventArgs) + ' + Dim solidBrush As New SolidBrush( _ + Color.FromArgb(255, 255, 0, 0)) + e.Graphics.FillEllipse(solidBrush, 0, 0, 100, 60) + + ' + End Sub + ' 508da5a6-2433-4d2b-9680-eaeae4e96e3b + ' How to: Fill a Shape with an Image Texture + Public Sub Method21(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("ImageFile.jpg") + Dim tBrush As New TextureBrush(image) + tBrush.Transform = New Matrix( _ + 75.0F / 640.0F, _ + 0.0F, _ + 0.0F, _ + 75.0F / 480.0F, _ + 0.0F, _ + 0.0F) + e.Graphics.FillEllipse(tBrush, New Rectangle(0, 150, 150, 250)) + + ' + End Sub + ' 6d407891-6e5c-4495-a546-3da5604e9fb8 + ' How to: Tile a Shape with an Image + Public Sub Method31(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("HouseAndTree.gif") + Dim tBrush As New TextureBrush(image) + Dim blackPen As New Pen(Color.Black) + e.Graphics.FillRectangle(tBrush, New Rectangle(0, 0, 200, 200)) + e.Graphics.DrawRectangle(blackPen, New Rectangle(0, 0, 200, 200)) + + ' + End Sub + Public Sub Method32(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("HouseAndTree.gif") + Dim tBrush As New TextureBrush(image) + Dim blackPen As New Pen(Color.Black) + tBrush.WrapMode = WrapMode.TileFlipX + e.Graphics.FillRectangle(tBrush, New Rectangle(0, 0, 200, 200)) + e.Graphics.DrawRectangle(blackPen, New Rectangle(0, 0, 200, 200)) + + ' + End Sub + Public Sub Method33(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("HouseAndTree.gif") + Dim tBrush As New TextureBrush(image) + Dim blackPen As New Pen(Color.Black) + tBrush.WrapMode = WrapMode.TileFlipY + e.Graphics.FillRectangle(tBrush, New Rectangle(0, 0, 200, 200)) + e.Graphics.DrawRectangle(blackPen, New Rectangle(0, 0, 200, 200)) + + ' + End Sub + Public Sub Method34(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("HouseAndTree.gif") + Dim tBrush As New TextureBrush(image) + Dim blackPen As New Pen(Color.Black) + tBrush.WrapMode = WrapMode.TileFlipXY + e.Graphics.FillRectangle(tBrush, New Rectangle(0, 0, 200, 200)) + e.Graphics.DrawRectangle(blackPen, New Rectangle(0, 0, 200, 200)) + + ' + End Sub + ' 9c8300ff-187b-404f-af1f-ebd499f5b16f + ' How to: Fill a Shape with a Hatch Pattern + Public Sub Method41(ByVal e As PaintEventArgs) + ' + Dim hBrush As New HatchBrush( _ + HatchStyle.Horizontal, _ + Color.Red, _ + Color.FromArgb(255, 128, 255, 255)) + e.Graphics.FillEllipse(hBrush, 0, 0, 100, 60) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb new file mode 100644 index 0000000000..218563e685 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingAPen/VB/Class1.vb @@ -0,0 +1,127 @@ +Option Explicit On +Option Strict On + +Imports System.Diagnostics +Imports System.Windows.Forms +Imports System.Xml +Imports System.Data +Imports System.Collections +Imports System.Drawing +Imports System.Drawing.Drawing2D + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + + ' 0828c331-a438-4bdd-a4d6-3ef1e59e8795 + ' How to: Use a Pen to Draw Lines + Public Sub Method11(ByVal e As PaintEventArgs) + ' + Dim pen As New Pen(Color.FromArgb(255, 0, 0, 0)) + e.Graphics.DrawLine(pen, 20, 10, 300, 100) + + ' + End Sub + ' 54a7fa14-3ad8-4d64-b424-2a12005b250c + ' How to: Use a Pen to Draw Rectangles + Public Sub Method21(ByVal e As PaintEventArgs) + ' + Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 5) + e.Graphics.DrawRectangle(blackPen, 10, 10, 100, 50) + ' + End Sub + ' 9fc480c2-3c75-4fd1-8ab5-296a99e820e2 + ' How to: Join Lines + Public Sub Method31(ByVal e As PaintEventArgs) + ' + Dim path As New GraphicsPath() + Dim penJoin As New Pen(Color.FromArgb(255, 0, 0, 255), 8) + + path.StartFigure() + path.AddLine(New Point(50, 200), New Point(100, 200)) + path.AddLine(New Point(100, 200), New Point(100, 250)) + + penJoin.LineJoin = LineJoin.Bevel + e.Graphics.DrawPath(penJoin, path) + + ' + End Sub + ' a202af36-4d31-4401-a126-b232f51db581 + ' How to: Set Pen Width and Alignment + Public Sub Method41(ByVal e As PaintEventArgs) + ' + Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 1) + Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10) + greenPen.Alignment = PenAlignment.Center + + ' Draw the line with the wide green pen. + e.Graphics.DrawLine(greenPen, 10, 100, 100, 50) + + ' Draw the line with the thin black pen. + e.Graphics.DrawLine(blackPen, 10, 100, 100, 50) + + ' + End Sub + Public Sub Method42(ByVal e As PaintEventArgs) + ' + Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 1) + Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10) + greenPen.Alignment = PenAlignment.Center + + ' Draw the rectangle with the wide green pen. + e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50) + + ' Draw the rectangle with the thin black pen. + e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50) + + ' + End Sub + Public Sub Method43(ByVal e As PaintEventArgs) + Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10) + ' + greenPen.Alignment = PenAlignment.Inset + + ' + End Sub + ' cd0ed96a-cce4-47b9-b58a-3bae2e3d1bee + ' How to: Draw a Custom Dashed Line + Public Sub Method51(ByVal e As PaintEventArgs) + ' + Dim dashValues As Single() = {5, 2, 15, 4} + Dim blackPen As New Pen(Color.Black, 5) + blackPen.DashPattern = dashValues + e.Graphics.DrawLine(blackPen, New Point(5, 5), New Point(405, 5)) + + ' + End Sub + ' dc9118cc-f3c2-42e5-8173-f46d41d18fd5 + ' How to: Draw a Line Filled with a Texture + Public Sub Method61(ByVal e As PaintEventArgs) + ' + Dim bitmap As New Bitmap("Texture1.jpg") + Dim tBrush As New TextureBrush(bitmap) + Dim texturedPen As New Pen(tBrush, 30) + + e.Graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height) + e.Graphics.DrawEllipse(texturedPen, 100, 20, 200, 100) + + ' + End Sub + ' eb68c3e1-c400-4886-8a04-76978a429cb6 + ' How to: Draw a Line with Line Caps + Public Sub Method71(ByVal e As PaintEventArgs) + ' + Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255), 8) + pen.StartCap = LineCap.ArrowAnchor + pen.EndCap = LineCap.RoundAnchor + e.Graphics.DrawLine(pen, 20, 175, 300, 175) + + ' + End Sub +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb new file mode 100644 index 0000000000..090aa3992d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.UsingaGradientBrush/VB/Class1.vb @@ -0,0 +1,295 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Drawing2D + +Public Class class1 + + ' 1948e834-e104-481c-b71d-d8aa9e4d106e + ' How to: Create a Path Gradient + Public Sub Method11(ByVal e As PaintEventArgs) + ' + ' Create a path that consists of a single ellipse. + Dim path As New GraphicsPath() + path.AddEllipse(0, 0, 140, 70) + + ' Use the path to construct a brush. + Dim pthGrBrush As New PathGradientBrush(path) + + ' Set the color at the center of the path to blue. + pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255) + + ' Set the color along the entire boundary + ' of the path to aqua. + Dim colors As Color() = {Color.FromArgb(255, 0, 255, 255)} + pthGrBrush.SurroundColors = colors + + e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70) + + ' + End Sub + 'The following example constructs a path gradient brush from a star-shaped path. T + Public Sub Method12(ByVal e As PaintEventArgs) + + ' + ' Put the points of a polygon in an array. + Dim points As Point() = { _ + New Point(75, 0), _ + New Point(100, 50), _ + New Point(150, 50), _ + New Point(112, 75), _ + New Point(150, 150), _ + New Point(75, 100), _ + New Point(0, 150), _ + New Point(37, 75), _ + New Point(0, 50), _ + New Point(50, 50)} + + ' Use the array of points to construct a path. + Dim path As New GraphicsPath() + path.AddLines(points) + + ' Use the path to construct a path gradient brush. + Dim pthGrBrush As New PathGradientBrush(path) + + ' Set the color at the center of the path to red. + pthGrBrush.CenterColor = Color.FromArgb(255, 255, 0, 0) + + ' Set the colors of the points in the array. + Dim colors As Color() = { _ + Color.FromArgb(255, 0, 0, 0), _ + Color.FromArgb(255, 0, 255, 0), _ + Color.FromArgb(255, 0, 0, 255), _ + Color.FromArgb(255, 255, 255, 255), _ + Color.FromArgb(255, 0, 0, 0), _ + Color.FromArgb(255, 0, 255, 0), _ + Color.FromArgb(255, 0, 0, 255), _ + Color.FromArgb(255, 255, 255, 255), _ + Color.FromArgb(255, 0, 0, 0), _ + Color.FromArgb(255, 0, 255, 0)} + + pthGrBrush.SurroundColors = colors + + ' Fill the path with the path gradient brush. + e.Graphics.FillPath(pthGrBrush, path) + ' + End Sub + + + Public Sub Method13(ByVal e As PaintEventArgs) + ' + ' Construct a path gradient brush based on an array of points. + Dim ptsF As PointF() = { _ + New PointF(0, 0), _ + New PointF(160, 0), _ + New PointF(160, 200), _ + New PointF(80, 150), _ + New PointF(0, 200)} + + Dim pBrush As New PathGradientBrush(ptsF) + + ' An array of five points was used to construct the path gradient + ' brush. Set the color of each point in that array. + 'Point (0, 0) is red + 'Point (160, 0) is green + 'Point (160, 200) is green + 'Point (80, 150) is blue + 'Point (0, 200) is red + Dim colors As Color() = { _ + Color.FromArgb(255, 255, 0, 0), _ + Color.FromArgb(255, 0, 255, 0), _ + Color.FromArgb(255, 0, 255, 0), _ + Color.FromArgb(255, 0, 0, 255), _ + Color.FromArgb(255, 255, 0, 0)} + pBrush.SurroundColors = colors + + ' Set the center color to white. + pBrush.CenterColor = Color.White + + ' Use the path gradient brush to fill a rectangle. + e.Graphics.FillRectangle(pBrush, New Rectangle(0, 0, 160, 200)) + ' + End Sub + + Public Sub Method14(ByVal e As PaintEventArgs) + + ' + ' Create a path that consists of a single ellipse. + Dim path As New GraphicsPath() + path.AddEllipse(0, 0, 200, 100) + + ' Create a path gradient brush based on the elliptical path. + Dim pthGrBrush As New PathGradientBrush(path) + + ' Set the color along the entire boundary to blue. + ' Changed variable name from color + Dim blueColor As Color() = {Color.Blue} + pthGrBrush.SurroundColors = blueColor + + ' Set the center color to aqua. + pthGrBrush.CenterColor = Color.Aqua + + ' Use the path gradient brush to fill the ellipse. + e.Graphics.FillPath(pthGrBrush, path) + + ' Set the focus scales for the path gradient brush. + pthGrBrush.FocusScales = New PointF(0.3F, 0.8F) + + ' Use the path gradient brush to fill the ellipse again. + ' Show this filled ellipse to the right of the first filled ellipse. + e.Graphics.TranslateTransform(220.0F, 0.0F) + e.Graphics.FillPath(pthGrBrush, path) + + ' + End Sub + + Public Sub Method15(ByVal e As PaintEventArgs) + ' + ' Vertices of the outer triangle + Dim points As Point() = { _ + New Point(100, 0), _ + New Point(200, 200), _ + New Point(0, 200)} + + ' No GraphicsPath object is created. The PathGradientBrush + ' object is constructed directly from the array of points. + Dim pthGrBrush As New PathGradientBrush(points) + + ' Create an array of colors containing dark green, aqua, and blue. + Dim colors As Color() = { _ + Color.FromArgb(255, 0, 128, 0), _ + Color.FromArgb(255, 0, 255, 255), _ + Color.FromArgb(255, 0, 0, 255)} + + ' Dark green is at the boundary of the triangle. + ' Aqua is 40 percent of the way from the boundary to the center point. + ' Blue is at the center point. + Dim relativePositions As Single() = { _ + 0.0F, _ + 0.4F, _ + 1.0F} + + Dim colorBlend As New ColorBlend() + colorBlend.Colors = colors + colorBlend.Positions = relativePositions + pthGrBrush.InterpolationColors = colorBlend + + ' Fill a rectangle that is larger than the triangle + ' specified in the Point array. The portion of the + ' rectangle outside the triangle will not be painted. + e.Graphics.FillRectangle(pthGrBrush, 0, 0, 200, 200) + + ' + End Sub + + Public Sub Method16(ByVal e As PaintEventArgs) + ' + ' Create a path that consists of a single ellipse. + Dim path As New GraphicsPath() + path.AddEllipse(0, 0, 140, 70) + + ' Use the path to construct a brush. + Dim pthGrBrush As New PathGradientBrush(path) + + ' Set the center point to a location that is not + ' the centroid of the path. + pthGrBrush.CenterPoint = New PointF(120, 40) + + ' Set the color at the center of the path to blue. + pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255) + + ' Set the color along the entire boundary + ' of the path to aqua. + Dim colors As Color() = {Color.FromArgb(255, 0, 255, 255)} + pthGrBrush.SurroundColors = colors + + e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70) + ' + + ' + pthGrBrush.CenterPoint = New PointF(145, 35) + ' + End Sub + + ' 6c88e1cc-1217-4399-ac12-cb37592b9f01 + ' How to: Create a Linear Gradient + Public Sub Method21(ByVal e As PaintEventArgs) + ' + Dim linGrBrush As New LinearGradientBrush( _ + New Point(0, 10), _ + New Point(200, 10), _ + Color.FromArgb(255, 255, 0, 0), _ + Color.FromArgb(255, 0, 0, 255)) + Dim pen As New Pen(linGrBrush) + + e.Graphics.DrawLine(pen, 0, 10, 200, 10) + e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100) + e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30) + + ' + End Sub + + + Public Sub Method22(ByVal e As PaintEventArgs) + ' + Dim linGrBrush As New LinearGradientBrush( _ + New Point(0, 10), _ + New Point(200, 10), _ + Color.FromArgb(255, 0, 0, 0), _ + Color.FromArgb(255, 255, 0, 0)) + + Dim relativeIntensities As Single() = {0.0F, 0.5F, 1.0F} + Dim relativePositions As Single() = {0.0F, 0.2F, 1.0F} + + 'Create a Blend object and assign it to linGrBrush. + Dim blend As New Blend() + blend.Factors = relativeIntensities + blend.Positions = relativePositions + linGrBrush.Blend = blend + + e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100) + e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30) + + ' + End Sub + + + Public Sub Method23(ByVal e As PaintEventArgs) + ' + Dim linGrBrush As New LinearGradientBrush( _ + New Point(0, 0), _ + New Point(200, 100), _ + Color.FromArgb(255, 0, 0, 255), _ + Color.FromArgb(255, 0, 255, 0)) + ' opaque blue + ' opaque green + Dim pen As New Pen(linGrBrush, 10) + + e.Graphics.DrawLine(pen, 0, 0, 600, 300) + e.Graphics.FillEllipse(linGrBrush, 10, 100, 200, 100) + + ' + End Sub + + ' da4690e7-5fac-4fd2-b3f0-5cb35c165b92 + ' How to: Apply Gamma Correction to a Gradient + Public Sub Method31(ByVal e As PaintEventArgs) + ' + Dim linGrBrush As New LinearGradientBrush( _ + New Point(0, 10), _ + New Point(200, 10), _ + Color.Red, _ + Color.Blue) + + e.Graphics.FillRectangle(linGrBrush, 0, 0, 200, 50) + linGrBrush.GammaCorrection = True + e.Graphics.FillRectangle(linGrBrush, 0, 60, 200, 50) + ' + End Sub +End Class + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb new file mode 100644 index 0000000000..b6094559b2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Drawing.WorkingWithImages/VB/Class1.vb @@ -0,0 +1,263 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml +Imports System.Drawing.Imaging +Imports System.Drawing.Drawing2D + + +Public Class SystemDrawingWorkingWithImages +Inherits Form + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New SystemDrawingWorkingWithImages()) + + End Sub + + ' 053e3360-bca0-4b25-9afa-0e77a6f17b03 + ' How to: Crop and Scale Images + Private Sub Method11(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("Apple.gif") + + ' Draw the image unaltered with its upper-left corner at (0, 0). + e.Graphics.DrawImage(image, 0, 0) + + ' Make the destination rectangle 30 percent wider and + ' 30 percent taller than the original image. + ' Put the upper-left corner of the destination + ' rectangle at (150, 20). + Dim width As Integer = image.Width + Dim height As Integer = image.Height + Dim destinationRect As New RectangleF( _ + 150, _ + 20, _ + 1.3F * width, _ + 1.3F * height) + + ' Draw a portion of the image. Scale that portion of the image + ' so that it fills the destination rectangle. + Dim sourceRect As New RectangleF(0, 0, 0.75F * width, 0.75F * height) + e.Graphics.DrawImage( _ + image, _ + destinationRect, _ + sourceRect, _ + GraphicsUnit.Pixel) + + ' + End Sub + ' 5bc558d7-b326-4050-a834-b8600da0de95 + ' How to: Load and Display Bitmaps + Private Sub Method21(ByVal e As PaintEventArgs) + ' + Dim bitmap As New Bitmap("Grapes.jpg") + e.Graphics.DrawImage(bitmap, 60, 10) + + ' + End Sub + ' 5fe2c95d-8653-4d55-bf0d-e5afa28f223b + ' How to: Improve Performance by Avoiding Automatic Scaling + Private Sub Method31(ByVal e As PaintEventArgs) + Dim image As New Bitmap("Texture.jpg") + ' + e.Graphics.DrawImage(image, 50, 30) ' upper-left corner at (50, 30) + ' + End Sub + Private Sub Method32(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("Texture.jpg") + + e.Graphics.DrawImage(image, 10, 10) + e.Graphics.DrawImage(image, 120, 10, image.Width, image.Height) + ' + End Sub + ' 60af1714-f148-4d85-a739-0557965ffa73 + ' How to: Load and Display Metafiles + Private Sub Method41(ByVal e As PaintEventArgs) + ' + Dim metafile As New Metafile("SampleMetafile.emf") + e.Graphics.DrawImage(metafile, 60, 10) + + ' + End Sub + ' 72ec0b31-0be7-444a-9575-1dbcb864e0be + ' How to: Read Image Metadata + Private Sub Method51(ByVal e As PaintEventArgs) + ' + 'Create an Image object. + Dim image As Bitmap = New Bitmap("c:\FakePhoto.jpg") + + 'Get the PropertyItems property from image. + Dim propItems As PropertyItem() = image.PropertyItems + + 'Set up the display. + Dim font As New Font("Arial", 12) + Dim blackBrush As New SolidBrush(Color.Black) + Dim X As Integer = 0 + Dim Y As Integer = 0 + + 'For each PropertyItem in the array, display the ID, type, and length. + Dim count As Integer = 0 + Dim propItem As PropertyItem + For Each propItem In propItems + e.Graphics.DrawString( _ + "Property Item " & count.ToString(), _ + font, _ + blackBrush, _ + X, Y) + + Y += font.Height + + e.Graphics.DrawString( _ + " id: 0x" & propItem.Id.ToString("x"), _ + font, _ + blackBrush, _ + X, Y) + + Y += font.Height + + e.Graphics.DrawString( _ + " type: " & propItem.Type.ToString(), _ + font, _ + blackBrush, _ + X, Y) + + Y += font.Height + + e.Graphics.DrawString( _ + " length: " & propItem.Len.ToString() & " bytes", _ + font, _ + blackBrush, _ + X, Y) + + Y += font.Height + + count += 1 + Next propItem + 'Convert the value of the second property to a string, and display it. + Dim encoding As New System.Text.ASCIIEncoding() + Dim manufacturer As String = encoding.GetString(propItems(1).Value) + + e.Graphics.DrawString( _ + "The equipment make is " & manufacturer & ".", _ + font, _ + blackBrush, _ + X, Y) + + ' + End Sub + ' a3bf97eb-63ed-425a-ba07-dcc65efb567c + ' How to: Rotate, Reflect, and Skew Images + Private Sub Method61(ByVal e As PaintEventArgs) + ' + ' New Point(200, 20) = destination for upper-left point of original + ' New Point(110, 100) = destination for upper-right point of original + ' New Point(250, 30) = destination for lower-left point of original + Dim destinationPoints As Point() = { _ + New Point(200, 20), _ + New Point(110, 100), _ + New Point(250, 30)} + + Dim image As New Bitmap("Stripes.bmp") + + ' Draw the image unaltered with its upper-left corner at (0, 0). + e.Graphics.DrawImage(image, 0, 0) + + ' Draw the image mapped to the parallelogram. + e.Graphics.DrawImage(image, destinationPoints) + + ' + End Sub + ' e956242a-1e5b-4217-a3cf-5f3fb45d00ba + ' How to: Create Thumbnail Images + + + ' + Public Function ThumbnailCallback() As Boolean + Return True + End Function + + Private Sub GetThumbnail(ByVal e As PaintEventArgs) + + Dim callback As New Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback) + Dim image As Image = New Bitmap("c:\FakePhoto.jpg") + Dim pThumbnail As Image = image.GetThumbnailImage(100, 100, callback, New IntPtr()) + e.Graphics.DrawImage(pThumbnail, 10, 10, pThumbnail.Width, pThumbnail.Height) + End Sub + ' + + + ' fde9bccf-8aa5-4b0d-ba4b-788740627b02 + ' How to: Use Interpolation Mode to Control Image Quality During Scaling + Private Sub Method81(ByVal e As PaintEventArgs) + ' + Dim image As New Bitmap("GrapeBunch.bmp") + Dim width As Integer = image.Width + Dim height As Integer = image.Height + + ' Draw the image with no shrinking or stretching. Pass in the destination + ' rectangle (2nd argument), the upper-left corner (3rd and 4th arguments), + ' width (5th argument), and height (6th argument) of the source + ' rectangle. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(10, 10, width, height), _ + 0, _ + 0, _ + width, _ + height, _ + GraphicsUnit.Pixel, _ + Nothing) + + ' Shrink the image using low-quality interpolation. + e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor + + ' Pass in the destination rectangle, and the upper-left corner, width, + ' and height of the source rectangle as above. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(10, 250, CInt(0.6 * width), CInt(0.6 * height)), _ + 0, _ + 0, _ + width, _ + height, _ + GraphicsUnit.Pixel) + + ' Shrink the image using medium-quality interpolation. + e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear + + ' Pass in the destination rectangle, and the upper-left corner, width, + ' and height of the source rectangle as above. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(150, 250, CInt(0.6 * width), _ + CInt(0.6 * height)), _ + 0, _ + 0, _ + width, _ + height, _ + GraphicsUnit.Pixel) + + ' Shrink the image using high-quality interpolation. + e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic + + ' Pass in the destination rectangle, and the upper-left corner, width, + ' and height of the source rectangle as above. + e.Graphics.DrawImage( _ + image, _ + New Rectangle(290, 250, CInt(0.6 * width), CInt(0.6 * height)), _ + 0, _ + 0, _ + width, _ + height, _ + GraphicsUnit.Pixel) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/VB/Form1.vb new file mode 100644 index 0000000000..537b9a8c86 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.LoadAsync/VB/Form1.vb @@ -0,0 +1,88 @@ +' +Imports System.Media +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Friend WithEvents playSoundButton As System.Windows.Forms.Button + Private WithEvents Player As New SoundPlayer + + Sub New() + + Me.InitializeComponent() + + End Sub + + Private Sub playSoundButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles playSoundButton.Click + + ' Replace this file name with a valid file name. + Me.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav" + Me.Player.LoadAsync() + + End Sub + + Private Sub Player_LoadCompleted( _ + ByVal sender As Object, _ + ByVal e As _ + System.ComponentModel.AsyncCompletedEventArgs) _ + Handles Player.LoadCompleted + + If Me.Player.IsLoadCompleted Then + Me.Player.Play() + End If + + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.playSoundButton = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + 'playSoundButton + ' + Me.playSoundButton.Location = New System.Drawing.Point(105, 107) + Me.playSoundButton.Name = "playSoundButton" + Me.playSoundButton.Size = New System.Drawing.Size(75, 23) + Me.playSoundButton.TabIndex = 0 + Me.playSoundButton.Text = "Play Sound" + Me.playSoundButton.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.playSoundButton) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/VB/Form1.vb new file mode 100644 index 0000000000..56d19c8f0b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Media.SoundPlayer.PlayLooping/VB/Form1.vb @@ -0,0 +1,103 @@ +' +Imports System.Media +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Private Player As New SoundPlayer + + Sub New() + + Me.InitializeComponent() + + End Sub + + Private Sub playLoopingButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles playLoopingButton.Click + + Try + ' Note: You may need to change the location specified based on + ' the sounds loaded on your computer. + Me.Player.SoundLocation = "C:\Windows\Media\chimes.wav" + Me.Player.PlayLooping() + Catch ex As Exception + MessageBox.Show(ex.Message, "Error playing sound") + End Try + + End Sub + + Private Sub stopPlayingButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles stopPlayingButton.Click + + Me.Player.Stop() + + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + Friend WithEvents playLoopingButton As System.Windows.Forms.Button + Friend WithEvents stopPlayingButton As System.Windows.Forms.Button + + '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.playLoopingButton = New System.Windows.Forms.Button + Me.stopPlayingButton = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + 'playLoopingButton + ' + Me.playLoopingButton.Location = New System.Drawing.Point(12, 12) + Me.playLoopingButton.Name = "playLoopingButton" + Me.playLoopingButton.Size = New System.Drawing.Size(89, 23) + Me.playLoopingButton.TabIndex = 0 + Me.playLoopingButton.Text = "Play Looping" + Me.playLoopingButton.UseVisualStyleBackColor = True + ' + 'stopPlayingButton + ' + Me.stopPlayingButton.Location = New System.Drawing.Point(107, 12) + Me.stopPlayingButton.Name = "stopPlayingButton" + Me.stopPlayingButton.Size = New System.Drawing.Size(75, 23) + Me.stopPlayingButton.TabIndex = 1 + Me.stopPlayingButton.Text = "Stop" + Me.stopPlayingButton.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(197, 52) + Me.Controls.Add(Me.stopPlayingButton) + Me.Controls.Add(Me.playLoopingButton) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb new file mode 100644 index 0000000000..cd72778a60 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BasicForm/VB/Form1.vb @@ -0,0 +1,26 @@ + ' +' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms +' + +' +Public Class Form1 + Inherits Form + ' + + ' + Public Sub New() + + End Sub + ' + ' + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/VB/form1.vb new file mode 100644 index 0000000000..01bb9ceccf --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingDBNull/VB/form1.vb @@ -0,0 +1,105 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Data.SqlClient +Imports System.Windows.Forms + + + +Public Class Form1 + Inherits Form + + Public Sub New() + End Sub + + ' The controls and components we need for the form. + Private WithEvents button1 As Button + Private pictureBox1 As PictureBox + Private bindingSource1 As BindingSource + Private textBox1 As TextBox + Private textBox2 As TextBox + + ' Data table to hold the database data. + Private employeeTable As New DataTable() + + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + ' Basic form setup. + Me.pictureBox1 = New PictureBox() + Me.bindingSource1 = New BindingSource() + Me.textBox1 = New TextBox() + Me.textBox2 = New TextBox() + Me.button1 = New Button() + Me.pictureBox1.Location = New System.Drawing.Point(20, 20) + Me.pictureBox1.Size = New System.Drawing.Size(174, 179) + Me.textBox1.Location = New System.Drawing.Point(25, 215) + Me.textBox1.ReadOnly = True + Me.textBox2.Location = New System.Drawing.Point(25, 241) + Me.textBox2.ReadOnly = True + Me.button1.Location = New System.Drawing.Point(200, 103) + Me.button1.Text = "Move Next" + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.button1) + Me.Controls.Add(Me.textBox2) + Me.Controls.Add(Me.textBox1) + Me.Controls.Add(Me.pictureBox1) + Me.ResumeLayout(False) + Me.PerformLayout() + + ' Create the connection string and populate the data table + ' with data. + Dim connectionString As String = "Integrated Security=SSPI;" & _ + "Persist Security Info = False;Initial Catalog=Northwind;" _ + & "Data Source = localhost" + Dim connection As New SqlConnection() + connection.ConnectionString = connectionString + Dim employeeAdapter As New SqlDataAdapter _ + (New SqlCommand("Select * from Employees", connection)) + connection.Open() + employeeAdapter.Fill(employeeTable) + + ' Set the DataSource property of the BindingSource to the employee table. + bindingSource1.DataSource = employeeTable + + ' Set up the binding to the ReportsTo column. + Dim reportsToBinding As Binding = _ + textBox2.DataBindings.Add("Text", bindingSource1, "ReportsTo", _ + True) + + ' Set the NullValue property for this binding. + reportsToBinding.NullValue = "No Manager" + + ' Set up the binding for the PictureBox using the Add method, setting + ' the null value in method call. + pictureBox1.DataBindings.Add("Image", bindingSource1, "Photo", _ + True, DataSourceUpdateMode.Never, _ + New Bitmap(GetType(Button), "Button.bmp")) + + ' Set up the remaining binding. + textBox1.DataBindings.Add("Text", bindingSource1, "LastName", True) + + End Sub + + + ' Move through the data when the button is clicked. + Private Sub button1_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles button1.Click + + bindingSource1.MoveNext() + + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/VB/Form1.vb new file mode 100644 index 0000000000..7685fb23c2 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingNavigatorNavigate/VB/Form1.vb @@ -0,0 +1,206 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Xml +Imports System.IO +Imports System.Text + + + +Class Form1 + Inherits Form + Private components As IContainer + Private bindingNavigator1 As BindingNavigator + Private bindingNavigatorAddNewItem As ToolStripButton + Private bindingNavigatorCountItem As ToolStripLabel + Private bindingNavigatorDeleteItem As ToolStripButton + Private bindingNavigatorMoveFirstItem As ToolStripButton + Private bindingNavigatorMovePreviousItem As ToolStripButton + Private bindingNavigatorSeparator As ToolStripSeparator + Private bindingNavigatorPositionItem As ToolStripTextBox + Private bindingNavigatorSeparator1 As ToolStripSeparator + Private bindingNavigatorMoveNextItem As ToolStripButton + Private bindingNavigatorMoveLastItem As ToolStripButton + Private textBox1 As TextBox + Private textBox2 As TextBox + Private bindingSource1 As BindingSource + Private bindingNavigatorSeparator2 As ToolStripSeparator + + + Public Sub New() + InitializeComponent() + LoadData() + + ' + bindingNavigator1.BindingSource = bindingSource1 + ' + + End Sub + ' + Private Sub LoadData() + ' The xml to bind to. + Dim xml As String = "" + "WashingtonOlympia" + "OregonSalem" + "CaliforniaSacramento" + "NevadaCarson City" + "" + + ' Convert the xml string to bytes and load into a memory stream. + Dim xmlBytes As Byte() = Encoding.UTF8.GetBytes(xml) + Dim stream As New MemoryStream(xmlBytes, False) + + ' Create a DataSet and load the xml into it. + Dim [set] As New DataSet() + [set].ReadXml(stream) + + ' Set the DataSource to the DataSet, and the DataMember + ' to state. + bindingSource1.DataSource = [set] + bindingSource1.DataMember = "state" + + textBox1.DataBindings.Add("Text", bindingSource1, "name") + textBox2.DataBindings.Add("Text", bindingSource1, "capital") + + End Sub + + ' + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container() + Dim resources As New System.ComponentModel.ComponentResourceManager(GetType(Form1)) + Me.bindingNavigator1 = New System.Windows.Forms.BindingNavigator(Me.components) + Me.bindingNavigatorAddNewItem = New System.Windows.Forms.ToolStripButton() + Me.bindingNavigatorCountItem = New System.Windows.Forms.ToolStripLabel() + Me.bindingNavigatorDeleteItem = New System.Windows.Forms.ToolStripButton() + Me.bindingNavigatorMoveFirstItem = New System.Windows.Forms.ToolStripButton() + Me.bindingNavigatorMovePreviousItem = New System.Windows.Forms.ToolStripButton() + Me.bindingNavigatorSeparator = New System.Windows.Forms.ToolStripSeparator() + Me.bindingNavigatorPositionItem = New System.Windows.Forms.ToolStripTextBox() + Me.bindingNavigatorSeparator1 = New System.Windows.Forms.ToolStripSeparator() + Me.bindingNavigatorMoveNextItem = New System.Windows.Forms.ToolStripButton() + Me.bindingNavigatorMoveLastItem = New System.Windows.Forms.ToolStripButton() + Me.bindingNavigatorSeparator2 = New System.Windows.Forms.ToolStripSeparator() + Me.textBox1 = New System.Windows.Forms.TextBox() + Me.textBox2 = New System.Windows.Forms.TextBox() + Me.bindingSource1 = New System.Windows.Forms.BindingSource(Me.components) + CType(Me.bindingNavigator1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.bindingNavigator1.SuspendLayout() + CType(Me.bindingSource1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + ' bindingNavigator1 + ' + Me.bindingNavigator1.AddNewItem = Me.bindingNavigatorAddNewItem + Me.bindingNavigator1.CountItem = Me.bindingNavigatorCountItem + Me.bindingNavigator1.CountItemFormat = "of {0}" + Me.bindingNavigator1.DeleteItem = Me.bindingNavigatorDeleteItem + Me.bindingNavigator1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.bindingNavigatorMoveFirstItem, Me.bindingNavigatorMovePreviousItem, Me.bindingNavigatorSeparator, Me.bindingNavigatorPositionItem, Me.bindingNavigatorCountItem, Me.bindingNavigatorSeparator1, Me.bindingNavigatorMoveNextItem, Me.bindingNavigatorMoveLastItem, Me.bindingNavigatorSeparator2, Me.bindingNavigatorAddNewItem, Me.bindingNavigatorDeleteItem}) + Me.bindingNavigator1.Location = New System.Drawing.Point(0, 0) + Me.bindingNavigator1.MoveFirstItem = Me.bindingNavigatorMoveFirstItem + Me.bindingNavigator1.MoveLastItem = Me.bindingNavigatorMoveLastItem + Me.bindingNavigator1.MoveNextItem = Me.bindingNavigatorMoveNextItem + Me.bindingNavigator1.MovePreviousItem = Me.bindingNavigatorMovePreviousItem + Me.bindingNavigator1.Name = "bindingNavigator1" + Me.bindingNavigator1.PositionItem = Me.bindingNavigatorPositionItem + Me.bindingNavigator1.TabIndex = 2 + Me.bindingNavigator1.Text = "bindingNavigator1" + ' + ' bindingNavigatorAddNewItem + ' + Me.bindingNavigatorAddNewItem.Image = CType(resources.GetObject("bindingNavigatorAddNewItem.Image"), System.Drawing.Image) + Me.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem" + Me.bindingNavigatorAddNewItem.Text = "Add new" + ' + ' bindingNavigatorCountItem + ' + Me.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem" + Me.bindingNavigatorCountItem.Text = "of {0}" + Me.bindingNavigatorCountItem.ToolTipText = "Total number of items" + ' + ' bindingNavigatorDeleteItem + ' + Me.bindingNavigatorDeleteItem.Image = CType(resources.GetObject("bindingNavigatorDeleteItem.Image"), System.Drawing.Image) + Me.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem" + Me.bindingNavigatorDeleteItem.Text = "Delete" + ' + ' bindingNavigatorMoveFirstItem + ' + Me.bindingNavigatorMoveFirstItem.Image = CType(resources.GetObject("bindingNavigatorMoveFirstItem.Image"), System.Drawing.Image) + Me.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem" + Me.bindingNavigatorMoveFirstItem.Text = "Move first" + ' + ' bindingNavigatorMovePreviousItem + ' + Me.bindingNavigatorMovePreviousItem.Image = CType(resources.GetObject("bindingNavigatorMovePreviousItem.Image"), System.Drawing.Image) + Me.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem" + Me.bindingNavigatorMovePreviousItem.Text = "Move previous" + ' + ' bindingNavigatorSeparator + ' + Me.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator" + + ' + ' bindingNavigatorPositionItem + ' + Me.bindingNavigatorPositionItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText + Me.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem" + Me.bindingNavigatorPositionItem.Size = New System.Drawing.Size(50, 25) + Me.bindingNavigatorPositionItem.Text = "0" + Me.bindingNavigatorPositionItem.ToolTipText = "Current position" + ' + ' bindingNavigatorSeparator1 + ' + Me.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1" + ' + ' bindingNavigatorMoveNextItem + ' + Me.bindingNavigatorMoveNextItem.Image = CType(resources.GetObject("bindingNavigatorMoveNextItem.Image"), System.Drawing.Image) + Me.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem" + Me.bindingNavigatorMoveNextItem.Text = "Move next" + ' + ' bindingNavigatorMoveLastItem + ' + Me.bindingNavigatorMoveLastItem.Image = CType(resources.GetObject("bindingNavigatorMoveLastItem.Image"), System.Drawing.Image) + Me.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem" + Me.bindingNavigatorMoveLastItem.Text = "Move last" + ' + ' bindingNavigatorSeparator2 + ' + Me.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2" + + ' + ' textBox1 + ' + Me.textBox1.Location = New System.Drawing.Point(46, 64) + Me.textBox1.Name = "textBox1" + Me.textBox1.TabIndex = 3 + ' + ' textBox2 + ' + Me.textBox2.Location = New System.Drawing.Point(46, 104) + Me.textBox2.Name = "textBox2" + Me.textBox2.TabIndex = 4 + ' + ' Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(textBox2) + Me.Controls.Add(textBox1) + Me.Controls.Add(bindingNavigator1) + Me.Name = "Form1" + CType(Me.bindingNavigator1, System.ComponentModel.ISupportInitialize).EndInit() + Me.bindingNavigator1.ResumeLayout(False) + Me.bindingNavigator1.PerformLayout() + CType(Me.bindingSource1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/VB/Form1.vb new file mode 100644 index 0000000000..33d3fe0000 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleControls/VB/Form1.vb @@ -0,0 +1,163 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms +Imports System.IO + + + +Public Class Form1 + Inherits Form + + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load + 'InitializeControlsAndDataSource(); + InitializeControlsAndData() + + End Sub + + ' + ' + ' Declare the controls to be used. + Private WithEvents bindingSource1 As BindingSource + Private WithEvents textBox1 As TextBox + Private WithEvents textBox2 As TextBox + Private WithEvents dataGridView1 As DataGridView + + + Private Sub InitializeControlsAndDataSource() + ' Initialize the controls and set location, size and + ' other basic properties. + Me.dataGridView1 = New DataGridView() + Me.bindingSource1 = New BindingSource() + Me.textBox1 = New TextBox() + Me.textBox2 = New TextBox() + Me.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.Dock = DockStyle.Top + Me.dataGridView1.Location = New Point(0, 0) + Me.dataGridView1.Size = New Size(292, 150) + Me.textBox1.Location = New Point(132, 156) + Me.textBox1.Size = New Size(100, 20) + Me.textBox2.Location = New Point(12, 156) + Me.textBox2.Size = New Size(100, 20) + Me.ClientSize = New Size(292, 266) + Me.Controls.Add(Me.textBox2) + Me.Controls.Add(Me.textBox1) + Me.Controls.Add(Me.dataGridView1) + + ' Declare the DataSet and add a table and column. + Dim set1 As New DataSet() + set1.Tables.Add("Menu") + set1.Tables(0).Columns.Add("Beverages") + + ' Add some rows to the table. + set1.Tables(0).Rows.Add("coffee") + set1.Tables(0).Rows.Add("tea") + set1.Tables(0).Rows.Add("hot chocolate") + set1.Tables(0).Rows.Add("milk") + set1.Tables(0).Rows.Add("orange juice") + + ' Set the data source to the DataSet. + bindingSource1.DataSource = set1 + + 'Set the DataMember to the Menu table. + bindingSource1.DataMember = "Menu" + + ' Add the control data bindings. + dataGridView1.DataSource = bindingSource1 + textBox1.DataBindings.Add("Text", bindingSource1, "Beverages", _ + True, DataSourceUpdateMode.OnPropertyChanged) + textBox2.DataBindings.Add("Text", bindingSource1, "Beverages", _ + True, DataSourceUpdateMode.OnPropertyChanged) + + + End Sub + + ' + ' + Private Sub bindingSource1_BindingComplete(ByVal sender As Object, _ + ByVal e As BindingCompleteEventArgs) Handles bindingSource1.BindingComplete + + ' Check if the data source has been updated, and that no error has occurred. + If e.BindingCompleteContext = BindingCompleteContext.DataSourceUpdate _ + AndAlso e.Exception Is Nothing Then + + ' If not, end the current edit. + e.Binding.BindingManagerBase.EndCurrentEdit() + End If + + End Sub + ' + ' + ' + Dim WithEvents bmb As BindingManagerBase + + Private Sub InitializeControlsAndData() + ' Initialize the controls and set location, size and + ' other basic properties. + Me.dataGridView1 = New DataGridView() + + Me.textBox1 = New TextBox() + Me.textBox2 = New TextBox() + Me.dataGridView1.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.Dock = DockStyle.Top + Me.dataGridView1.Location = New Point(0, 0) + Me.dataGridView1.Size = New Size(292, 150) + Me.textBox1.Location = New Point(132, 156) + Me.textBox1.Size = New Size(100, 20) + Me.textBox2.Location = New Point(12, 156) + Me.textBox2.Size = New Size(100, 20) + Me.ClientSize = New Size(292, 266) + Me.Controls.Add(Me.textBox2) + Me.Controls.Add(Me.textBox1) + Me.Controls.Add(Me.dataGridView1) + + ' Declare the DataSet and add a table and column. + Dim set1 As New DataSet() + set1.Tables.Add("Menu") + set1.Tables(0).Columns.Add("Beverages") + + ' Add some rows to the table. + set1.Tables(0).Rows.Add("coffee") + set1.Tables(0).Rows.Add("tea") + set1.Tables(0).Rows.Add("hot chocolate") + set1.Tables(0).Rows.Add("milk") + set1.Tables(0).Rows.Add("orange juice") + + ' Add the control data bindings. + dataGridView1.DataSource = set1 + dataGridView1.DataMember = "Menu" + textBox1.DataBindings.Add("Text", set1, "Menu.Beverages", _ + True, DataSourceUpdateMode.OnPropertyChanged) + textBox2.DataBindings.Add("Text", set1, "Menu.Beverages", _ + True, DataSourceUpdateMode.OnPropertyChanged) + + ' Get the BindingManagerBase for this binding. + bmb = Me.BindingContext(set1, "Menu") + + End Sub + + Private Sub bmb_BindingComplete(ByVal sender As Object, ByVal e As BindingCompleteEventArgs) _ + Handles bmb.BindingComplete + + ' Check if the data source has been updated, and that no error has occurred. + If e.BindingCompleteContext = BindingCompleteContext.DataSourceUpdate _ + AndAlso e.Exception Is Nothing Then + + ' If not, end the current edit. + e.Binding.BindingManagerBase.EndCurrentEdit() + End If + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/VB/Form1.vb new file mode 100644 index 0000000000..6f3999b311 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.BindingSourceMultipleForms/VB/Form1.vb @@ -0,0 +1,139 @@ + ' +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Data + +Public Class MainForm + Inherits Form + + Public Sub New() + End Sub + + Private WithEvents bindingSource1 As BindingSource + Private WithEvents button1 As Button + + Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + InitializeData() + End Sub + + + Private Sub InitializeData() + bindingSource1 = New System.Windows.Forms.BindingSource() + Dim dataset1 As New DataSet() + ClientSize = New System.Drawing.Size(292, 266) + + ' Some xml data to populate the DataSet with. + ' Some xml data to populate the DataSet with. + Dim musicXml As String = "" & _ + "Dave Matthews" & _ + "Under the Table and Dreaming" & _ + "19943.5" & _ + "ColdplayX&Y" & _ + "20054" & _ + "Dave Matthews" & _ + "Live at Red Rocks" & _ + "19974" & _ + "U2" & _ + "Joshua Tree1987" & _ + "5" & _ + "U2" & _ + "How to Dismantle an Atomic Bomb" & _ + "20044.5" & _ + "Natalie Merchant" & _ + "Tigerlily1995" & _ + "3.5" & _ + "" + + ' Read the xml. + Dim reader As New System.IO.StringReader(musicXml) + dataset1.ReadXml(reader) + + ' Get a DataView of the table contained in the dataset. + Dim tables As DataTableCollection = dataset1.Tables + Dim view1 As New DataView(tables(0)) + + ' Create a DataGridView control and add it to the form. + Dim datagridview1 As New DataGridView() + datagridview1.ReadOnly = True + datagridview1.AutoGenerateColumns = True + datagridview1.Width = 300 + Me.Controls.Add(datagridview1) + bindingSource1.DataSource = view1 + datagridview1.DataSource = bindingSource1 + datagridview1.Columns.Remove("artist") + datagridview1.Columns.Remove("releaseDate") + + ' Create and add a button to the form. + button1 = New Button() + button1.AutoSize = True + button1.Text = "Show/Edit Details" + Me.Controls.Add(button1) + button1.Location = New Point(50, 200) + + End Sub + + ' Handle the BindingComplete event to ensure the two forms + ' remain synchronized. + Private Sub bindingSource1_BindingComplete(ByVal sender As Object, _ + ByVal e As BindingCompleteEventArgs) Handles bindingSource1.BindingComplete + If e.BindingCompleteContext = BindingCompleteContext.DataSourceUpdate _ + AndAlso e.Exception Is Nothing Then + e.Binding.BindingManagerBase.EndCurrentEdit() + End If + + End Sub + + ' The detailed form will be shown when the button is clicked. + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + + Dim detailForm As New DetailForm(bindingSource1) + detailForm.Show() + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New MainForm()) + + End Sub +End Class + +' The detail form class. +Public Class DetailForm + Inherits Form + Private formDataSource As BindingSource + + ' The constructor takes a BindingSource object. + Public Sub New(ByVal dataSource As BindingSource) + formDataSource = dataSource + Me.ClientSize = New Size(240, 200) + Dim textBox1 As New TextBox() + Me.Text = "Selection Details" + textBox1.Width = 220 + Dim textBox2 As New TextBox() + Dim textBox3 As New TextBox() + Dim textBox4 As New TextBox() + textBox4.Width = 30 + textBox3.Width = 50 + + ' Associate each text box with a column from the data source. + textBox1.DataBindings.Add("Text", formDataSource, "cd", _ + True, DataSourceUpdateMode.OnPropertyChanged) + + textBox2.DataBindings.Add("Text", formDataSource, "artist", True) + textBox3.DataBindings.Add("Text", formDataSource, "releaseDate", True) + textBox4.DataBindings.Add("Text", formDataSource, "rating", True) + textBox1.Location = New Point(10, 10) + textBox2.Location = New Point(10, 40) + textBox3.Location = New Point(10, 80) + textBox4.Location = New Point(10, 120) + Me.Controls.AddRange(New Control() {textBox1, textBox2, textBox3, _ + textBox4}) + + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/VB/Form1.vb new file mode 100644 index 0000000000..897f001129 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ButtonDoubleClick/VB/Form1.vb @@ -0,0 +1,69 @@ + ' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + + + +Public Class Form1 + Inherits Form + Private WithEvents button1 As DoubleClickButton + Private initialStyle As FormBorderStyle + + Public Sub New() + Me.SuspendLayout() + initialStyle = Me.FormBorderStyle + Me.ClientSize = New System.Drawing.Size(292, 266) + button1 = New DoubleClickButton() + button1.Location = New Point(40, 40) + button1.AutoSize = True + button1.Text = "Click or Double Click" + Me.Controls.Add(button1) + Me.Name = "Form1" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + + ' Handle the double click event. + Private Sub button1_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.DoubleClick + + ' Change the border style back to the initial style. + Me.FormBorderStyle = initialStyle + MessageBox.Show("Rolled back single click change.") + + End Sub + + + ' Handle the click event. + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + + Me.FormBorderStyle = FormBorderStyle.FixedToolWindow + + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' + +Public Class DoubleClickButton + Inherits Button + + Public Sub New() + ' Set the style so a double click event occurs. + SetStyle(ControlStyles.StandardClick Or ControlStyles.StandardDoubleClick, True) + + End Sub +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/VB/Form1.vb new file mode 100644 index 0000000000..007813282d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ChangeNotification/VB/Form1.vb @@ -0,0 +1,224 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Diagnostics +Imports System.Drawing +Imports System.Windows.Forms + +' +' This form demonstrates using a BindingSource to bind +' a list to a simple user control. The list does not +' raise change notifications, however the DemoCustomer type +' in the list does. In addition, an event is raised when the DataSource +' property of the user control changes. + +Public Class Form1 + Inherits System.Windows.Forms.Form + ' This button causes the value of a list element to be changed. + Private WithEvents changeItemBtn As New Button() + + ' This is the DataGridView control that displays the contents + ' of the list. + Private WithEvents customerControl1 As New CustomerControl() + + ' This is the BindingSource used to bind the list to the + ' DataGridView control. + Private customersBindingSource As New BindingSource() + + + Public Sub New() + ' Set up the "Change Item" button. + Me.changeItemBtn.Text = "Change Item" + Me.changeItemBtn.Dock = DockStyle.Bottom + Me.Controls.Add(Me.changeItemBtn) + + ' Set up the DataGridView. + customerControl1.Dock = DockStyle.Top + Me.Controls.Add(customerControl1) + Me.Size = New Size(800, 200) + + End Sub + + Private Sub customerControl1_DataSourceChanged(ByVal sender As [Object], ByVal e As EventArgs) + MessageBox.Show("Data Source has changed") + + End Sub + + + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ + Handles Me.Load + ' Create and populate the list of DemoCustomer objects + ' which will supply data to the control. + Dim customerList As New List(Of DemoCustomer) + + customerList.Add(DemoCustomer.CreateNewCustomer()) + customerList.Add(DemoCustomer.CreateNewCustomer()) + customerList.Add(DemoCustomer.CreateNewCustomer()) + + ' Bind the list to the BindingSource. + Me.customersBindingSource.DataSource = customerList + customerControl1.DataSource = customersBindingSource + + End Sub + + + ' This event handler changes the value of the CompanyName + ' property for the first item in the list. + Private Sub changeItemBtn_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles changeItemBtn.Click + + ' Get a reference to the list from the BindingSource. + Dim customerList As List(Of DemoCustomer) = _ + CType(customersBindingSource.DataSource, List(Of DemoCustomer)) + + ' Change the value of the CompanyName property for the + ' first item in the list. + customerList(0).CompanyName = "Tailspin Toys" + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class + +' +' +' This class implements a simple user control +' that demonstrates how to apply the propertyNameChanged pattern. + _ +Public Class CustomerControl + Inherits UserControl + Private dataGridView1 As DataGridView + Private label1 As Label + Private lastUpdate As DateTime = DateTime.Now + + Public DataSourceChanged As EventHandler + + + Public Property DataSource() As Object + Get + Return Me.dataGridView1.DataSource + End Get + Set + If DataSource IsNot Value Then + Me.dataGridView1.DataSource = Value + OnDataSourceChanged() + End If + End Set + End Property + + + Public Property DataMember() As String + Get + Return Me.dataGridView1.DataMember + End Get + Set + Me.dataGridView1.DataMember = value + End Set + End Property + + + Private Sub OnDataSourceChanged() + If (DataSourceChanged IsNot Nothing) Then + DataSourceChanged(Me, New EventArgs()) + End If + + End Sub + + + Public Sub New() + Me.dataGridView1 = New System.Windows.Forms.DataGridView() + Me.label1 = New System.Windows.Forms.Label() + Me.dataGridView1.ColumnHeadersHeightSizeMode = _ + System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.ImeMode = System.Windows.Forms.ImeMode.Disable + Me.dataGridView1.Location = New System.Drawing.Point(19, 55) + Me.dataGridView1.Size = New System.Drawing.Size(350, 150) + Me.dataGridView1.TabIndex = 1 + Me.label1.AutoSize = True + Me.label1.Location = New System.Drawing.Point(19, 23) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(76, 13) + Me.label1.TabIndex = 2 + Me.label1.Text = "Customer List:" + Me.Controls.Add(Me.label1) + Me.Controls.Add(Me.dataGridView1) + Me.Size = New System.Drawing.Size(350, 216) + End Sub +End Class +' +' +' This class implements a simple customer type +' that implements the IPropertyChange interface. + +Public Class DemoCustomer + Implements INotifyPropertyChanged + + ' These fields hold the values for the public properties. + Private idValue As Guid = Guid.NewGuid() + Private customerName As String = String.Empty + Private companyNameValue As String = String.Empty + Private phoneNumberValue As String = String.Empty + + Public Event PropertyChanged As PropertyChangedEventHandler _ + Implements INotifyPropertyChanged.PropertyChanged + + Private Sub NotifyPropertyChanged(ByVal info As String) + RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info)) + End Sub + + + ' The constructor is private to enforce the factory pattern. + Private Sub New() + customerName = "no data" + companyNameValue = "no data" + phoneNumberValue = "no data" + + End Sub + + + ' This is the public factory method. + Public Shared Function CreateNewCustomer() As DemoCustomer + Return New DemoCustomer() + + End Function + + ' This property represents an ID, suitable + ' for use as a primary key in a database. + Public ReadOnly Property ID() As Guid + Get + Return Me.idValue + End Get + End Property + + + Public Property CompanyName() As String + Get + Return Me.companyNameValue + End Get + Set + If value <> Me.companyNameValue Then + Me.companyNameValue = value + NotifyPropertyChanged("CompanyName") + End If + End Set + End Property + + Public Property PhoneNumber() As String + Get + Return Me.phoneNumberValue + End Get + Set + If value <> Me.phoneNumberValue Then + Me.phoneNumberValue = value + NotifyPropertyChanged("PhoneNumber") + End If + End Set + End Property +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb new file mode 100644 index 0000000000..d65f67f1f6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Clipboard/vb/form1.vb @@ -0,0 +1,184 @@ +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + ' + Public Class Customer + + Private nameValue As String = String.Empty + + Public Sub New(ByVal name As String) + nameValue = name + End Sub + + Public Property Name() As String + Get + Return nameValue + End Get + Set(ByVal value As String) + nameValue = value + End Set + End Property + + End Class + ' + + Public Sub New() + ' + Clipboard.Clear() + ' + End Sub + + ' + ' Demonstrates SetData, ContainsData, and GetData + ' using a custom format name and a business object. + Public ReadOnly Property TestCustomFormat() As Customer + Get + Clipboard.SetData("CustomerFormat", New Customer("Customer Name")) + + If Clipboard.ContainsData("CustomerFormat") Then + Return CType(Clipboard.GetData("CustomerFormat"), Customer) + End If + + Return Nothing + End Get + End Property + ' + + ' + ' Demonstrates how to use a DataObject to add + ' data to the Clipboard in multiple formats. + Public Sub TestClipboardMultipleFormats() + + Dim data As New DataObject() + + ' Add a Customer object using the type as the format. + data.SetData(New Customer("Customer as Customer object")) + + ' Add a ListViewItem object using a custom format name. + data.SetData("CustomFormat", _ + New ListViewItem("Customer as ListViewItem")) + + Clipboard.SetDataObject(data) + Dim retrievedData As DataObject = _ + CType(Clipboard.GetDataObject(), DataObject) + + If (retrievedData.GetDataPresent("CustomFormat")) Then + + Dim item As ListViewItem = _ + TryCast(retrievedData.GetData("CustomFormat"), ListViewItem) + + If item IsNot Nothing Then + MessageBox.Show(item.Text) + End If + + End If + + If retrievedData.GetDataPresent(GetType(Customer)) Then + + Dim customer As Customer = _ + CType(retrievedData.GetData(GetType(Customer)), Customer) + + If customer IsNot Nothing Then + + MessageBox.Show(customer.Name) + End If + + End If + + End Sub + ' + + ' + ' Demonstrates SetData, ContainsData, and GetData. + Public Function SwapClipboardFormattedData( _ + ByVal format As String, ByVal data As Object) As Object + + Dim returnObject As Object = Nothing + + If (Clipboard.ContainsData(format)) Then + returnObject = Clipboard.GetData(format) + Clipboard.SetData(format, data) + End If + + Return returnObject + + End Function + ' + + ' + ' + ' Demonstrates SetAudio, ContainsAudio, and GetAudioStream. + Public Function SwapClipboardAudio( _ + ByVal replacementAudioStream As System.IO.Stream) _ + As System.IO.Stream + + Dim returnAudioStream As System.IO.Stream = Nothing + + If (Clipboard.ContainsAudio()) Then + returnAudioStream = Clipboard.GetAudioStream() + Clipboard.SetAudio(replacementAudioStream) + End If + + Return returnAudioStream + + End Function + ' + + ' + ' Demonstrates SetFileDropList, ContainsFileDroList, and GetFileDropList + Public Function SwapClipboardFileDropList(ByVal replacementList _ + As System.Collections.Specialized.StringCollection) _ + As System.Collections.Specialized.StringCollection + + Dim returnList As System.Collections.Specialized.StringCollection _ + = Nothing + + If Clipboard.ContainsFileDropList() Then + + returnList = Clipboard.GetFileDropList() + Clipboard.SetFileDropList(replacementList) + End If + + Return returnList + + End Function + ' + + ' + ' Demonstrates SetImage, ContainsImage, and GetImage. + Public Function SwapClipboardImage( _ + ByVal replacementImage As System.Drawing.Image) _ + As System.Drawing.Image + + Dim returnImage As System.Drawing.Image = Nothing + + If Clipboard.ContainsImage() Then + returnImage = Clipboard.GetImage() + Clipboard.SetImage(replacementImage) + End If + + Return returnImage + End Function + ' + + ' + ' Demonstrates SetText, ContainsText, and GetText. + Public Function SwapClipboardHtmlText( _ + ByVal replacementHtmlText As String) As String + + Dim returnHtmlText As String = Nothing + + If (Clipboard.ContainsText(TextDataFormat.Html)) Then + returnHtmlText = Clipboard.GetText(TextDataFormat.Html) + Clipboard.SetText(replacementHtmlText, TextDataFormat.Html) + End If + + Return returnHtmlText + + End Function + ' + ' + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/COMForm.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/COMForm.vb new file mode 100644 index 0000000000..118f27728e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/COMForm.vb @@ -0,0 +1,62 @@ +' +' +Imports System.Windows.Forms +Imports System.Runtime.InteropServices +' + + _ +Public Class COMForm + +#Region "COM GUIDs" + ' These GUIDs provide the COM identity for this class + ' and its COM interfaces. If you change them, existing + ' clients will no longer be able to access the class. + Public Const ClassId As String = "1b49fe33-7c93-41ae-9dc7-8ac4d823286a" + Public Const InterfaceId As String = "11651e1f-6db0-4c9e-b644-dcb79e6de2f6" + Public Const EventsId As String = "7e61f977-b39d-47a6-8f34-f743c65ae3a3" +#End Region + + ' A creatable COM class must have a Public Sub New() + ' with no parameters, otherwise, the class will not be + ' registered in the COM registry and cannot be created + ' via CreateObject. + Public Sub New() + MyBase.New() + End Sub + + ' + Private WithEvents frmManager As FormManager + + Public Sub ShowForm1() + ' Call the StartForm method by using a new instance + ' of the Form1 class. + StartForm(New Form1) + End Sub + + Private Sub StartForm(ByVal frm As Form) + + ' This procedure is used to show all forms + ' that the client application requests. When the first form + ' is displayed, this code will create a new message + ' loop that runs on a new thread. The new form will + ' be treated as the main form. + + ' Later forms will be shown on the same message loop. + If IsNothing(frmManager) Then + frmManager = New FormManager(frm) + Else + frmManager.ShowForm(frm) + End If + End Sub + + Private Sub frmManager_MessageLoopExit() _ + Handles frmManager.MessageLoopExit + + 'Release the reference to the frmManager object. + frmManager = Nothing + + End Sub + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/Form1.vb new file mode 100644 index 0000000000..6f72223ba9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/Form1.vb @@ -0,0 +1,90 @@ +' +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + ' + Private Sub Button1_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles Button1.Click + MessageBox.Show("Clicked button") + End Sub + ' + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.TextBox1 = New System.Windows.Forms.TextBox + Me.TextBox2 = New System.Windows.Forms.TextBox + Me.TextBox3 = New System.Windows.Forms.TextBox + Me.Button1 = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + 'TextBox1 + ' + Me.TextBox1.Location = New System.Drawing.Point(12, 12) + Me.TextBox1.Name = "TextBox1" + Me.TextBox1.Size = New System.Drawing.Size(100, 20) + Me.TextBox1.TabIndex = 0 + ' + 'TextBox2 + ' + Me.TextBox2.Location = New System.Drawing.Point(12, 38) + Me.TextBox2.Name = "TextBox2" + Me.TextBox2.Size = New System.Drawing.Size(100, 20) + Me.TextBox2.TabIndex = 1 + ' + 'TextBox3 + ' + Me.TextBox3.Location = New System.Drawing.Point(12, 66) + Me.TextBox3.Name = "TextBox3" + Me.TextBox3.Size = New System.Drawing.Size(100, 20) + Me.TextBox3.TabIndex = 2 + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(12, 92) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(75, 23) + Me.Button1.TabIndex = 3 + Me.Button1.Text = "Command" + Me.Button1.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(132, 146) + Me.Controls.Add(Me.Button1) + Me.Controls.Add(Me.TextBox3) + Me.Controls.Add(Me.TextBox2) + Me.Controls.Add(Me.TextBox1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + Friend WithEvents TextBox1 As System.Windows.Forms.TextBox + Friend WithEvents TextBox2 As System.Windows.Forms.TextBox + Friend WithEvents TextBox3 As System.Windows.Forms.TextBox + Friend WithEvents Button1 As System.Windows.Forms.Button + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/FormManager.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/FormManager.vb new file mode 100644 index 0000000000..0b200039cd --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/FormManager.vb @@ -0,0 +1,62 @@ +' +Imports System.Runtime.InteropServices +Imports System.Threading +Imports System.Windows.Forms + + _ +Friend Class FormManager + ' This class is used so that you can generically pass any + ' form that you want to the delegate. + + Private WithEvents appContext As ApplicationContext + Private Delegate Sub FormShowDelegate(ByVal form As Form) + Event MessageLoopExit() + + Public Sub New(ByVal MainForm As Form) + Dim t As Thread + If IsNothing(appContext) Then + appContext = New ApplicationContext(MainForm) + t = New Thread(AddressOf StartMessageLoop) + t.IsBackground = True + t.SetApartmentState(ApartmentState.STA) + t.Start() + End If + End Sub + + Private Sub StartMessageLoop() + ' Call the Application.Run method to run the form on its own message loop. + Application.Run(appContext) + End Sub + + Public Sub ShowForm(ByVal form As Form) + + Dim formShow As FormShowDelegate + + ' Start the main form first. Otherwise, focus will stay on the + ' calling form. + appContext.MainForm.Activate() + + ' Create a new instance of the FormShowDelegate method, and + ' then invoke the delegate off the MainForm object. + formShow = New FormShowDelegate( _ + AddressOf ShowFormOnMainForm_MessageLoop) + + appContext.MainForm.Invoke(formShow, New Object() {form}) + End Sub + + Private Sub ShowFormOnMainForm_MessageLoop(ByVal form As Form) + form.Show() + End Sub + + Private Sub ac_ThreadExit( _ + ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles appContext.ThreadExit + appContext.MainForm.Dispose() + appContext.MainForm = Nothing + appContext.Dispose() + appContext = Nothing + RaiseEvent MessageLoopExit() + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/makefile new file mode 100644 index 0000000000..fe9fabc6ce --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ComInterop/VB/makefile @@ -0,0 +1,5 @@ +ComForm.dll: Form1.vb FormManager.vb COMForm.vb + vbc /t:library /r:System.dll,System.Drawing.dll,System.Windows.Forms.dll /out:ComForm.dll Form1.vb FormManager.vb COMForm.vb + +clean: + del *.dll *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/VB/form1.vb new file mode 100644 index 0000000000..1ca9e23732 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ContextMenuStrip/VB/form1.vb @@ -0,0 +1,140 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + Private toolStripButton1 As ToolStripButton + Private toolStripButton2 As ToolStripButton + Private toolStripButton3 As ToolStripButton + Private contextMenuStrip1 As ContextMenuStrip + Private components As IContainer + Private toolStripMenuItem1 As ToolStripMenuItem + Private toolStripMenuItem2 As ToolStripMenuItem + Private contextMenuStrip2 As ContextMenuStrip + Private rearrangeButtonsToolStripMenuItem As ToolStripMenuItem + Private selectIconsToolStripMenuItem As ToolStripMenuItem + Private toolStrip1 As ToolStrip + + + Public Sub New() + InitializeComponent() + End Sub + + _ + Public Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container() + Dim resources As New System.ComponentModel.ComponentResourceManager(GetType(Form1)) + Me.toolStrip1 = New System.Windows.Forms.ToolStrip() + Me.toolStripButton1 = New System.Windows.Forms.ToolStripButton() + Me.toolStripButton2 = New System.Windows.Forms.ToolStripButton() + Me.toolStripButton3 = New System.Windows.Forms.ToolStripButton() + Me.contextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components) + Me.contextMenuStrip2 = New System.Windows.Forms.ContextMenuStrip(Me.components) + Me.toolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem() + Me.toolStripMenuItem2 = New System.Windows.Forms.ToolStripMenuItem() + Me.rearrangeButtonsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() + Me.selectIconsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() + Me.toolStrip1.SuspendLayout() + Me.contextMenuStrip1.SuspendLayout() + Me.contextMenuStrip2.SuspendLayout() + Me.SuspendLayout() + ' + ' + ' Associate contextMenuStrip2 with toolStrip1. + ' toolStrip1 property settings follow. + ' + Me.toolStrip1.ContextMenuStrip = Me.contextMenuStrip2 + Me.toolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.toolStripButton1, Me.toolStripButton2, Me.toolStripButton3}) + Me.toolStrip1.Location = New System.Drawing.Point(0, 0) + Me.toolStrip1.Name = "toolStrip1" + Me.toolStrip1.Size = New System.Drawing.Size(292, 25) + Me.toolStrip1.TabIndex = 0 + Me.toolStrip1.Text = "toolStrip1" + ' + ' + ' toolStripButton1 + ' + Me.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image + Me.toolStripButton1.Image = CType(resources.GetObject("toolStripButton1.Image"), System.Drawing.Image) + Me.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta + Me.toolStripButton1.Name = "toolStripButton1" + Me.toolStripButton1.Text = "toolStripButton1" + ' + ' toolStripButton2 + ' + Me.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image + Me.toolStripButton2.Image = CType(resources.GetObject("toolStripButton2.Image"), System.Drawing.Image) + Me.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta + Me.toolStripButton2.Name = "toolStripButton2" + Me.toolStripButton2.Text = "toolStripButton2" + ' + ' toolStripButton3 + ' + Me.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image + Me.toolStripButton3.Image = CType(resources.GetObject("toolStripButton3.Image"), System.Drawing.Image) + Me.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta + Me.toolStripButton3.Name = "toolStripButton3" + Me.toolStripButton3.Text = "toolStripButton3" + ' + ' contextMenuStrip1 + ' + Me.contextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.toolStripMenuItem1, Me.toolStripMenuItem2}) + Me.contextMenuStrip1.Name = "contextMenuStrip1" + Me.contextMenuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.No + Me.contextMenuStrip1.Size = New System.Drawing.Size(131, 48) + ' + ' contextMenuStrip2 + ' + Me.contextMenuStrip2.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.rearrangeButtonsToolStripMenuItem, Me.selectIconsToolStripMenuItem}) + Me.contextMenuStrip2.Name = "contextMenuStrip2" + Me.contextMenuStrip2.RightToLeft = System.Windows.Forms.RightToLeft.No + Me.contextMenuStrip2.Size = New System.Drawing.Size(162, 48) + ' + ' toolStripMenuItem1 + ' + Me.toolStripMenuItem1.Name = "toolStripMenuItem1" + Me.toolStripMenuItem1.Text = "&Resize" + ' + ' toolStripMenuItem2 + ' + Me.toolStripMenuItem2.Name = "toolStripMenuItem2" + Me.toolStripMenuItem2.Text = "&Keep on Top" + ' + ' rearrangeButtonsToolStripMenuItem + ' + Me.rearrangeButtonsToolStripMenuItem.Name = "rearrangeButtonsToolStripMenuItem" + Me.rearrangeButtonsToolStripMenuItem.Text = "R&earrange Buttons" + ' + ' selectIconsToolStripMenuItem + ' + Me.selectIconsToolStripMenuItem.Name = "selectIconsToolStripMenuItem" + Me.selectIconsToolStripMenuItem.Text = "&Select Icons" + ' + ' + ' Associate contextMenuStrip1 with Form1. + ' Form1 property settings follow. + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.ContextMenuStrip = Me.contextMenuStrip1 + Me.Controls.Add(toolStrip1) + Me.Name = "Form1" + Me.toolStrip1.ResumeLayout(False) + Me.contextMenuStrip1.ResumeLayout(False) + Me.contextMenuStrip2.ResumeLayout(False) + Me.ResumeLayout(False) + Me.PerformLayout() + End Sub + ' + + ' +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb new file mode 100644 index 0000000000..4abdc9c9a1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.CurrencyManagerReset/VB/Form1.vb @@ -0,0 +1,214 @@ + ' +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + + + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeControlsAndDataSource() + + End Sub + + ' Declare the controls to be used. + Private WithEvents bindingSource1 As BindingSource + Private dataGridView1 As DataGridView + Private WithEvents button1 As Button + Private dataGridView2 As DataGridView + Private cachePositionCheckBox As CheckBox + Public set1 As DataSet + + + Private Sub InitializeControlsAndDataSource() + ' Initialize the controls and set location, size and + ' other basic properties. + Me.dataGridView1 = New DataGridView() + Me.bindingSource1 = New BindingSource() + Me.button1 = New Button() + Me.dataGridView2 = New DataGridView() + Me.cachePositionCheckBox = New System.Windows.Forms.CheckBox() + Me.dataGridView1.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView1.Dock = DockStyle.Top + Me.dataGridView1.Location = New Point(0, 20) + Me.dataGridView1.Size = New Size(292, 170) + Me.button1.Location = New System.Drawing.Point(18, 175) + Me.button1.Size = New System.Drawing.Size(125, 23) + + button1.Text = "Clear Parent Field" + + Me.dataGridView2.ColumnHeadersHeightSizeMode = _ + System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize + Me.dataGridView2.Location = New System.Drawing.Point(0, 225) + Me.dataGridView2.Size = New System.Drawing.Size(309, 130) + Me.cachePositionCheckBox.AutoSize = True + Me.cachePositionCheckBox.Checked = True + Me.cachePositionCheckBox.Location = New System.Drawing.Point(150, 175) + Me.cachePositionCheckBox.Name = "radioButton1" + Me.cachePositionCheckBox.Size = New System.Drawing.Size(151, 17) + Me.cachePositionCheckBox.Text = "Cache and restore position" + Me.ClientSize = New System.Drawing.Size(325, 420) + Me.Controls.Add(Me.dataGridView1) + Me.Controls.Add(Me.cachePositionCheckBox) + Me.Controls.Add(Me.dataGridView2) + Me.Controls.Add(Me.button1) + + ' Initialize the data. + set1 = InitializeDataSet() + + ' Set the data source to the DataSet. + bindingSource1.DataSource = set1 + + 'Set the DataMember to the Menu table. + bindingSource1.DataMember = "Customers" + + ' Add the control data bindings. + dataGridView1.DataSource = bindingSource1 + + ' Set the data source and member for the second DataGridView. + dataGridView2.DataSource = bindingSource1 + dataGridView2.DataMember = "custOrders" + + ' Get the currency manager for the customer orders binding. + Dim relatedCM As CurrencyManager = _ + bindingSource1.GetRelatedCurrencyManager("custOrders") + + ' Handle the two events for caching and resetting the position. + AddHandler relatedCM.ListChanged, AddressOf relatedCM_ListChanged + AddHandler relatedCM.PositionChanged, AddressOf relatedCM_PositionChanged + + ' Set the position in the child table for demonstration purposes. + relatedCM.Position = 3 + + ' Set cacheing to true in case current changed event + ' occurred on set up. + cacheChildPosition = True + + + End Sub + + + + ' Establish the data set with two tables and a relationship + ' between them. + Private Function InitializeDataSet() As DataSet + set1 = New DataSet() + ' Declare the DataSet and add a table and column. + set1.Tables.Add("Customers") + set1.Tables(0).Columns.Add("CustomerID") + set1.Tables(0).Columns.Add("Customer Name") + set1.Tables(0).Columns.Add("Contact Name") + + ' Add some rows to the table. + set1.Tables("Customers").Rows.Add("c1", "Fabrikam, Inc.", _ + "Ellen Adams") + set1.Tables(0).Rows.Add("c2", "Lucerne Publishing", "Don Hall") + set1.Tables(0).Rows.Add("c3", "Northwind Traders", "Lori Penor") + set1.Tables(0).Rows.Add("c4", "Tailspin Toys", "Michael Patten") + set1.Tables(0).Rows.Add("c5", "Woodgrove Bank", "Jyothi Pai") + + ' Declare the DataSet and add a table and column. + set1.Tables.Add("Orders") + set1.Tables(1).Columns.Add("CustomerID") + set1.Tables(1).Columns.Add("OrderNo") + set1.Tables(1).Columns.Add("OrderDate") + + ' Add some rows to the table. + set1.Tables(1).Rows.Add("c1", "119", "10/04/2006") + set1.Tables(1).Rows.Add("c1", "149", "10/10/2006") + set1.Tables(1).Rows.Add("c1", "159", "10/12/2006") + set1.Tables(1).Rows.Add("c2", "169", "10/10/2006") + set1.Tables(1).Rows.Add("c2", "179", "10/10/2006") + set1.Tables(1).Rows.Add("c2", "189", "10/12/2006") + set1.Tables(1).Rows.Add("c3", "122", "10/04/2006") + set1.Tables(1).Rows.Add("c4", "130", "10/10/2006") + set1.Tables(1).Rows.Add("c5", "1.29", "10/14/2006") + + Dim dr As New DataRelation("custOrders", _ + set1.Tables("Customers").Columns("CustomerID"), _ + set1.Tables("Orders").Columns("CustomerID")) + set1.Relations.Add(dr) + Return set1 + + End Function ' + ' + Private cachedPosition As Integer = - 1 + Private cacheChildPosition As Boolean = True + + ' + ' + Private Sub relatedCM_ListChanged(ByVal sender As Object, _ + ByVal e As ListChangedEventArgs) + ' Check to see if this is a caching situation. + If cacheChildPosition AndAlso cachePositionCheckBox.Checked Then + ' If so, check to see if it is a reset situation, and the current + ' position is greater than zero. + Dim relatedCM As CurrencyManager = sender + If e.ListChangedType = ListChangedType.Reset _ + AndAlso relatedCM.Position > 0 Then + + ' If so, cache the position of the child table. + cachedPosition = relatedCM.Position + End If + End If + + End Sub + ' + + ' + ' Handle the current changed event. This event occurs when + ' the current item is changed, but not when a field of the current + ' item is changed. + Private Sub bindingSource1_CurrentChanged(ByVal sender As Object, _ + ByVal e As EventArgs) Handles bindingSource1.CurrentChanged + ' If the CurrentChanged event occurs, this is not a caching + ' situation. + cacheChildPosition = False + + End Sub + ' + + ' + Private Sub relatedCM_PositionChanged(ByVal sender As Object, ByVal e As EventArgs) + ' Check to see if this is a caching situation. + If cacheChildPosition AndAlso cachePositionCheckBox.Checked Then + Dim relatedCM As CurrencyManager = sender + + ' If so, check to see if the current position is + ' not equal to the cached position and the cached + ' position is not out of bounds. + If relatedCM.Position <> cachedPosition AndAlso _ + cachedPosition > 0 AndAlso cachedPosition < _ + relatedCM.Count Then + relatedCM.Position = cachedPosition + cachedPosition = -1 + End If + End If + End Sub + ' + + Private count As Integer = 0 + + Private Sub button1_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles button1.Click + ' For demo purposes--modifies a value in the first row of the + ' parent table. + Dim row1 As DataRow = set1.Tables(0).Rows(0) + row1(1) = DBNull.Value + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + + End Sub +End Class + +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/VB/form1.vb new file mode 100644 index 0000000000..f4d1805533 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.AddingNew/VB/form1.vb @@ -0,0 +1,143 @@ + ' +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Data.SqlClient +Imports System.Windows.Forms +' + +' +' This form demonstrates using a BindingSource to provide +' data from a collection of custom types to a DataGridView control. +Public Class Form1 + Inherits System.Windows.Forms.Form + + ' + ' This is the BindingSource that will provide data for + ' the DataGridView control. + Private WithEvents customersBindingSource As New BindingSource() + + ' This is the DataGridView control that will display our data. + Private customersDataGridView As New DataGridView() + + ' Set up the StatusBar for displaying ListChanged events. + Private status As New StatusBar() + ' + + ' + Public Sub New() + + ' Set up the form. + Me.Size = New Size(800, 800) + AddHandler Me.Load, AddressOf Form1_Load + Me.Controls.Add(status) + + ' Set up the DataGridView control. + Me.customersDataGridView.Dock = DockStyle.Fill + Me.Controls.Add(customersDataGridView) + + End Sub + ' + + ' + Private Sub Form1_Load( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) + + ' Add a DemoCustomer to cause a row to be displayed. + Me.customersBindingSource.AddNew() + + ' Bind the BindingSource to the DataGridView + ' control's DataSource. + Me.customersDataGridView.DataSource = Me.customersBindingSource + + End Sub + ' + + ' + ' This event handler provides custom item-creation behavior. + Private Sub customersBindingSource_AddingNew( _ + ByVal sender As Object, _ + ByVal e As AddingNewEventArgs) _ + Handles customersBindingSource.AddingNew + + e.NewObject = DemoCustomer.CreateNewCustomer() + + End Sub + ' + + ' + ' This event handler detects changes in the BindingSource + ' list or changes to items within the list. + Private Sub customersBindingSource_ListChanged( _ + ByVal sender As Object, _ + ByVal e As ListChangedEventArgs) _ + Handles customersBindingSource.ListChanged + + status.Text = e.ListChangedType.ToString() + + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' + +' +' This class implements a simple customer type. +Public Class DemoCustomer + + ' These fields hold the values for the public properties. + Private idValue As Guid = Guid.NewGuid() + Private customerName As String = String.Empty + Private companyNameValue As String = String.Empty + Private phoneNumberValue As String = String.Empty + + ' The constructor is private to enforce the factory pattern. + Private Sub New() + customerName = "no data" + companyNameValue = "no data" + phoneNumberValue = "no data" + End Sub + + ' This is the public factory method. + Public Shared Function CreateNewCustomer() As DemoCustomer + Return New DemoCustomer() + End Function + + ' This property represents an ID, suitable + ' for use as a primary key in a database. + Public ReadOnly Property ID() As Guid + Get + Return Me.idValue + End Get + End Property + + Public Property CompanyName() As String + Get + Return Me.companyNameValue + End Get + + Set(ByVal value As String) + Me.companyNameValue = Value + End Set + End Property + + Public Property PhoneNumber() As String + Get + Return Me.phoneNumberValue + End Get + + Set(ByVal value As String) + Me.phoneNumberValue = Value + End Set + End Property +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/VB/form1.vb new file mode 100644 index 0000000000..fdc390007c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindToFactory/VB/form1.vb @@ -0,0 +1,128 @@ + ' +' +Imports System.Collections +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Data.Common +Imports System.Diagnostics +Imports System.Drawing +Imports System.Data.SqlClient +Imports System.Windows.Forms + +' +' +' This form demonstrates using a BindingSource to bind to a factory +' object. + +Public Class Form1 + Inherits System.Windows.Forms.Form + ' + ' This is the TextBox for entering CustomerID values. + Private WithEvents customerIdTextBox As New TextBox() + + ' This is the DataGridView that displays orders for the + ' specified customer. + Private customersDataGridView As New DataGridView() + + ' This is the BindingSource for binding the database query + ' result set to the DataGridView. + Private ordersBindingSource As New BindingSource() + + ' + ' + Public Sub New() + + ' Set up the CustomerID TextBox. + Me.customerIdTextBox.Location = New Point(100, 200) + Me.customerIdTextBox.Size = New Size(500, 30) + Me.customerIdTextBox.Text = _ + "Enter a valid Northwind CustomerID, for example: ALFKI," & _ + " then RETURN or click outside the TextBox" + Me.Controls.Add(Me.customerIdTextBox) + + ' Set up the DataGridView. + customersDataGridView.Dock = DockStyle.Top + Me.Controls.Add(customersDataGridView) + + ' Set up the form. + Me.Size = New Size(800, 500) + End Sub + + ' + ' + ' This event handler binds the BindingSource to the DataGridView + ' control's DataSource property. + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Me.Load + + ' Attach the BindingSource to the DataGridView. + Me.customersDataGridView.DataSource = Me.ordersBindingSource + + End Sub + + ' + ' + ' This is a static factory method. It queries the Northwind + ' database for the orders belonging to the specified + ' customer and returns an IEnumerable. + Public Shared Function GetOrdersByCustomerId(ByVal id As String) _ + As IEnumerable + + ' Open a connection to the database. + Dim connectString As String = "Integrated Security=SSPI;" & _ + "Persist Security Info=False;Initial Catalog=Northwind;" & _ + "Data Source= localhost" + Dim connection As New SqlConnection() + + connection.ConnectionString = connectString + connection.Open() + + ' Execute the query. + Dim queryString As String = _ + String.Format("Select * From Orders where CustomerID = '{0}'", id) + Dim command As New SqlCommand(queryString, connection) + Dim reader As SqlDataReader = _ + command.ExecuteReader(CommandBehavior.CloseConnection) + Return reader + + End Function + + ' + ' + ' These event handlers are called when the user tabs or clicks + ' out of the customerIdTextBox or hits the return key. + ' The database is then queried with the CustomerID + ' in the customerIdTextBox.Text property. + Private Sub customerIdTextBox_Leave(ByVal sender As Object, _ + ByVal e As EventArgs) Handles customerIdTextBox.Leave + + ' Attach the data source to the BindingSource control. + Me.ordersBindingSource.DataSource = _ + GetOrdersByCustomerId(Me.customerIdTextBox.Text) + + End Sub + + + Private Sub customerIdTextBox_KeyDown(ByVal sender As Object, _ + ByVal e As KeyEventArgs) Handles customerIdTextBox.KeyDown + + If e.KeyCode = Keys.Return Then + + ' Attach the data source to the BindingSource control. + Me.ordersBindingSource.DataSource = _ + GetOrdersByCustomerId(Me.customerIdTextBox.Text) + End If + + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/VB/form1.vb new file mode 100644 index 0000000000..57f22749c0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.BindingToType/VB/form1.vb @@ -0,0 +1,92 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Windows.Forms + +Class Form1 + Inherits Form + Private bSource As New BindingSource() + Private WithEvents button1 As Button + Private dgv As New DataGridView() + + Public Sub New() + Me.button1 = New System.Windows.Forms.Button() + Me.button1.Location = New System.Drawing.Point(140, 326) + Me.button1.Name = "button1" + Me.button1.AutoSize = True + Me.button1.Text = "Add Customer" + Me.ClientSize = New System.Drawing.Size(362, 370) + Me.Controls.Add(Me.button1) + + ' Bind the BindingSource to the DemoCustomer type. + bSource.DataSource = GetType(DemoCustomer) + + ' Set up the DataGridView control. + dgv.Dock = DockStyle.Top + Me.Controls.Add(dgv) + + ' Bind the DataGridView control to the BindingSource. + dgv.DataSource = bSource + + End Sub + + Public Shared Sub Main() + Application.Run(New Form1()) + + End Sub + + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + bSource.Add(New DemoCustomer(DateTime.Today)) + + End Sub +End Class + +' This simple class is used to demonstrate binding to a type. +Public Class DemoCustomer + + Public Sub New() + idValue = Guid.NewGuid() + End Sub + + Public Sub New(ByVal FirstOrderDate As DateTime) + FirstOrder = FirstOrderDate + idValue = Guid.NewGuid() + End Sub + + ' These fields hold the data that backs the public properties. + Private firstOrderDateValue As DateTime + Private idValue As Guid + Private custNameValue As String + + Public Property CustomerName() As String + Get + Return custNameValue + End Get + Set(ByVal value As String) + custNameValue = value + End Set + End Property + + ' This is a property that represents the first order date. + Public Property FirstOrder() As DateTime + Get + Return Me.firstOrderDateValue + End Get + Set(ByVal value As DateTime) + If value <> Me.firstOrderDateValue Then + Me.firstOrderDateValue = value + End If + End Set + End Property + + ' This is a property that represents a customer ID. + Public ReadOnly Property ID() As Guid + Get + Return Me.idValue + End Get + End Property +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/VB/form1.vb new file mode 100644 index 0000000000..145363c47f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetBindings/VB/form1.vb @@ -0,0 +1,121 @@ + ' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms +Imports System.Collections + + +Class Form1 + Inherits Form + + ' Declare the objects on the form. + Private label1 As Label + Private label2 As Label + Private textBox1 As TextBox + Private textBox2 As TextBox + Private WithEvents button1 As Button + Private bindingSource1 As BindingSource + Private states As ArrayList + + Public Sub New() + + ' Basic form setup. + Me.button1 = New System.Windows.Forms.Button() + Me.textBox1 = New System.Windows.Forms.TextBox() + Me.label1 = New System.Windows.Forms.Label() + Me.label2 = New System.Windows.Forms.Label() + Me.textBox2 = New System.Windows.Forms.TextBox() + Me.button1.Location = New System.Drawing.Point(12, 18) + Me.button1.Size = New System.Drawing.Size(119, 38) + Me.button1.Text = "RemoveAt(0)" + Me.textBox1.Location = New System.Drawing.Point(55, 75) + Me.textBox1.ReadOnly = True + Me.textBox1.Size = New System.Drawing.Size(119, 20) + Me.label1.Location = New System.Drawing.Point(12, 110) + Me.label1.Size = New System.Drawing.Size(43, 14) + Me.label1.Text = "Capital:" + Me.label2.Location = New System.Drawing.Point(12, 78) + Me.label2.Size = New System.Drawing.Size(34, 14) + Me.label2.Text = "State:" + Me.textBox2.Location = New System.Drawing.Point(55, 110) + Me.textBox2.Size = New System.Drawing.Size(119, 20) + Me.textBox2.ReadOnly = True + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.textBox2) + Me.Controls.Add(Me.label2) + Me.Controls.Add(Me.label1) + Me.Controls.Add(Me.textBox1) + Me.Controls.Add(Me.button1) + Me.Text = "Form1" + + ' Create an ArrayList containing some of the State objects. + states = New ArrayList() + states.Add(New State("California", "Sacramento")) + states.Add(New State("Oregon", "Salem")) + states.Add(New State("Washington", "Olympia")) + states.Add(New State("Idaho", "Boise")) + states.Add(New State("Utah", "Salt Lake City")) + states.Add(New State("Hawaii", "Honolulu")) + states.Add(New State("Colorado", "Denver")) + states.Add(New State("Montana", "Helena")) + + bindingSource1 = New BindingSource() + + ' Bind BindingSource1 to the list of states. + bindingSource1.DataSource = states + + ' Bind the two text boxes to properties of State. + textBox1.DataBindings.Add("Text", bindingSource1, "Name") + textBox2.DataBindings.Add("Text", bindingSource1, "Capital") + + End Sub + ' + + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + + ' If items remain in the list, remove the first item. + If states.Count > 0 Then + states.RemoveAt(0) + + ' Call ResetBindings to update the textboxes. + bindingSource1.ResetBindings(False) + End If + + End Sub + + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + ' The State class to add to the ArrayList. + Private Class State + Private stateName As String + + Public ReadOnly Property Name() As String + Get + Return stateName + End Get + End Property + + Private stateCapital As String + + Public ReadOnly Property Capital() As String + Get + Return stateCapital + End Get + End Property + + Public Sub New(ByVal name As String, ByVal capital As String) + stateName = name + stateCapital = capital + + End Sub + End Class +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/VB/form1.vb new file mode 100644 index 0000000000..541c67f8f5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnector.ResetItem/VB/form1.vb @@ -0,0 +1,145 @@ +' +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Diagnostics +Imports System.Drawing +Imports System.Windows.Forms +' + +' +' This form demonstrates using a BindingSource to bind +' a list to a DataGridView control. The list does not +' raise change notifications, so the ResetItem method +' on the BindingSource is used. +Public Class Form1 + Inherits System.Windows.Forms.Form + + ' + ' This button causes the value of a list element to be changed. + Private WithEvents changeItemBtn As New Button() + + ' This is the DataGridView control that displays the contents + ' of the list. + Private customersDataGridView As New DataGridView() + + ' This is the BindingSource used to bind the list to the + ' DataGridView control. + Private WithEvents customersBindingSource As New BindingSource() + ' + + ' + Public Sub New() + ' Set up the "Change Item" button. + Me.changeItemBtn.Text = "Change Item" + Me.changeItemBtn.Dock = DockStyle.Bottom + Me.Controls.Add(Me.changeItemBtn) + + ' Set up the DataGridView. + customersDataGridView.Dock = DockStyle.Top + Me.Controls.Add(customersDataGridView) + Me.Size = New Size(800, 200) + End Sub + ' + + ' + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Me.Load + ' Create and populate the list of DemoCustomer objects + ' which will supply data to the DataGridView. + Dim customerList As List(Of DemoCustomer) = _ + New List(Of DemoCustomer) + customerList.Add(DemoCustomer.CreateNewCustomer()) + customerList.Add(DemoCustomer.CreateNewCustomer()) + customerList.Add(DemoCustomer.CreateNewCustomer()) + + ' Bind the list to the BindingSource. + Me.customersBindingSource.DataSource = customerList + + ' Attach the BindingSource to the DataGridView. + Me.customersDataGridView.DataSource = Me.customersBindingSource + End Sub + ' + + ' + ' This event handler changes the value of the CompanyName + ' property for the first item in the list. + Private Sub changeItemBtn_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles changeItemBtn.Click + + ' Get a reference to the list from the BindingSource. + Dim customerList As List(Of DemoCustomer) = _ + CType(Me.customersBindingSource.DataSource, List(Of DemoCustomer)) + + ' Change the value of the CompanyName property for the + ' first item in the list. + customerList(0).CompanyName = "Tailspin Toys" + + ' Call ResetItem to alert the BindingSource that the + ' list has changed. + Me.customersBindingSource.ResetItem(0) + + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' + +' +' This class implements a simple customer type. +Public Class DemoCustomer + + ' These fields hold the values for the public properties. + Private idValue As Guid = Guid.NewGuid() + Private customerName As String = String.Empty + Private companyNameValue As String = String.Empty + Private phoneNumberValue As String = String.Empty + + ' The constructor is private to enforce the factory pattern. + Private Sub New() + customerName = "no data" + companyNameValue = "no data" + phoneNumberValue = "no data" + End Sub + + ' This is the public factory method. + Public Shared Function CreateNewCustomer() As DemoCustomer + Return New DemoCustomer() + End Function + + ' This property represents an ID, suitable + ' for use as a primary key in a database. + Public ReadOnly Property ID() As Guid + Get + Return Me.idValue + End Get + End Property + + Public Property CompanyName() As String + Get + Return Me.companyNameValue + End Get + + Set(ByVal value As String) + Me.companyNameValue = Value + End Set + End Property + + + Public Property PhoneNumber() As String + Get + Return Me.phoneNumberValue + End Get + + Set(ByVal value As String) + Me.phoneNumberValue = Value + End Set + End Property +End Class +' +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/VB/form1.vb new file mode 100644 index 0000000000..d48c3eb33a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorBindingComplete/VB/form1.vb @@ -0,0 +1,142 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Class Form1 + Inherits Form + + Private BindingSource1 As New BindingSource() + Private textBox1 As New TextBox() + Private textBox2 As New TextBox() + Private textBox3 As New TextBox() + + Public Sub New() + + 'Set up the textbox controls. + Me.textBox1.Location = New System.Drawing.Point(82, 13) + Me.textBox1.TabIndex = 1 + Me.textBox2.Location = New System.Drawing.Point(81, 47) + Me.textBox2.TabIndex = 2 + Me.textBox3.Location = New System.Drawing.Point(81, 83) + Me.textBox3.TabIndex = 3 + + ' Add the textbox controls to the form + Me.Controls.Add(Me.textBox2) + Me.Controls.Add(Me.textBox1) + Me.Controls.Add(Me.textBox3) + + End Sub + + ' + Private WithEvents partNameBinding As Binding + Private WithEvents partNumberBinding As Binding + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + ' Set the DataSource of BindingSource1 to the Part type. + BindingSource1.DataSource = GetType(Part) + + ' Bind the textboxes to the properties of the Part type, + ' enabling formatting. + partNameBinding = textBox1.DataBindings.Add("Text", BindingSource1, _ + "PartName", True) + partNumberBinding = textBox2.DataBindings.Add("Text", BindingSource1, _ + "PartNumber", True) + + 'Bind the textbox to the PartPrice value with currency formatting. + textBox3.DataBindings.Add("Text", BindingSource1, "PartPrice", _ + True, DataSourceUpdateMode.OnPropertyChanged, 0, "C") + + ' Add a new part to BindingSource1. + BindingSource1.Add(New Part("Widget", 1234, 12.45)) + End Sub + + ' Handle the BindingComplete event to catch errors and exceptions + ' in binding process. + Sub partNumberBinding_BindingComplete(ByVal sender As Object, _ + ByVal e As BindingCompleteEventArgs) _ + Handles partNumberBinding.BindingComplete + + If Not e.BindingCompleteState = BindingCompleteState.Success Then + MessageBox.Show("partNumberBinding: " + e.ErrorText) + End If + + End Sub + + ' Handle the BindingComplete event to catch errors and exceptions + ' in binding process. + Sub partNameBinding_BindingComplete(ByVal sender As Object, _ + ByVal e As BindingCompleteEventArgs) _ + Handles partNameBinding.BindingComplete + + If Not e.BindingCompleteState = BindingCompleteState.Success Then + MessageBox.Show("partNameBinding: " + e.ErrorText) + End If + + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class + +' +' Represents a business object that throws exceptions when invalid +' values are entered for some of its properties. +Public Class Part + Private name As String + Private number As Integer + Private price As Double + + Public Sub New(ByVal name As String, ByVal number As Integer, _ + ByVal price As Double) + + PartName = name + PartNumber = number + PartPrice = price + End Sub + + + Public Property PartName() As String + Get + Return name + End Get + Set(ByVal value As String) + If Value.Length <= 0 Then + Throw New Exception("Each part must have a name.") + Else + name = Value + End If + End Set + End Property + + Public Property PartPrice() As Double + Get + Return price + End Get + Set(ByVal value As Double) + price = Value + End Set + End Property + + Public Property PartNumber() As Integer + Get + Return number + End Get + Set(ByVal value As Integer) + If Value < 100 Then + Throw New Exception("Invalid part number." _ + & " Part numbers must be greater than 100.") + Else + number = Value + End If + End Set + End Property +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/VB/form1.vb new file mode 100644 index 0000000000..8d9628a165 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorFilterAndSort/VB/form1.vb @@ -0,0 +1,192 @@ + +#Region "Using directives" + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Data.SqlClient +Imports System.Drawing +Imports System.Windows.Forms + + +#End Region + + +Class Form1 + Inherits Form + + + + Private BindingSource1 As BindingSource + Private dataGridView1 As DataGridView + Private WithEvents button1 As Button + Private label1 As Label + Private label2 As Label + + + Private components As IContainer + + + Public Sub New() + InitializeComponent() + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container() + Me.BindingSource1 = New System.Windows.Forms.BindingSource(Me.components) + Me.dataGridView1 = New System.Windows.Forms.DataGridView() + Me.button1 = New System.Windows.Forms.Button() + Me.label1 = New System.Windows.Forms.Label() + Me.label2 = New System.Windows.Forms.Label() + CType(Me.BindingSource1, System.ComponentModel.ISupportInitialize).BeginInit() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + ' dataGridView1 + ' + Me.dataGridView1.Dock = System.Windows.Forms.DockStyle.Bottom + Me.dataGridView1.Location = New System.Drawing.Point(0, 100) + Me.dataGridView1.Name = "dataGridView1" + Me.dataGridView1.Size = New System.Drawing.Size(292, 166) + Me.dataGridView1.TabIndex = 0 + ' + ' button1 + ' + Me.button1.Location = New System.Drawing.Point(12, 39) + Me.button1.Name = "button1" + Me.button1.TabIndex = 1 + Me.button1.Text = "button1" + ' + ' label1 + ' + Me.label1.AutoSize = True + Me.label1.Location = New System.Drawing.Point(112, 48) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(35, 14) + Me.label1.TabIndex = 3 + Me.label1.Text = "label1" + ' + ' label2 + ' + Me.label2.AutoSize = True + Me.label2.Location = New System.Drawing.Point(112, 67) + Me.label2.Name = "label2" + Me.label2.Size = New System.Drawing.Size(35, 14) + Me.label2.TabIndex = 4 + Me.label2.Text = "label2" + ' + ' Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(label2) + Me.Controls.Add(label1) + Me.Controls.Add(button1) + Me.Controls.Add(dataGridView1) + Me.Name = "Form1" + CType(Me.BindingSource1, System.ComponentModel.ISupportInitialize).EndInit() + CType(Me.dataGridView1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + + + Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load + InitializeSortedFilteredBindingSource() + + End Sub + + ' The following code example demonstrates BindingSource.Filter and + ' BindingSource.Sort members. + ' To run this example paste the code into a form that contains a + ' BindingSource named BindingSource1 and a DataGridView named + ' dataGridView1. Handle the form's load event and call + ' InitializeSortedFilteredBindingSource in the load event-handling + ' method. + + ' If you are using VB, you may need to add a reference to the System.Data.dll. + ' + Private Sub InitializeSortedFilteredBindingSource() + + ' Create the connection string, data adapter and data table. + Dim connectionString As New SqlConnection("Initial Catalog=Northwind;" & _ + "Data Source=localhost;Integrated Security=SSPI;") + Dim customersTableAdapter As New SqlDataAdapter("Select * from Customers", _ + connectionString) + Dim customerTable As New DataTable() + + ' Fill the adapter with the contents of the customer table. + customersTableAdapter.Fill(customerTable) + + ' Set data source for BindingSource1. + BindingSource1.DataSource = customerTable + + ' Filter the items to show contacts who are owners. + ' + BindingSource1.Filter = "ContactTitle='Owner'" + ' + ' Sort the items on the company name in descending order. + ' + BindingSource1.Sort = "Country DESC, Address ASC" + ' + + ' Set the data source for dataGridView1 to BindingSource1. + dataGridView1.DataSource = BindingSource1 + + + End Sub + + ' + + ' The following code example demonstrates BindingSource.Items, + ' BindingSource.List, BindingSource.RemoveAt, BindingSource.Count + ' BindingSourceItemCollection.Count. + ' To run this example paste the code into a form that contains a + ' BindingSource named BindingSource1, two labels named label1 and label2 + ' and a button named button1. Associate the button1_Click + ' method with the click event for button1. + ' + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + + ' Create the connection string, data adapter and data table. + Dim connectionString As New SqlConnection("Initial Catalog=Northwind;" & _ + "Data Source=localhost;Integrated Security=SSPI;") + Dim customersTableAdapter As New SqlDataAdapter("Select * from Customers", _ + connectionString) + Dim customerTable As New DataTable() + + ' Fill the adapter with the contents of the customer table. + customersTableAdapter.Fill(customerTable) + + ' Set data source for BindingSource1. + BindingSource1.DataSource = customerTable + + ' Set the label text to the number of items in the collection before + ' an item is removed. + label1.Text = "Starting count: " + BindingSource1.Count.ToString() + + ' Access the List property and remove an item. + BindingSource1.List.RemoveAt(4) + + ' Remove an item directly from the BindingSource. + ' This is equivalent to the previous line of code. + BindingSource1.RemoveAt(4) + + ' Show the new count. + label2.Text = "Count after removal: " + BindingSource1.Count.ToString() + + End Sub +End Class +' + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb new file mode 100644 index 0000000000..91ba52db94 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataConnectorWebService/VB/form1.vb @@ -0,0 +1,196 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Namespace BindToWebService + Class Form1 + Inherits Form + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Private BindingSource1 As New BindingSource() + Private textBox1 As New TextBox() + Private textBox2 As New TextBox() + Private WithEvents button1 As New Button() + + Public Sub New() + + textBox1.Location = New System.Drawing.Point(118, 131) + textBox1.ReadOnly = True + button1.Location = New System.Drawing.Point(133, 60) + button1.Text = "Get zipcode" + ClientSize = New System.Drawing.Size(292, 266) + Controls.Add(Me.button1) + Controls.Add(Me.textBox1) + End Sub + + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + + textBox1.Text = "Calling Web service.." + Dim resolver As New ZipCodeResolver() + BindingSource1.Add(resolver.CorrectedAddressXml("0", "One Microsoft Way", "Redmond", "WA")) + + End Sub + + + Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load + ' + BindingSource1.DataSource = GetType(USPSAddress) + ' + ' + textBox1.DataBindings.Add("Text", Me.BindingSource1, "FullZIP", True) + ' + End Sub + + End Class + + _ + Public Class ZipCodeResolver + Inherits System.Web.Services.Protocols.SoapHttpClientProtocol + + Private CorrectedAddressXmlOperationCompleted As _ + System.Threading.SendOrPostCallback + + + Public Sub New() + MyBase.New() + Me.Url = _ + "http://webservices.eraserver.net/zipcoderesolver/zipcoderesolver.asmx" + End Sub + + + Public Event CorrectedAddressXmlCompleted As _ + CorrectedAddressXmlCompletedEventHandler + + _ + Public Function CorrectedAddressXml(ByVal accessCode As String, _ + ByVal address As String, ByVal city As String, ByVal state As String) _ + As USPSAddress + Dim results() As Object = Me.Invoke("CorrectedAddressXml", _ + New Object() {accessCode, address, city, state}) + Return CType(results(0), USPSAddress) + End Function + + ''' + Public Function BeginCorrectedAddressXml(ByVal accessCode As String, _ + ByVal address As String, ByVal city As String, ByVal state As String, _ + ByVal callback As System.AsyncCallback, ByVal asyncState As Object) _ + As System.IAsyncResult + + Return Me.BeginInvoke("CorrectedAddressXml", _ + New Object() {accessCode, address, city, state}, callback, asyncState) + End Function + + Public Function EndCorrectedAddressXml(ByVal asyncResult _ + As System.IAsyncResult) As USPSAddress + Dim results() As Object = Me.EndInvoke(asyncResult) + Return CType(results(0), USPSAddress) + End Function + End Class + + ' + _ + Public Class USPSAddress + + Private streetField As String + + Private cityField As String + + Private stateField As String + + Private shortZIPField As String + + Private fullZIPField As String + + + Public Property Street() As String + Get + Return Me.streetField + End Get + Set(ByVal value As String) + Me.streetField = value + End Set + End Property + + + Public Property City() As String + Get + Return Me.cityField + End Get + Set(ByVal value As String) + Me.cityField = value + End Set + End Property + + Public Property State() As String + Get + Return Me.stateField + End Get + Set(ByVal value As String) + Me.stateField = value + End Set + End Property + + + Public Property ShortZIP() As String + Get + Return Me.shortZIPField + End Get + Set(ByVal value As String) + Me.shortZIPField = value + End Set + End Property + + + Public Property FullZIP() As String + Get + Return Me.fullZIPField + End Get + Set(ByVal value As String) + Me.fullZIPField = value + End Set + End Property + End Class + ' + + Public Delegate Sub CorrectedAddressXmlCompletedEventHandler(ByVal sender As Object, _ + ByVal args As CorrectedAddressXmlCompletedEventArgs) + + Public Class CorrectedAddressXmlCompletedEventArgs + Inherits System.ComponentModel.AsyncCompletedEventArgs + + Private results() As Object + + Friend Sub New(ByVal results() As Object, ByVal exception As System.Exception, _ + ByVal cancelled As Boolean, ByVal userState As Object) + MyBase.New(exception, cancelled, userState) + Me.results = results + End Sub + + Public ReadOnly Property Result() As USPSAddress + Get + Me.RaiseExceptionIfNecessary() + Return CType(Me.results(0), USPSAddress) + End Get + End Property + End Class + +End Namespace +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/VB/autosizing.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/VB/autosizing.vb new file mode 100644 index 0000000000..efff796f2f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.AutoSizing/VB/autosizing.vb @@ -0,0 +1,322 @@ +Imports System.Windows.Forms +Imports System.Drawing + +' +Public Class AutoSizing + Inherits System.Windows.Forms.Form + + Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel + Friend WithEvents Button1 As Button = New Button() + Friend WithEvents Button2 As Button = New Button() + Friend WithEvents Button3 As Button = New Button() + Friend WithEvents Button4 As Button = New Button() + Friend WithEvents Button5 As Button = New Button() + Friend WithEvents Button6 As Button = New Button() + Friend WithEvents Button7 As Button = New Button() + Friend WithEvents Button8 As Button = New Button() + Friend WithEvents Button9 As Button = New Button() + Friend WithEvents Button10 As Button = New Button() + Friend WithEvents Button11 As Button = New Button() + Friend WithEvents DataGridView1 As DataGridView + + Public Sub New() + MyBase.New() + InitializeComponent() + AddDirections() + + AddButton(Button1, "Reset") + AddButton(Button2, "Change Column 3 Header") + AddButton(Button3, "Change Meatloaf Recipe") + AddButton(Button4, "Change Restaurant 2") + + AddButtonsForAutomaticResizing() + End Sub + + Private Sub AddDirections() + Dim directions As New Label() + directions.AutoSize = True + Dim newLine As String = Environment.NewLine + directions.Text = "Press the buttons that start " & newLine _ + & "with 'Change' to see how different sizing " & newLine _ + & "modes deal with content changes." + + FlowLayoutPanel1.Controls.Add(directions) + End Sub + + Private Sub InitializeComponent() + Me.FlowLayoutPanel1 = New FlowLayoutPanel + Me.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + Me.FlowLayoutPanel1.Location = _ + New System.Drawing.Point(454, 0) + Me.FlowLayoutPanel1.AutoSize = True + Me.FlowLayoutPanel1.TabIndex = 7 + + Me.Controls.Add(Me.FlowLayoutPanel1) + Me.Text = Me.GetType().Name + Me.AutoSize = True + End Sub + + Private startingSize As Size + Private thirdColumnHeader As String = "Main Ingredients" + Private boringMeatloaf As String = "ground beef" + Private boringMeatloafRanking As String = "*" + Private boringRecipe As Boolean + Private shortMode As Boolean + Private otherRestaurant As String = "Gomes's Saharan Sushi" + + Private Sub InitializeDataGridView(ByVal ignored As Object, _ + ByVal ignoredToo As EventArgs) Handles Me.Load + DataGridView1 = New System.Windows.Forms.DataGridView + Controls.Add(DataGridView1) + startingSize = New Size(450, 400) + DataGridView1.Size = startingSize + + SetUpColumns() + PopulateRows() + + shortMode = False + boringRecipe = True + AddLabels() + End Sub + + Private Sub SetUpColumns() + DataGridView1.ColumnCount = 4 + DataGridView1.ColumnHeadersVisible = True + + Dim columnHeaderStyle As New DataGridViewCellStyle + columnHeaderStyle.BackColor = Color.Aqua + columnHeaderStyle.Font = New Font("Verdana", 10, _ + FontStyle.Bold) + DataGridView1.ColumnHeadersDefaultCellStyle = _ + columnHeaderStyle + + DataGridView1.Columns(0).Name = "Recipe" + DataGridView1.Columns(1).Name = "Category" + DataGridView1.Columns(2).Name = thirdColumnHeader + DataGridView1.Columns(3).Name = "Rating" + End Sub + + Private Sub PopulateRows() + Dim row1 As String() = New String() _ + {"Meatloaf", "Main Dish", boringMeatloaf, _ + boringMeatloafRanking} + Dim row2 As String() = New String() _ + {"Key Lime Pie", "Dessert", _ + "lime juice, evaporated milk", _ + "****"} + Dim row3 As String() = New String() _ + {"Orange-Salsa Pork Chops", "Main Dish", _ + "pork chops, salsa, orange juice", "****"} + Dim row4 As String() = New String() _ + {"Black Bean and Rice Salad", "Salad", _ + "black beans, brown rice", _ + "****"} + Dim row5 As String() = New String() _ + {"Chocolate Cheesecake", "Dessert", "cream cheese", _ + "***"} + Dim row6 As String() = New String() _ + {"Black Bean Dip", "Appetizer", "black beans, sour cream", _ + "***"} + Dim rows As Object() = New Object() {row1, row2, row3, _ + row4, row5, row6} + + Dim rowArray As String() + For Each rowArray In rows + DataGridView1.Rows.Add(rowArray) + Next + + For Each row As DataGridViewRow In DataGridView1.Rows + If row.IsNewRow Then Continue For + row.HeaderCell.Value = "Restaurant " & row.Index + Next + End Sub + + Private Sub AddButton(ByVal button As Button, _ + ByVal buttonLabel As String) + + button.Text = buttonLabel + button.AutoSize = True + FlowLayoutPanel1.Controls.Add(button) + End Sub + + Private Sub resetToDisorder(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button1.Click + + DataGridView1.Size = startingSize + Controls.Remove(DataGridView1) + DataGridView1.Dispose() + InitializeDataGridView(Nothing, Nothing) + End Sub + + Private Sub ChangeColumn3Header(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button2.Click + + Toggle(shortMode) + If shortMode Then DataGridView1.Columns(2).HeaderText = "S" _ + Else DataGridView1.Columns(2).HeaderText = _ + thirdColumnHeader + End Sub + + Private Shared Function Toggle(ByRef toggleThis As Boolean) _ + As Boolean + toggleThis = Not toggleThis + Return toggleThis + End Function + + Private Sub ChangeMeatloafRecipe(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button3.Click + + Toggle(boringRecipe) + If boringRecipe Then + SetMeatloaf(boringMeatloaf, boringMeatloafRanking) + Else + Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _ + & "1/2 cup bread crumbs, 1/4 cup ketchup," _ + & "1/3 tsp onion powder, " _ + & "1 clove of garlic, 1/2 pack onion soup mix, " _ + & "dash of your favorite BBQ Sauce" + SetMeatloaf(greatMeatloafRecipe, "***") + End If + End Sub + + Private Sub ChangeRestaurant(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button4.Click + + If Not DataGridView1.Rows(2).HeaderCell.Value _ + .Equals(otherRestaurant) Then + + DataGridView1.Rows(2).HeaderCell.Value = _ + otherRestaurant + Else + DataGridView1.Rows(2).HeaderCell.Value = _ + "Restaurant 2" + End If + End Sub + + Private Sub SetMeatloaf(ByVal recipe As String, _ + ByVal rating As String) + DataGridView1.Rows(0).Cells(2).Value = recipe + DataGridView1.Rows(0).Cells(3).Value = rating + End Sub + + Private currentLayoutName As String = _ + "DataGridView.AutoSizeRowsMode is currently: " + Private Sub AddLabels() + Dim current As Label = CType( _ + FlowLayoutPanel1.Controls(currentLayoutName), Label) + + If current Is Nothing Then + current = New Label() + current.AutoSize = True + current.Name = currentLayoutName + FlowLayoutPanel1.Controls.Add(current) + current.Text = currentLayoutName & _ + DataGridView1.AutoSizeRowsMode.ToString() + End If + End Sub + +#Region "Automatic Resizing" + Private Sub AddButtonsForAutomaticResizing() + AddButton(Button5, "Keep Column Headers Sized") + AddButton(Button6, "Keep Row Headers Sized") + AddButton(Button7, "Keep Rows Sized") + AddButton(Button8, "Keep Row Headers Sized with RowsMode") + AddButton(Button9, "Disable AutoSizeRowsMode") + AddButton(Button10, "AutoSize third column by rows") + AddButton(Button11, "AutoSize third column by rows and headers") + End Sub + + ' + Private Sub ColumnHeadersHeightSizeMode(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button5.Click + + DataGridView1.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.AutoSize + + End Sub + ' + + ' + Private Sub RowHeadersWidthSizeMode(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button6.Click + + DataGridView1.RowHeadersWidthSizeMode = _ + DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders + + End Sub + ' + + ' + Private Sub AutoSizeRowsMode(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button7.Click + + DataGridView1.AutoSizeRowsMode = _ + DataGridViewAutoSizeRowsMode.AllCells + + End Sub + ' + + Private Sub AutoSizeRowHeadersUsingAllHeadersMode _ + (ByVal sender As Object, ByVal e As System.EventArgs) _ + Handles Button8.Click + + DataGridView1.AutoSizeRowsMode = _ + DataGridViewAutoSizeRowsMode.AllHeaders + + End Sub + + ' + Private Sub WatchRowsModeChanges(ByVal sender As Object, _ + ByVal modeEvent As DataGridViewAutoSizeModeEventArgs) _ + Handles DataGridView1.AutoSizeRowsModeChanged + + Dim label As Label = CType(FlowLayoutPanel1.Controls _ + (currentLayoutName), Label) + + If modeEvent.PreviousModeAutoSized Then + label.Text = "changed to different " & label.Name & _ + DataGridView1.AutoSizeRowsMode.ToString() + Else + label.Text = label.Name & _ + DataGridView1.AutoSizeRowsMode.ToString() + End If + End Sub + ' + + Private Sub DisableAutoSizeRowsMode(ByVal sender As Object, _ + ByVal modeEvent As EventArgs) Handles Button9.Click + + DataGridView1.AutoSizeRowsMode = _ + DataGridViewAutoSizeRowsMode.None + End Sub + + ' + Private Sub AutoSizeOneColumn(ByVal sender As Object, _ + ByVal theEvent As EventArgs) Handles Button10.Click + + Dim column As DataGridViewColumn = DataGridView1.Columns(2) + column.AutoSizeMode = _ + DataGridViewAutoSizeColumnMode.DisplayedCells + + End Sub + ' + + Private Sub AutoSizeOneColumnIncludingHeaders(ByVal sender As Object, _ + ByVal theEvent As EventArgs) Handles Button11.Click + + Dim column As DataGridViewColumn = DataGridView1.Columns(2) + column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells + + End Sub +#End Region + + _ + Public Shared Sub Main() + Application.Run(New AutoSizing()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewbanddemo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewbanddemo.vb new file mode 100644 index 0000000000..6ab7e49bf9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewbanddemo.vb @@ -0,0 +1,284 @@ +' +Imports System.Windows.Forms +Imports System.Drawing + +Public Class DataGridViewBandDemo + Inherits Form + +#Region "Form setup" + Public Sub New() + MyBase.New() + InitializeComponent() + + AddButton(Button1, "Reset") + AddButton(Button2, "Change Column 3 Header") + AddButton(Button3, "Change Meatloaf Recipe") + AddAdditionalButtons() + End Sub + + Friend WithEvents dataGridView As DataGridView + Friend WithEvents Button1 As Button = New Button() + Friend WithEvents Button2 As Button = New Button() + Friend WithEvents Button3 As Button = New Button() + Friend WithEvents Button4 As Button = New Button() + Friend WithEvents Button5 As Button = New Button() + Friend WithEvents Button6 As Button = New Button() + Friend WithEvents Button7 As Button = New Button() + Friend WithEvents Button8 As Button = New Button() + Friend WithEvents Button9 As Button = New Button() + Friend WithEvents Button10 As Button = New Button() + Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel _ + = New FlowLayoutPanel() + + Private Sub InitializeComponent() + FlowLayoutPanel1.Location = New Point(454, 0) + FlowLayoutPanel1.AutoSize = True + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + FlowLayoutPanel1.Name = "flowlayoutpanel" + ClientSize = New System.Drawing.Size(614, 360) + Controls.Add(FlowLayoutPanel1) + Text = Me.GetType.Name + AutoSize = True + End Sub +#End Region + +#Region "setup DataGridView" + Private thirdColumnHeader As String = "Main Ingredients" + Private boringMeatloaf As String = "ground beef" + Private boringMeatloafRanking As String = "*" + Private boringRecipe As Boolean + Private shortMode As Boolean + + Private Sub InitializeDataGridView(ByVal ignored As Object, _ + ByVal ignoredToo As EventArgs) Handles Me.Load + + dataGridView = New System.Windows.Forms.DataGridView + Controls.Add(dataGridView) + dataGridView.Size = New Size(300, 200) + + ' Create an unbound DataGridView by declaring a + ' column count. + dataGridView.ColumnCount = 4 + AdjustDataGridViewSizing() + + ' Set the column header style. + Dim columnHeaderStyle As New DataGridViewCellStyle + columnHeaderStyle.BackColor = Color.Aqua + columnHeaderStyle.Font = _ + New Font("Verdana", 10, FontStyle.Bold) + dataGridView.ColumnHeadersDefaultCellStyle = _ + columnHeaderStyle + + ' Set the column header names. + dataGridView.Columns(0).Name = "Recipe" + dataGridView.Columns(1).Name = "Category" + dataGridView.Columns(2).Name = thirdColumnHeader + dataGridView.Columns(3).Name = "Rating" + + ' Populate the rows. + Dim row1 As String() = New String() _ + {"Meatloaf", "Main Dish", boringMeatloaf, _ + boringMeatloafRanking} + Dim row2 As String() = New String() _ + {"Key Lime Pie", "Dessert", _ + "lime juice, evaporated milk", _ + "****"} + Dim row3 As String() = New String() _ + {"Orange-Salsa Pork Chops", "Main Dish", _ + "pork chops, salsa, orange juice", "****"} + Dim row4 As String() = New String() _ + {"Black Bean and Rice Salad", "Salad", _ + "black beans, brown rice", _ + "****"} + Dim row5 As String() = New String() _ + {"Chocolate Cheesecake", "Dessert", "cream cheese", _ + "***"} + Dim row6 As String() = New String() _ + {"Black Bean Dip", "Appetizer", _ + "black beans, sour cream", _ + "***"} + Dim rows As Object() = New Object() {row1, row2, _ + row3, row4, row5, row6} + + Dim rowArray As String() + For Each rowArray In rows + dataGridView.Rows.Add(rowArray) + Next + + PostRowCreation() + + shortMode = False + boringRecipe = True + End Sub + + Protected Sub AddButton(ByVal button As Button, _ + ByVal buttonLabel As String) + + FlowLayoutPanel1.Controls.Add(button) + button.TabIndex = FlowLayoutPanel1.Controls.Count + button.Text = buttonLabel + button.AutoSize = True + End Sub + + ' Reset columns to initial disorderly arrangement. + Private Sub ResetToDisorder(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button1.Click + Controls.Remove(dataGridview) + dataGridView.Dispose() + InitializeDataGridView(Nothing, Nothing) + End Sub + + ' Change the header in column three. + Private Sub Button2_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button2.Click + + Toggle(shortMode) + If shortMode Then dataGridView.Columns(2).HeaderText = _ + "S" _ + Else dataGridView.Columns(2).HeaderText = _ + thirdColumnHeader + End Sub + + Private Shared Sub Toggle(ByRef toggleThis As Boolean) + toggleThis = Not toggleThis + End Sub + + ' Change the meatloaf recipe. + Private Sub Button3_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button3.Click + + Toggle(boringRecipe) + If boringRecipe Then + SetMeatloaf(boringMeatloaf, boringMeatloafRanking) + Else + Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _ + & "1/2 cup bread crumbs, 1/4 cup ketchup," _ + & "1/3 tsp onion powder, " _ + & "1 clove of garlic, 1/2 pack onion soup mix " _ + & " dash of your favorite BBQ Sauce" + SetMeatloaf(greatMeatloafRecipe, "***") + End If + End Sub + + Private Sub SetMeatloaf(ByVal recipe As String, _ + ByVal rating As String) + + dataGridView.Rows(0).Cells(2).Value = recipe + dataGridView.Rows(0).Cells(3).Value = rating + End Sub +#End Region + +#Region "demonstration code" + Private Sub AddAdditionalButtons() + AddButton(Button4, "Freeze First Row") + AddButton(Button5, "Freeze Second Column") + AddButton(Button6, "Hide Salad Row") + AddButton(Button7, "Disable First Column Resizing") + AddButton(Button8, "Make ReadOnly") + AddButton(Button9, "Style Using Tag") + End Sub + + Private Sub AdjustDataGridViewSizing() + dataGridView.AutoSizeRowsMode = _ + DataGridViewAutoSizeRowsMode.AllCells + dataGridView.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.AutoSize + End Sub + + ' + ' Freeze the first row. + Private Sub Button4_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button4.Click + + FreezeBand(dataGridView.Rows(0)) + End Sub + + Private Sub FreezeColumn(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button5.Click + + FreezeBand(dataGridView.Columns(1)) + End Sub + + Private Shared Sub FreezeBand(ByVal band As DataGridViewBand) + + band.Frozen = True + Dim style As DataGridViewCellStyle = New DataGridViewCellStyle() + style.BackColor = Color.WhiteSmoke + band.DefaultCellStyle = style + + End Sub + ' + + ' + ' Hide a band of cells. + Private Sub Button6_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button6.Click + + Dim band As DataGridViewBand = dataGridView.Rows(3) + band.Visible = False + End Sub + ' + + ' + ' Turn off user's ability to resize a column. + Private Sub Button7_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button7.Click + + Dim band As DataGridViewBand = dataGridView.Columns(0) + band.Resizable = DataGridViewTriState.False + End Sub + ' + + ' + ' Make the entire DataGridView read only. + Private Sub Button8_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button8.Click + + For Each band As DataGridViewBand In dataGridView.Columns + band.ReadOnly = True + Next + End Sub + ' + + ' + Private Sub PostRowCreation() + SetBandColor(dataGridView.Columns(0), Color.CadetBlue) + SetBandColor(dataGridView.Rows(1), Color.Coral) + SetBandColor(dataGridView.Columns(2), Color.DodgerBlue) + End Sub + + Private Shared Sub SetBandColor(ByVal band As DataGridViewBand, _ + ByVal color As Color) + band.Tag = color + End Sub + + ' Color the bands by the value stored in their tag. + Private Sub Button9_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button9.Click + + For Each band As DataGridViewBand In dataGridView.Columns + If band.Tag IsNot Nothing Then + band.DefaultCellStyle.BackColor = _ + CType(band.Tag, Color) + End If + Next + + For Each band As DataGridViewBand In dataGridView.Rows + If band.Tag IsNot Nothing Then + band.DefaultCellStyle.BackColor = _ + CType(band.Tag, Color) + End If + Next + End Sub + ' +#End Region + + _ + Public Shared Sub Main() + Application.Run(New DataGridViewBandDemo()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewcolumndemo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewcolumndemo.vb new file mode 100644 index 0000000000..c1c8f4925f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewcolumndemo.vb @@ -0,0 +1,421 @@ +' +Imports System.Windows.Forms +Imports System.Drawing + +Public Class DataGridViewColumnDemo + Inherits Form + +#Region "set up form" + Public Sub New() + InitializeComponent() + + AddButton(Button1, "Reset") + AddButton(Button2, "Change Column 3 Header") + AddButton(Button3, "Change Meatloaf Recipe") + AddAdditionalButtons() + End Sub + + Friend WithEvents dataGridView As DataGridView + Friend WithEvents Button1 As Button = New Button() + Friend WithEvents Button2 As Button = New Button() + Friend WithEvents Button3 As Button = New Button() + Friend WithEvents Button4 As Button = New Button() + Friend WithEvents Button5 As Button = New Button() + Friend WithEvents Button6 As Button = New Button() + Friend WithEvents Button7 As Button = New Button() + Friend WithEvents Button8 As Button = New Button() + Friend WithEvents Button9 As Button = New Button() + Friend WithEvents Button10 As Button = New Button() + Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel _ + = New FlowLayoutPanel() + + Private Sub InitializeComponent() + FlowLayoutPanel1.Location = New Point(454, 0) + FlowLayoutPanel1.AutoSize = True + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + FlowLayoutPanel1.Name = "flowlayoutpanel" + ClientSize = New System.Drawing.Size(614, 360) + Controls.Add(FlowLayoutPanel1) + Text = Me.GetType.Name + AutoSize = True + End Sub +#End Region + +#Region "set up DataGridView" + Private thirdColumnHeader As String = "Main Ingredients" + Private boringMeatloaf As String = "ground beef" + Private boringMeatloafRanking As String = "*" + Private boringRecipe As Boolean + Private shortMode As Boolean + + Private Sub InitializeDataGridView(ByVal ignored As Object, _ + ByVal ignoredToo As EventArgs) Handles Me.Load + + dataGridView = New System.Windows.Forms.DataGridView + Controls.Add(dataGridView) + dataGridView.Size = New Size(300, 200) + + ' Create an unbound DataGridView by declaring a + ' column count. + dataGridView.ColumnCount = 4 + AdjustDataGridViewSizing() + + ' Set the column header style. + Dim columnHeaderStyle As New DataGridViewCellStyle + columnHeaderStyle.BackColor = Color.Aqua + columnHeaderStyle.Font = _ + New Font("Verdana", 10, FontStyle.Bold) + dataGridView.ColumnHeadersDefaultCellStyle = _ + columnHeaderStyle + + ' Set the column header names. + dataGridView.Columns(0).Name = "Recipe" + dataGridView.Columns(1).Name = "Category" + dataGridView.Columns(2).Name = thirdColumnHeader + dataGridView.Columns(3).Name = "Rating" + + PostColumnCreation() + + ' Populate the rows. + Dim row1 As String() = New String() _ + {"Meatloaf", "Main Dish", boringMeatloaf, _ + boringMeatloafRanking} + Dim row2 As String() = New String() _ + {"Key Lime Pie", "Dessert", _ + "lime juice, evaporated milk", _ + "****"} + Dim row3 As String() = New String() _ + {"Orange-Salsa Pork Chops", "Main Dish", _ + "pork chops, salsa, orange juice", "****"} + Dim row4 As String() = New String() _ + {"Black Bean and Rice Salad", "Salad", _ + "black beans, brown rice", _ + "****"} + Dim row5 As String() = New String() _ + {"Chocolate Cheesecake", "Dessert", "cream cheese", _ + "***"} + Dim row6 As String() = New String() _ + {"Black Bean Dip", "Appetizer", _ + "black beans, sour cream", _ + "***"} + Dim rows As Object() = New Object() {row1, row2, _ + row3, row4, row5, row6} + + Dim rowArray As String() + For Each rowArray In rows + dataGridView.Rows.Add(rowArray) + Next + + shortMode = False + boringRecipe = True + End Sub + + Private Sub AddButton(ByVal button As Button, _ + ByVal buttonLabel As String) + + FlowLayoutPanel1.Controls.Add(button) + button.TabIndex = FlowLayoutPanel1.Controls.Count + button.Text = buttonLabel + button.AutoSize = True + End Sub + + Private Sub ResetToDisorder(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button1.Click + Controls.Remove(dataGridview) + dataGridView.Dispose() + InitializeDataGridView(Nothing, Nothing) + End Sub + + Private Sub ChangeColumn3Header(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button2.Click + + Toggle(shortMode) + If shortMode Then dataGridView.Columns(2).HeaderText = _ + "S" _ + Else dataGridView.Columns(2).HeaderText = _ + thirdColumnHeader + End Sub + + Private Shared Sub Toggle(ByRef toggleThis As Boolean) + toggleThis = Not toggleThis + End Sub + + Private Sub ChangeMeatloafRecipe(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button3.Click + + Toggle(boringRecipe) + If boringRecipe Then + SetMeatloaf(boringMeatloaf, boringMeatloafRanking) + Else + Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _ + & "1/2 cup bread crumbs, 1/4 cup ketchup," _ + & "1/3 tsp onion powder, " _ + & "1 clove of garlic, 1/2 pack onion soup mix " _ + & " dash of your favorite BBQ Sauce" + SetMeatloaf(greatMeatloafRecipe, "***") + End If + End Sub + + Private Sub SetMeatloaf(ByVal recipe As String, _ + ByVal rating As String) + + dataGridView.Rows(0).Cells(2).Value = recipe + dataGridView.Rows(0).Cells(3).Value = rating + End Sub +#End Region + +#Region "demonstration code" + Private Sub PostColumnCreation() + AddContextLabel() + AddCriteriaLabel() + CustomizeCellsInThirdColumn() + AddContextMenu() + SetDefaultCellInFirstColumn() + ToolTips() + End Sub + + Private criteriaLabel As String = "Column 3 sizing criteria: " + Private Sub AddCriteriaLabel() + AddLabelToPanelIfNotAlreadyThere(criteriaLabel, _ + criteriaLabel & _ + dataGridView.Columns(2).AutoSizeMode.ToString() _ + & ".") + End Sub + + Private Sub AddContextLabel() + Dim labelName As String = "label" + AddLabelToPanelIfNotAlreadyThere(labelName, _ + "Use shortcut menu to change cell color.") + End Sub + + Private Sub AddLabelToPanelIfNotAlreadyThere( _ + ByVal labelName As String, _ + ByVal labelText As String) + + Dim label As Label + If FlowLayoutPanel1.Controls(labelName) Is Nothing Then + label = New Label() + label.AutoSize = True + label.Name = labelName + label.BackColor = Color.Bisque + FlowLayoutPanel1.Controls.Add(label) + Else + label = CType(FlowLayoutPanel1.Controls(labelName), Label) + End If + label.Text = labelText + End Sub + + ' + Private Sub CustomizeCellsInThirdColumn() + + Dim thirdColumn As Integer = 2 + Dim column As DataGridViewColumn = _ + dataGridView.Columns(thirdColumn) + Dim cell As DataGridViewCell = _ + New DataGridViewTextBoxCell() + + cell.Style.BackColor = Color.Wheat + column.CellTemplate = cell + End Sub + ' + + ' + WithEvents toolStripItem1 As New ToolStripMenuItem() + + Private Sub AddContextMenu() + toolStripItem1.Text = "Redden" + Dim strip As New ContextMenuStrip() + For Each column As DataGridViewColumn _ + In dataGridView.Columns() + + column.ContextMenuStrip = strip + column.ContextMenuStrip.Items.Add(toolStripItem1) + Next + End Sub + ' Change the cell's color. + Private Sub toolStripItem1_Click(ByVal sender As Object, _ + ByVal args As EventArgs) _ + Handles toolStripItem1.Click + + dataGridView.Rows(mouseLocation.RowIndex) _ + .Cells(mouseLocation.ColumnIndex) _ + .Style.BackColor = Color.Red + End Sub + + Private mouseLocation As DataGridViewCellEventArgs + + ' Deal with hovering over a cell. + Private Sub dataGridView_CellMouseEnter(ByVal sender As Object, _ + ByVal location As DataGridViewCellEventArgs) _ + Handles DataGridView.CellMouseEnter + + mouseLocation = location + End Sub + ' + + ' + Private Sub SetDefaultCellInFirstColumn() + Dim firstColumn As DataGridViewColumn = _ + dataGridView.Columns(0) + Dim cellStyle As DataGridViewCellStyle = _ + New DataGridViewCellStyle() + cellStyle.BackColor = Color.Thistle + + firstColumn.DefaultCellStyle = cellStyle + End Sub + ' + + ' + Private Sub ToolTips() + Dim firstColumn As DataGridViewColumn = _ + dataGridView.Columns(0) + Dim thirdColumn As DataGridViewColumn = _ + dataGridView.Columns(2) + firstColumn.ToolTipText = _ + "This is column uses a default cell." + thirdColumn.ToolTipText = _ + "This is column uses a template cell." _ + & " Changes to one cell's style changes them all." + End Sub + ' + + Private Sub AddAdditionalButtons() + AddButton(Button4, "Set Minimum Width of Column Two") + AddButton(Button5, "Set Width of Column One") + AddButton(Button6, "Autosize Third Column") + AddButton(Button7, "Add Thick Vertical Edge") + AddButton(Button8, "Style and Number Columns") + AddButton(Button9, "Change Column Header Text") + AddButton(Button10, "Swap First and Last Columns") + End Sub + + Private Sub AdjustDataGridViewSizing() + dataGridView.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.AutoSize + End Sub + + ' + 'Set the minimum width. + Private Sub Button4_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button4.Click + + Dim column As DataGridViewColumn = dataGridView.Columns(1) + column.MinimumWidth = 40 + End Sub + ' + + ' + ' Set the width. + Private Sub Button5_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button5.Click + + Dim column As DataGridViewColumn = dataGridView.Columns(0) + column.Width = 60 + End Sub + ' + + ' + ' AutoSize the third column. + Private Sub Button6_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button6.Click + + Dim column As DataGridViewColumn = dataGridView.Columns(2) + column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells + End Sub + ' + + ' + ' Set the vertical edge. + Private Sub Button7_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button7.Click + + Dim thirdColumn As Integer = 2 + Dim column As DataGridViewColumn = _ + dataGridView.Columns(thirdColumn) + column.DividerWidth = 10 + + End Sub + ' + + ' + ' Style and number columns. + Private Sub Button8_Click(ByVal sender As Object, _ + ByVal args As EventArgs) Handles Button8.Click + + Dim style As DataGridViewCellStyle = _ + New DataGridViewCellStyle() + style.Alignment = _ + DataGridViewContentAlignment.MiddleCenter + style.ForeColor = Color.IndianRed + style.BackColor = Color.Ivory + + For Each column As DataGridViewColumn _ + In dataGridView.Columns + + column.HeaderCell.Value = _ + column.Index.ToString + column.HeaderCell.Style = style + Next + End Sub + ' + + ' + ' Change the text in the column header. + Private Sub Button9_Click(ByVal sender As Object, _ + ByVal args As EventArgs) Handles Button9.Click + + For Each column As DataGridViewColumn _ + In dataGridView.Columns + + column.HeaderText = String.Concat("Column ", _ + column.Index.ToString) + Next + End Sub + ' + + ' + ' Swap the last column with the first. + Private Sub Button10_Click(ByVal sender As Object, _ + ByVal args As EventArgs) Handles Button10.Click + + Dim columnCollection As DataGridViewColumnCollection = _ + dataGridView.Columns + + Dim firstVisibleColumn As DataGridViewColumn = _ + columnCollection.GetFirstColumn(DataGridViewElementStates.Visible) + Dim lastVisibleColumn As DataGridViewColumn = _ + columnCollection.GetLastColumn(DataGridViewElementStates.Visible, _ + Nothing) + + Dim firstColumn_sIndex As Integer = firstVisibleColumn.DisplayIndex + firstVisibleColumn.DisplayIndex = _ + lastVisibleColumn.DisplayIndex + lastVisibleColumn.DisplayIndex = firstColumn_sIndex + End Sub + ' + + ' + ' Updated the criteria label. + Private Sub dataGridView_AutoSizeColumnCriteriaChanged( _ + ByVal sender As Object, _ + ByVal args As DataGridViewAutoSizeColumnModeEventArgs) _ + Handles DataGridView.AutoSizeColumnModeChanged + + args.Column.DataGridView.Parent. _ + Controls("flowlayoutpanel"). _ + Controls(criteriaLabel).Text = _ + criteriaLabel & args.Column.AutoSizeMode.ToString + End Sub + ' +#End Region + + _ + Public Shared Sub Main() + Application.Run(New DataGridViewColumnDemo()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewrowdemo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewrowdemo.vb new file mode 100644 index 0000000000..d93b1400ab --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ButtonDemos/VB/datagridviewrowdemo.vb @@ -0,0 +1,266 @@ +' +Imports System.Windows.Forms +Imports System.Drawing + +Public Class DataGridViewRowDemo + Inherits Form + +#Region "Form setup" + Public Sub New() + MyBase.New() + InitializeComponent() + + AddButton(Button1, "Reset") + AddButton(Button2, "Change Column 3 Header") + AddButton(Button3, "Change Meatloaf Recipe") + AddAdditionalButtons() + End Sub + + Friend WithEvents dataGridView As DataGridView + Friend WithEvents Button1 As Button = New Button() + Friend WithEvents Button2 As Button = New Button() + Friend WithEvents Button3 As Button = New Button() + Friend WithEvents Button4 As Button = New Button() + Friend WithEvents Button5 As Button = New Button() + Friend WithEvents Button6 As Button = New Button() + Friend WithEvents Button7 As Button = New Button() + Friend WithEvents Button8 As Button = New Button() + Friend WithEvents Button9 As Button = New Button() + Friend WithEvents Button10 As Button = New Button() + Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel _ + = New FlowLayoutPanel() + + Private Sub InitializeComponent() + FlowLayoutPanel1.Location = New Point(454, 0) + FlowLayoutPanel1.AutoSize = True + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + FlowLayoutPanel1.Name = "flowlayoutpanel" + ClientSize = New System.Drawing.Size(614, 360) + Controls.Add(FlowLayoutPanel1) + Text = Me.GetType.Name + AutoSize = True + End Sub +#End Region + +#Region "setup DataGridView" + Private thirdColumnHeader As String = "Main Ingredients" + Private boringMeatloaf As String = "ground beef" + Private boringMeatloafRanking As String = "*" + Private boringRecipe As Boolean + Private shortMode As Boolean + + Private Sub InitializeDataGridView(ByVal ignored As Object, _ + ByVal ignoredToo As EventArgs) Handles Me.Load + + dataGridView = New System.Windows.Forms.DataGridView + Controls.Add(dataGridView) + dataGridView.Size = New Size(300, 200) + + ' Create an unbound DataGridView by declaring a + ' column count. + dataGridView.ColumnCount = 4 + dataGridView.ColumnHeadersVisible = True + AdjustDataGridViewSizing() + + ' Set the column header style. + Dim columnHeaderStyle As New DataGridViewCellStyle + columnHeaderStyle.BackColor = Color.Aqua + columnHeaderStyle.Font = _ + New Font("Verdana", 10, FontStyle.Bold) + dataGridView.ColumnHeadersDefaultCellStyle = _ + columnHeaderStyle + + ' Set the column header names. + dataGridView.Columns(0).Name = "Recipe" + dataGridView.Columns(1).Name = "Category" + dataGridView.Columns(2).Name = thirdColumnHeader + dataGridView.Columns(3).Name = "Rating" + + ' Populate the rows. + Dim row1 As String() = New String() _ + {"Meatloaf", "Main Dish", boringMeatloaf, _ + boringMeatloafRanking} + Dim row2 As String() = New String() _ + {"Key Lime Pie", "Dessert", _ + "lime juice, evaporated milk", _ + "****"} + Dim row3 As String() = New String() _ + {"Orange-Salsa Pork Chops", "Main Dish", _ + "pork chops, salsa, orange juice", "****"} + Dim row4 As String() = New String() _ + {"Black Bean and Rice Salad", "Salad", _ + "black beans, brown rice", _ + "****"} + Dim row5 As String() = New String() _ + {"Chocolate Cheesecake", "Dessert", "cream cheese", _ + "***"} + Dim row6 As String() = New String() _ + {"Black Bean Dip", "Appetizer", _ + "black beans, sour cream", _ + "***"} + Dim rows As Object() = New Object() {row1, row2, _ + row3, row4, row5, row6} + + Dim rowArray As String() + For Each rowArray In rows + dataGridView.Rows.Add(rowArray) + Next + + shortMode = False + boringRecipe = True + End Sub + + Private Sub AddButton(ByVal button As Button, _ + ByVal buttonLabel As String) + + FlowLayoutPanel1.Controls.Add(button) + button.TabIndex = FlowLayoutPanel1.Controls.Count + button.Text = buttonLabel + button.AutoSize = True + End Sub + + ' Reset columns to initial disorderly arrangement. + Private Sub Button1_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button1.Click + Controls.Remove(dataGridview) + dataGridView.Dispose() + InitializeDataGridView(Nothing, Nothing) + End Sub + + ' Change column 3 header. + Private Sub Button2_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button2.Click + + Toggle(shortMode) + If shortMode Then dataGridView.Columns(2).HeaderText = _ + "S" _ + Else dataGridView.Columns(2).HeaderText = _ + thirdColumnHeader + End Sub + + Private Shared Sub Toggle(ByRef toggleThis As Boolean) + toggleThis = Not toggleThis + End Sub + + ' Change meatloaf recipe. + Private Sub Button3_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button3.Click + + Toggle(boringRecipe) + If boringRecipe Then + SetMeatloaf(boringMeatloaf, boringMeatloafRanking) + Else + Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _ + & "1/2 cup bread crumbs, 1/4 cup ketchup," _ + & "1/3 tsp onion powder, " _ + & "1 clove of garlic, 1/2 pack onion soup mix " _ + & " dash of your favorite BBQ Sauce" + SetMeatloaf(greatMeatloafRecipe, "***") + End If + End Sub + + Private Sub SetMeatloaf(ByVal recipe As String, _ + ByVal rating As String) + + dataGridView.Rows(0).Cells(2).Value = recipe + dataGridView.Rows(0).Cells(3).Value = rating + End Sub +#End Region + +#Region "demonstration code" + Private Sub AddAdditionalButtons() + AddButton(Button4, "Set Row Two Minimum Height") + AddButton(Button5, "Set Row One Height") + AddButton(Button6, "Label Rows") + AddButton(Button7, "Turn on Extra Edge") + AddButton(Button8, "Give Cheesecake an Excellent Rating") + End Sub + + Private Sub AdjustDataGridViewSizing() + dataGridView.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.AutoSize + dataGridView.Columns(ratingColumn).Width = 50 + End Sub + + ' + ' Set minimum height. + Private Sub Button4_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button4.Click + + Dim secondRow As Integer = 1 + Dim row As DataGridViewRow = dataGridView.Rows(secondRow) + row.MinimumHeight = 40 + End Sub + ' + + ' + ' Set height. + Private Sub Button5_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button5.Click + + Dim row As DataGridViewRow = dataGridView.Rows(0) + row.Height = 15 + End Sub + ' + + ' + ' Set row labels. + Private Sub Button6_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button6.Click + + Dim rowNumber As Integer = 1 + For Each row As DataGridViewRow In dataGridView.Rows + If row.IsNewRow Then Continue For + row.HeaderCell.Value = "Row " & rowNumber + rowNumber = rowNumber + 1 + Next + dataGridView.AutoResizeRowHeadersWidth( _ + DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders) + End Sub + ' + + ' + ' Set a thick horizontal edge. + Private Sub Button7_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button7.Click + + Dim secondRow As Integer = 1 + Dim row As DataGridViewRow = dataGridView.Rows(secondRow) + row.DividerHeight = 10 + + End Sub + ' + + ' + ' Give cheescake excellent rating. + Private Sub Button8_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button8.Click + + UpdateStars(dataGridView.Rows(4), "******************") + End Sub + + Private ratingColumn As Integer = 3 + + Private Sub UpdateStars(ByVal row As DataGridViewRow, _ + ByVal stars As String) + + row.Cells(ratingColumn).Value = stars + + ' Resize the column width to account for the new value. + row.DataGridView.AutoResizeColumn(ratingColumn, _ + DataGridViewAutoSizeColumnMode.DisplayedCells) + + End Sub + ' +#End Region + + _ + Public Shared Sub Main() + Application.Run(New DataGridViewRowDemo()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb new file mode 100644 index 0000000000..ceaab4eb43 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DataError/VB/errorhandling.vb @@ -0,0 +1,82 @@ +' +' +Imports System.Data +Imports System.Data.SqlClient +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Private WithEvents dataGridView1 As New DataGridView() + Private bindingSource1 As New BindingSource() + + Public Sub New() + + ' Initialize the form. + Me.dataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(dataGridView1) + + End Sub + ' + + ' + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Me.Load + + ' Initialize the BindingSource and bind the DataGridView to it. + bindingSource1.DataSource = GetData("select * from Customers") + Me.dataGridView1.DataSource = bindingSource1 + Me.dataGridView1.AutoResizeColumns( _ + DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) + + End Sub + ' + + ' + Private Sub dataGridView1_DataError(ByVal sender As Object, _ + ByVal e As DataGridViewDataErrorEventArgs) _ + Handles dataGridView1.DataError + + ' If the data source raises an exception when a cell value is + ' commited, display an error message. + If e.Exception IsNot Nothing AndAlso _ + e.Context = DataGridViewDataErrorContexts.Commit Then + + MessageBox.Show("CustomerID value must be unique.") + + End If + + End Sub + ' + + ' + Private Shared Function GetData(ByVal selectCommand As String) As DataTable + + Dim connectionString As String = _ + "Integrated Security=SSPI;Persist Security Info=False;" + _ + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096" + + ' Connect to the database and fill a data table, including the + ' schema information that contains the CustomerID column + ' constraint. + Dim adapter As New SqlDataAdapter(selectCommand, connectionString) + Dim data As New DataTable() + data.Locale = System.Globalization.CultureInfo.InvariantCulture + adapter.Fill(data) + adapter.FillSchema(data, SchemaType.Source) + + Return data + + End Function + ' + + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/VB/form1.vb new file mode 100644 index 0000000000..d53ba49949 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.DisabledButtons/VB/form1.vb @@ -0,0 +1,213 @@ +' This sample shows how to create a custom button column/cell that allows specific +' button cells to be disabled. This is done by rendering the disabled buttons in +' the overridden Paint method with ButtonRenderer. + +' Snippet0 (entire sample) will go in How to: Disable Buttons in a Button Column +' in the Windows Forms DataGridView Control +' Snippet5 will go in DataGridView.CurrentCellDirtyStateChanged, CommitEdit and +' CellValueChanged +' Snippet20 will go in DataGridViewButtonCell.Paint() (and/or DataGridViewCell.Paint?) +' Snippet20 will also go in DataGridViewCell.BorderWidths() + + +' +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.VisualStyles + +Class Form1 + Inherits Form + Private WithEvents dataGridView1 As New DataGridView() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Me.AutoSize = True + End Sub + + Public Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + Dim column0 As New DataGridViewCheckBoxColumn() + Dim column1 As New DataGridViewDisableButtonColumn() + column0.Name = "CheckBoxes" + column1.Name = "Buttons" + dataGridView1.Columns.Add(column0) + dataGridView1.Columns.Add(column1) + + dataGridView1.RowCount = 8 + dataGridView1.AutoSize = True + dataGridView1.AllowUserToAddRows = False + dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = _ + DataGridViewContentAlignment.MiddleCenter + + ' Set the text for each button. + Dim i As Integer + For i = 0 To dataGridView1.RowCount - 1 + dataGridView1.Rows(i).Cells("Buttons").Value = _ + "Button " + i.ToString() + Next i + + Me.Controls.Add(dataGridView1) + + End Sub + + ' + ' This event handler manually raises the CellValueChanged event + ' by calling the CommitEdit method. + Sub dataGridView1_CurrentCellDirtyStateChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles dataGridView1.CurrentCellDirtyStateChanged + + If dataGridView1.IsCurrentCellDirty Then + dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit) + End If + End Sub + + ' If a check box cell is clicked, this event handler disables + ' or enables the button in the same row as the clicked cell. + Public Sub dataGridView1_CellValueChanged(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellValueChanged + + If dataGridView1.Columns(e.ColumnIndex).Name = "CheckBoxes" Then + Dim buttonCell As DataGridViewDisableButtonCell = _ + CType(dataGridView1.Rows(e.RowIndex).Cells("Buttons"), _ + DataGridViewDisableButtonCell) + + Dim checkCell As DataGridViewCheckBoxCell = _ + CType(dataGridView1.Rows(e.RowIndex).Cells("CheckBoxes"), _ + DataGridViewCheckBoxCell) + buttonCell.Enabled = Not CType(checkCell.Value, [Boolean]) + + dataGridView1.Invalidate() + End If + End Sub + ' + + ' If the user clicks on an enabled button cell, this event handler + ' reports that the button is enabled. + Sub dataGridView1_CellClick(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellClick + + If dataGridView1.Columns(e.ColumnIndex).Name = "Buttons" Then + Dim buttonCell As DataGridViewDisableButtonCell = _ + CType(dataGridView1.Rows(e.RowIndex).Cells("Buttons"), _ + DataGridViewDisableButtonCell) + + If buttonCell.Enabled Then + MsgBox(dataGridView1.Rows(e.RowIndex). _ + Cells(e.ColumnIndex).Value.ToString() + _ + " is enabled") + End If + End If + End Sub + +End Class + +' +Public Class DataGridViewDisableButtonColumn + Inherits DataGridViewButtonColumn + + Public Sub New() + Me.CellTemplate = New DataGridViewDisableButtonCell() + End Sub +End Class +' + +Public Class DataGridViewDisableButtonCell + Inherits DataGridViewButtonCell + + Private enabledValue As Boolean + Public Property Enabled() As Boolean + Get + Return enabledValue + End Get + Set(ByVal value As Boolean) + enabledValue = value + End Set + End Property + + ' Override the Clone method so that the Enabled property is copied. + Public Overrides Function Clone() As Object + Dim Cell As DataGridViewDisableButtonCell = _ + CType(MyBase.Clone(), DataGridViewDisableButtonCell) + Cell.Enabled = Me.Enabled + Return Cell + End Function + + ' + ' By default, enable the button cell. + Public Sub New() + Me.enabledValue = True + End Sub + ' + + ' + Protected Overrides Sub Paint(ByVal graphics As Graphics, _ + ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, _ + ByVal rowIndex As Integer, _ + ByVal elementState As DataGridViewElementStates, _ + ByVal value As Object, ByVal formattedValue As Object, _ + ByVal errorText As String, _ + ByVal cellStyle As DataGridViewCellStyle, _ + ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _ + ByVal paintParts As DataGridViewPaintParts) + + ' The button cell is disabled, so paint the border, + ' background, and disabled button for the cell. + If Not Me.enabledValue Then + + ' Draw the background of the cell, if specified. + If (paintParts And DataGridViewPaintParts.Background) = _ + DataGridViewPaintParts.Background Then + + Dim cellBackground As New SolidBrush(cellStyle.BackColor) + graphics.FillRectangle(cellBackground, cellBounds) + cellBackground.Dispose() + End If + + ' Draw the cell borders, if specified. + If (paintParts And DataGridViewPaintParts.Border) = _ + DataGridViewPaintParts.Border Then + + PaintBorder(graphics, clipBounds, cellBounds, cellStyle, _ + advancedBorderStyle) + End If + + ' Calculate the area in which to draw the button. + Dim buttonArea As Rectangle = cellBounds + Dim buttonAdjustment As Rectangle = _ + Me.BorderWidths(advancedBorderStyle) + buttonArea.X += buttonAdjustment.X + buttonArea.Y += buttonAdjustment.Y + buttonArea.Height -= buttonAdjustment.Height + buttonArea.Width -= buttonAdjustment.Width + + ' Draw the disabled button. + ButtonRenderer.DrawButton(graphics, buttonArea, _ + PushButtonState.Disabled) + + ' Draw the disabled button text. + If TypeOf Me.FormattedValue Is String Then + TextRenderer.DrawText(graphics, CStr(Me.FormattedValue), _ + Me.DataGridView.Font, buttonArea, SystemColors.GrayText) + End If + + Else + ' The button cell is enabled, so let the base class + ' handle the painting. + MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, _ + elementState, value, formattedValue, errorText, _ + cellStyle, advancedBorderStyle, paintParts) + End If + End Sub + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/VB/tictactoe.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/VB/tictactoe.vb new file mode 100644 index 0000000000..bf6a6ead05 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ImageColumn_TicTacToe/VB/tictactoe.vb @@ -0,0 +1,408 @@ +' The following code example demonstrates using images to create a +' TicTacToe game. +' +Imports System.IO +Imports System.Windows.Forms +Imports System.Drawing +Public Class TicTacToe + Inherits System.Windows.Forms.Form + + Friend WithEvents dataGridView1 As DataGridView + Friend WithEvents Button1 As Button = New Button() + Friend WithEvents turn As Label = New Label() + Friend WithEvents Button2 As Button = New Button() + Friend WithEvents Button3 As Button = New Button() + Friend WithEvents Button4 As Button = New Button() + Friend WithEvents Button5 As Button = New Button() + Friend WithEvents Panel1 As FlowLayoutPanel = New FlowLayoutPanel() + +#Region "bitmaps" + Private oImage As Byte() = { _ + &H42, &H4D, &HC6, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H76, &H0, &H0, &H0, &H28, &H0, _ + &H0, &H0, &HB, &H0, &H0, &H0, &HA, &H0, _ + &H0, &H0, &H1, &H0, &H4, &H0, &H0, &H0, _ + &H0, &H0, &H50, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H0, &H0, &H0, &H0, &H10, &H0, _ + &H0, &H0, &H10, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H0, &H0, &H80, &H0, &H0, &H80, _ + &H0, &H0, &H0, &H80, &H80, &H0, &H80, &H0, _ + &H0, &H0, &H80, &H0, &H80, &H0, &H80, &H80, _ + &H0, &H0, &HC0, &HC0, &HC0, &H0, &H80, &H80, _ + &H80, &H0, &H0, &H0, &HFF, &H0, &H0, &HFF, _ + &H0, &H0, &H0, &HFF, &HFF, &H0, &HFF, &H0, _ + &H0, &H0, &HFF, &H0, &HFF, &H0, &HFF, &HFF, _ + &H0, &H0, &HFF, &HFF, &HFF, &H0, &HFF, &HFF, _ + &H0, &HF, &HFF, &HF0, &H0, &H0, &HFF, &H0, _ + &HFF, &HF0, &HF, &HF0, &H0, &H0, &HF0, &HFF, _ + &HFF, &HFF, &HF0, &HF0, &H0, &H0, &HF0, &HFF, _ + &HFF, &HFF, &HF0, &HF0, &H0, &H0, &HF, &HFF, _ + &HFF, &HFF, &HFF, &H0, &H0, &H0, &HF, &HFF, _ + &HFF, &HFF, &HFF, &H0, &H0, &H0, &HF0, &HFF, _ + &HFF, &HFF, &HF0, &HF0, &H0, &H0, &HF0, &HFF, _ + &HFF, &HFF, &HF0, &HF0, &H0, &H0, &HFF, &H0, _ + &HFF, &HF0, &HF, &HF0, &H0, &H0, &HFF, &HFF, _ + &H0, &HF, &HFF, &HF0, &H0, &H0} + + Private xImage As Byte() = { _ + &H42, &H4D, &HC6, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H76, &H0, &H0, &H0, &H28, &H0, _ + &H0, &H0, &HB, &H0, &H0, &H0, &HA, &H0, _ + &H0, &H0, &H1, &H0, &H4, &H0, &H0, &H0, _ + &H0, &H0, &H50, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H0, &H0, &H0, &H0, &H10, &H0, _ + &H0, &H0, &H10, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H0, &H0, &H80, &H0, &H0, &H80, _ + &H0, &H0, &H0, &H80, &H80, &H0, &H80, &H0, _ + &H0, &H0, &H80, &H0, &H80, &H0, &H80, &H80, _ + &H0, &H0, &HC0, &HC0, &HC0, &H0, &H80, &H80, _ + &H80, &H0, &H0, &H0, &HFF, &H0, &H0, &HFF, _ + &H0, &H0, &H0, &HFF, &HFF, &H0, &HFF, &H0, _ + &H0, &H0, &HFF, &H0, &HFF, &H0, &HFF, &HFF, _ + &H0, &H0, &HFF, &HFF, &HFF, &H0, &HF0, &HFF, _ + &HFF, &HFF, &HF0, &HF0, &H0, &H0, &HFF, &HF, _ + &HFF, &HFF, &HF, &HF0, &H0, &H0, &HFF, &HF0, _ + &HFF, &HF0, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HF, &HF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HF, &HF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HF, &HF, &HFF, &HF0, &H0, &H0, &HFF, &HF0, _ + &HFF, &HF0, &HFF, &HF0, &H0, &H0, &HFF, &HF, _ + &HFF, &HFF, &HF, &HF0, &H0, &H0, &HF0, &HFF, _ + &HFF, &HFF, &HF0, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0} + + Private blankImage As Byte() = { _ + &H42, &H4D, &HC6, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H76, &H0, &H0, &H0, &H28, &H0, _ + &H0, &H0, &HB, &H0, &H0, &H0, &HA, &H0, _ + &H0, &H0, &H1, &H0, &H4, &H0, &H0, &H0, _ + &H0, &H0, &H50, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H0, &H0, &H0, &H0, &H10, &H0, _ + &H0, &H0, &H10, &H0, &H0, &H0, &H0, &H0, _ + &H0, &H0, &H0, &H0, &H80, &H0, &H0, &H80, _ + &H0, &H0, &H0, &H80, &H80, &H0, &H80, &H0, _ + &H0, &H0, &H80, &H0, &H80, &H0, &H80, &H80, _ + &H0, &H0, &HC0, &HC0, &HC0, &H0, &H80, &H80, _ + &H80, &H0, &H0, &H0, &HFF, &H0, &H0, &HFF, _ + &H0, &H0, &H0, &HFF, &HFF, &H0, &HFF, &H0, _ + &H0, &H0, &HFF, &H0, &HFF, &H0, &HFF, &HFF, _ + &H0, &H0, &HFF, &HFF, &HFF, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0, &HFF, &HFF, _ + &HFF, &HFF, &HFF, &HF0, &H0, &H0} +#End Region + + Private blank As Bitmap = New Bitmap( _ + New MemoryStream(blankImage)) + Private x As Bitmap = New Bitmap(New MemoryStream(xImage)) + Private o As Bitmap = New Bitmap(New MemoryStream(oImage)) + Private xString As String = "X's turn" + Private oString As String = "O's turn" + Private gameOverString As String = "Game Over" + Private bitmapPadding As Integer = 6 + + Private Sub InitializeDataGridView(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Me.Load + SuspendLayout() + Panel1.SuspendLayout() + + ConfigureForm() + SizeGrid() + CreateColumns() + CreateRows() + + ResumeLayout(False) + Panel1.ResumeLayout(False) + End Sub + + Private Sub ConfigureForm() + AutoSize = True + turn.Size = New System.Drawing.Size(75, 34) + turn.TextAlign = ContentAlignment.MiddleLeft + turn.Text = xString + + Panel1.FlowDirection = FlowDirection.TopDown + Panel1.Location = New System.Drawing.Point(0, 8) + Panel1.Size = New System.Drawing.Size(120, 196) + + ClientSize = New System.Drawing.Size(355, 200) + Controls.Add(Me.Panel1) + Text = "TicTacToe" + + dataGridView1 = New System.Windows.Forms.DataGridView + dataGridView1.Location = New Point(120, 0) + dataGridView1.AllowUserToAddRows = False + Controls.Add(dataGridView1) + SetupButtons() + End Sub + + Private Sub SetupButtons() + SetupButton(Button1, "Restart") + Panel1.Controls.Add(Me.turn) + SetupButton(Button2, "Increase Cell Size") + SetupButton(Button3, "Stretch Images") + SetupButton(Button4, "Zoom Images") + SetupButton(Button5, "Normal Images") + End Sub + + Private Sub SetupButton(ByVal button As Button, _ + ByVal buttonLabel As String) + + Panel1.Controls.Add(button) + button.Text = buttonLabel + button.AutoSize = True + + End Sub + + ' + Private Sub CreateColumns() + + Dim imageColumn As DataGridViewImageColumn + Dim columnCount As Integer = 0 + Do + Dim unMarked As Bitmap = blank + imageColumn = New DataGridViewImageColumn() + + ' Add twice the padding for the left and + ' right sides of the cell. + imageColumn.Width = x.Width + 2 * bitmapPadding + 1 + + imageColumn.Image = unMarked + imageColumn.ImageLayout = DataGridViewImageCellLayout.NotSet + imageColumn.Description = "default image layout" + dataGridView1.Columns.Add(imageColumn) + columnCount = columnCount + 1 + Loop While columnCount < 3 + End Sub + ' + + Private Sub CreateRows() + dataGridView1.Rows.Add() + dataGridView1.Rows.Add() + dataGridView1.Rows.Add() + End Sub + + ' + Private Sub SizeGrid() + dataGridView1.ColumnHeadersVisible = False + dataGridView1.RowHeadersVisible = False + dataGridView1.AllowUserToResizeColumns = False + dataGridView1.AllowUserToResizeRows = False + dataGridView1.BorderStyle = BorderStyle.None + + ' Add twice the padding for the top and bottom of the cell. + dataGridView1.RowTemplate.Height = x.Height + _ + 2 * bitmapPadding + 1 + + dataGridView1.AutoSize = True + End Sub + ' + + Private Sub reset(ByVal sender As Object, _ + ByVal e As EventArgs) _ + Handles Button1.Click + + dataGridView1.Dispose() + InitializeDataGridView(Nothing, Nothing) + End Sub + + ' + Private Sub dataGridView1_CellClick(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellClick + + If turn.Text.Equals(gameOverString) Then Return + + Dim cell As DataGridViewImageCell = _ + CType(dataGridView1.Rows(e.RowIndex). _ + Cells(e.ColumnIndex), DataGridViewImageCell) + If (cell.Value Is blank) Then + If IsOsTurn() Then + cell.Value = o + Else + cell.Value = x + End If + ToggleTurn() + ToolTip(e) + End If + If IsAWin() Then + turn.Text = gameOverString + End If + End Sub + ' + + ' + Private Sub dataGridView1_CellMouseEnter(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellMouseEnter + + Dim markingUnderMouse As Bitmap = _ + CType(dataGridView1.Rows(e.RowIndex). _ + Cells(e.ColumnIndex).Value, Bitmap) + + If markingUnderMouse Is blank Then + dataGridView1.Cursor = Cursors.Default + ElseIf markingUnderMouse Is o OrElse markingUnderMouse Is x Then + dataGridView1.Cursor = Cursors.No + ToolTip(e) + End If + End Sub + + Private Sub ToolTip( _ + ByVal e As DataGridViewCellEventArgs) + + Dim cell As DataGridViewImageCell = _ + CType(dataGridView1.Rows(e.RowIndex). _ + Cells(e.ColumnIndex), DataGridViewImageCell) + Dim imageColumn As DataGridViewImageColumn = _ + CType(dataGridView1.Columns(cell.ColumnIndex), _ + DataGridViewImageColumn) + + cell.ToolTipText = imageColumn.Description + End Sub + + Private Sub dataGridView1_CellMouseLeave(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellMouseLeave + + dataGridView1.Cursor = Cursors.Default + End Sub + ' + + ' + Private Sub Stretch(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Button3.Click + + For Each column As DataGridViewImageColumn _ + In dataGridView1.Columns + column.ImageLayout = DataGridViewImageCellLayout.Stretch + column.Description = "Stretched image layout" + Next + End Sub + + Private Sub ZoomToImage(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Button4.Click + + For Each column As DataGridViewImageColumn _ + In dataGridView1.Columns + column.ImageLayout = DataGridViewImageCellLayout.Zoom + column.Description = "Zoomed image layout" + Next + End Sub + + Private Sub NormalImage(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Button5.Click + + For Each column As DataGridViewImageColumn _ + In dataGridView1.Columns + column.ImageLayout = DataGridViewImageCellLayout.Normal + column.Description = "Normal image layout" + Next + End Sub + ' + + Private Sub MakeCellsLarger(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Button2.Click + + For Each column As DataGridViewImageColumn _ + In dataGridView1.Columns + column.Width = column.Width * 2 + Next + For Each row As DataGridViewRow In dataGridView1.Rows + If row.IsNewRow Then Continue For + row.Height = CInt(row.Height * 1.5) + Next + End Sub + + Private Function IsAWin() As Boolean + If ARowIsSame() OrElse AColumnIsSame() OrElse ADiagonalIsSame() Then + Return True + Else + Return False + End If + End Function + + Private Function ARowIsSame() As Boolean + Dim marking As Bitmap = Nothing + If marking Is blank Then Return False + For Each row As DataGridViewRow In dataGridView1.Rows + If row.IsNewRow Then Continue For + marking = CType(row.Cells(0).Value, Bitmap) + If marking IsNot blank Then + If marking Is row.Cells(1).Value AndAlso _ + marking Is row.Cells(2).Value Then Return True + End If + Next + Return False + End Function + + Private Function AColumnIsSame() As Boolean + + Dim columnIndex As Integer = 0 + Dim marking As Bitmap + Do + marking = CType(dataGridView1.Rows(0).Cells(columnIndex).Value, _ + Bitmap) + If marking IsNot blank Then + If marking Is _ + dataGridView1.Rows(1).Cells(columnIndex).Value _ + AndAlso marking Is _ + dataGridView1.Rows(2).Cells(columnIndex).Value _ + Then Return True + End If + columnIndex = columnIndex + 1 + Loop While columnIndex < _ + dataGridView1.Columns.GetColumnCount( _ + DataGridViewElementStates.Visible) + Return False + End Function + + Private Function ADiagonalIsSame() As Boolean + + If LeftToRightDiagonalIsSame() Then Return True + If RightToLeftDiagonalIsSame() Then Return True + Return False + End Function + + Private Function LeftToRightDiagonalIsSame() As Boolean + Return IsDiagonalSame(0, 2) + End Function + + Private Function RightToLeftDiagonalIsSame() As Boolean + Return IsDiagonalSame(2, 0) + End Function + + Private Function IsDiagonalSame(ByVal startingColumn As Integer, _ + ByVal lastColumn As Integer) As Boolean + + Dim marking As Bitmap = CType( _ + dataGridView1.Rows(0).Cells(startingColumn).Value, Bitmap) + If marking Is blank Then Return False + If marking Is dataGridView1.Rows(1).Cells(1).Value AndAlso _ + marking Is dataGridView1.Rows(2).Cells(lastColumn).Value _ + Then Return True + End Function + + Private Sub ToggleTurn() + If turn.Text.Equals(xString) Then turn.Text = oString _ + Else turn.Text = xString + End Sub + + Private Function IsOsTurn() As Boolean + If turn.Text.Equals(oString) Then Return True _ + Else : Return False + End Function + + Public Shared Sub Main() + Application.Run(New TicTacToe()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/VB/programmaticsizing.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/VB/programmaticsizing.vb new file mode 100644 index 0000000000..83613fe169 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.ProgrammaticResizing/VB/programmaticsizing.vb @@ -0,0 +1,304 @@ +Imports System.Windows.Forms +Imports System.Drawing +' +Public Class ProgrammaticSizing + Inherits System.Windows.Forms.Form + +#Region " form setup " + Public Sub New() + MyBase.New() + InitializeComponent() + AddDirections() + + AddButton(Button1, "Reset") + AddButton(Button2, "Change Column 3 Header") + AddButton(Button3, "Change Meatloaf Recipe") + AddButton(Button10, "Change Restaurant 2") + AddButtonsForProgrammaticResizing() + End Sub + + Friend WithEvents DataGridView1 As DataGridView + Friend WithEvents Button1 As Button = New Button() + Friend WithEvents Button2 As Button = New Button() + Friend WithEvents Button3 As Button = New Button() + Friend WithEvents Button4 As Button = New Button() + Friend WithEvents Button5 As Button = New Button() + Friend WithEvents Button6 As Button = New Button() + Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel + Friend WithEvents Button7 As Button = New Button() + Friend WithEvents Button8 As Button = New Button() + Friend WithEvents Button9 As Button = New Button() + Friend WithEvents Button10 As Button = New Button() + Friend WithEvents Button11 As Button = New Button() + + Private Sub InitializeComponent() + Me.FlowLayoutPanel1 = New FlowLayoutPanel + Me.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + Me.FlowLayoutPanel1.Location = New Point(454, 0) + Me.FlowLayoutPanel1.AutoSize = True + + Me.AutoSize = True + Me.Text = Me.GetType().Name + Me.Controls.Add(FlowLayoutPanel1) + End Sub + + Private Sub AddDirections() + Dim directions As New Label() + directions.AutoSize = True + Dim newLine As String = Environment.NewLine + directions.Text = "Press the buttons that start " & newLine _ + & "with 'Change' to see how different sizing " & newLine _ + & "modes deal with content changes." + + FlowLayoutPanel1.Controls.Add(directions) + End Sub + + Public Shared Sub Main() + Application.Run(New ProgrammaticSizing()) + End Sub +#End Region + + Private startingSize As Size + Private thirdColumnHeader As String = "Main Ingredients" + Private boringMeatloaf As String = "ground beef" + Private boringMeatloafRanking As String = "*" + Private boringRecipe As Boolean + Private shortMode As Boolean + Private otherRestaurant As String = "Gomes's Saharan Sushi" + + Private Sub InitializeDataGridView(ByVal ignored As Object, _ + ByVal ignoredToo As EventArgs) Handles Me.Load + Me.DataGridView1 = New System.Windows.Forms.DataGridView + Me.DataGridView1.Name = "DataGridView1" + Me.DataGridView1.Size = New System.Drawing.Size(292, 266) + Me.Controls.Add(Me.DataGridView1) + + startingSize = New Size(450, 400) + DataGridView1.Size = startingSize + + AddColumns() + PopulateRows() + + shortMode = False + boringRecipe = True + End Sub + + Private Sub AddColumns() + DataGridView1.ColumnCount = 4 + DataGridView1.ColumnHeadersVisible = True + + Dim columnHeaderStyle As New DataGridViewCellStyle + columnHeaderStyle.BackColor = Color.Aqua + columnHeaderStyle.Font = New Font("Verdana", 10, _ + FontStyle.Bold) + DataGridView1.ColumnHeadersDefaultCellStyle = _ + columnHeaderStyle + + DataGridView1.Columns(0).Name = "Recipe" + DataGridView1.Columns(1).Name = "Category" + DataGridView1.Columns(2).Name = thirdColumnHeader + DataGridView1.Columns(3).Name = "Rating" + End Sub + + Private Sub PopulateRows() + + Dim row1 As String() = New String() _ + {"Meatloaf", "Main Dish", boringMeatloaf, _ + boringMeatloafRanking} + Dim row2 As String() = New String() _ + {"Key Lime Pie", "Dessert", _ + "lime juice, evaporated milk", _ + "****"} + Dim row3 As String() = New String() _ + {"Orange-Salsa Pork Chops", "Main Dish", _ + "pork chops, salsa, orange juice", "****"} + Dim row4 As String() = New String() _ + {"Black Bean and Rice Salad", "Salad", _ + "black beans, brown rice", _ + "****"} + Dim row5 As String() = New String() _ + {"Chocolate Cheesecake", "Dessert", "cream cheese", _ + "***"} + Dim row6 As String() = New String() _ + {"Black Bean Dip", "Appetizer", _ + "black beans, sour cream", "***"} + Dim rows As Object() = New Object() {row1, row2, row3, _ + row4, row5, row6} + + Dim rowArray As String() + For Each rowArray In rows + DataGridView1.Rows.Add(rowArray) + Next + + For Each row As DataGridViewRow In DataGridView1.Rows + If row.IsNewRow Then Continue For + row.HeaderCell.Value = "Restaurant " & row.Index + Next + + End Sub + + Private Sub AddButton(ByVal button As Button, _ + ByVal buttonLabel As String) + + button.Text = buttonLabel + button.AutoSize = True + button.TabIndex = FlowLayoutPanel1.Controls.Count + FlowLayoutPanel1.Controls.Add(button) + End Sub + + Private Sub ResetToDisorder(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button1.Click + + Controls.Remove(DataGridView1) + DataGridView1.Size = startingSize + DataGridView1.Dispose() + InitializeDataGridView(Nothing, Nothing) + End Sub + + Private Sub ChangeColumn3Header(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button2.Click + + Toggle(shortMode) + If shortMode Then DataGridView1.Columns(2).HeaderText = "S" _ + Else DataGridView1.Columns(2).HeaderText = thirdColumnHeader + End Sub + + Private Shared Function Toggle(ByRef toggleThis As Boolean) _ + As Boolean + + toggleThis = Not toggleThis + End Function + + Private Sub ChangeMeatloafRecipe(ByVal sender As Object, _ + ByVal e As System.EventArgs) _ + Handles Button3.Click + + Toggle(boringRecipe) + If boringRecipe Then + SetMeatloaf(boringMeatloaf, boringMeatloafRanking) + + Else + Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _ + & "1/2 cup bread crumbs, 1/4 cup ketchup," _ + & "1/3 tsp onion powder, " _ + & "1 clove of garlic, 1/2 pack onion soup mix " _ + & " dash of your favorite BBQ Sauce" + SetMeatloaf(greatMeatloafRecipe, "***") + End If + End Sub + + Private Sub SetMeatloaf(ByVal recipe As String, _ + ByVal rating As String) + + DataGridView1.Rows(0).Cells(2).Value = recipe + DataGridView1.Rows(0).Cells(3).Value = rating + End Sub + + Private Sub ChangeRestaurant(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button10.Click + + If DataGridView1.Rows(2).HeaderCell.Value.Equals(otherRestaurant) Then + DataGridView1.Rows(2).HeaderCell.Value = _ + "Restaurant 2" + Else + DataGridView1.Rows(2).HeaderCell.Value = _ + otherRestaurant + End If + + End Sub + +#Region "programmatic resizing" + + Private Sub AddButtonsForProgrammaticResizing() + AddButton(Button4, "Size Third Column") + AddButton(Button5, "Size Column Headers") + AddButton(Button6, "Size All Columns") + AddButton(Button7, "Size Third Row") + AddButton(Button8, "Size First Row Header Using All Headers") + AddButton(Button9, "Size All Rows and Row Headers") + AddButton(Button11, "Size All Rows") + End Sub + + ' The following code example resizes the second column to fit. + ' + Private Sub SizeThirdColumnHeader(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button4.Click + + DataGridView1.AutoResizeColumn( _ + 2, DataGridViewAutoSizeColumnMode.ColumnHeader) + + End Sub + ' + + ' The following code example resizes the second column to fit + ' the header + ' text, but it leaves the widths of the + ' row headers and columns unchanged. + ' + Private Sub SizeColumnHeaders(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button5.Click + + DataGridView1.AutoResizeColumnHeadersHeight(2) + + End Sub + ' + + ' The following code example resizes all the columns to fit the + ' header text and column contents. + ' + Private Sub SizeAllColumns(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button6.Click + + DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells) + + End Sub + ' + + ' The following code example resizes the third row + ' to fit the column contents. + ' + Private Sub SizeThirdRow(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button7.Click + + Dim thirdRow As Integer = 2 + DataGridView1.AutoResizeRow( _ + 2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader) + + End Sub + ' + + ' The following code example resizes the first displayed row + ' to fit it's header. + ' + Private Sub SizeFirstRowHeaderToAllHeaders(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button8.Click + + DataGridView1.AutoResizeRowHeadersWidth( _ + DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders) + + End Sub + ' + + ' Size all the rows, including their headers and columns. + ' + Private Sub SizeAllRowsAndTheirHeaders(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button9.Click + + DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells) + + End Sub + ' + + ' + Private Sub SizeAllRows(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Button11.Click + + DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders) + + End Sub + ' +#End Region +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/VB/datagridviewrowtemplate.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/VB/datagridviewrowtemplate.vb new file mode 100644 index 0000000000..4bafba6f6d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.RowTemplate/VB/datagridviewrowtemplate.vb @@ -0,0 +1,41 @@ +Imports System.Drawing +Imports System.Windows.Forms + +Class Form1 + Inherits Form + + Private dataGridView1 As New DataGridView() + + _ + Public Shared Sub Main() + + Application.Run(New Form1()) + + End Sub + + + Sub New() + + Me.dataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.dataGridView1) + Me.Text = "DataGridView.RowTemplate demo" + + End Sub + + + Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load + + ' + With Me.dataGridView1.RowTemplate + .DefaultCellStyle.BackColor = Color.Bisque + .Height = 35 + .MinimumHeight = 20 + End With + ' + + Me.dataGridView1.ColumnCount = 5 + Me.dataGridView1.RowCount = 10 + + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/VB/form1.vb new file mode 100644 index 0000000000..8f2b724bc5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.SortCompare/VB/form1.vb @@ -0,0 +1,79 @@ +' +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Private WithEvents DataGridView1 As New DataGridView() + + ' Establish the main entry point for the application. + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + ' Initialize the form. + ' This code can be replaced with designer generated code. + Me.DataGridView1.AllowUserToAddRows = False + Me.DataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.DataGridView1) + Me.Text = "DataGridView.SortCompare demo" + + Me.PopulateDataGridView() + End Sub + + '' + ' Replace this with your own population code. + Private Sub PopulateDataGridView() + With Me.DataGridView1 + ' Add columns to the DataGridView. + .ColumnCount = 3 + + ' Set the properties of the DataGridView columns. + .Columns(0).Name = "ID" + .Columns(1).Name = "Name" + .Columns(2).Name = "City" + .Columns("ID").HeaderText = "ID" + .Columns("Name").HeaderText = "Name" + .Columns("City").HeaderText = "City" + End With + + ' Add rows of data to the DataGridView. + With Me.DataGridView1.Rows + .Add(New String() {"1", "Parker", "Seattle"}) + .Add(New String() {"2", "Parker", "New York"}) + .Add(New String() {"3", "Watson", "Seattle"}) + .Add(New String() {"4", "Jameson", "New Jersey"}) + .Add(New String() {"5", "Brock", "New York"}) + .Add(New String() {"6", "Conner", "Portland"}) + End With + + ' Autosize the columns. + Me.DataGridView1.AutoResizeColumns() + + End Sub + ' + + ' + Private Sub DataGridView1_SortCompare( _ + ByVal sender As Object, ByVal e As DataGridViewSortCompareEventArgs) _ + Handles DataGridView1.SortCompare + + ' Try to sort based on the contents of the cell in the current column. + e.SortResult = System.String.Compare(e.CellValue1.ToString(), _ + e.CellValue2.ToString()) + + ' If the cells are equal, sort based on the ID column. + If (e.SortResult = 0) AndAlso Not (e.Column.Name = "ID") Then + e.SortResult = System.String.Compare( _ + DataGridView1.Rows(e.RowIndex1).Cells("ID").Value.ToString(), _ + DataGridView1.Rows(e.RowIndex2).Cells("ID").Value.ToString()) + End If + + e.Handled = True + + End Sub + ' +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb new file mode 100644 index 0000000000..1a5ef71b67 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.VirtualMode/VB/virtualmode.vb @@ -0,0 +1,296 @@ +' The purpose of this snippet is to demonstrate how to use all the primary virtual-mode events. +' Additionally, this example implements row-level commit-scope. To experiment with this feature, +' make some edits in multiple cells within a single row, then click ESC once to revert the edit +' for a single cell, and twice to revert the edit for the entire row. You can commit all edits +' for a row without changing focus by pressing CTRL-ENTER. + +' +' +Imports System.Windows.Forms + +' +Public Class Form1 + Inherits Form + + Private WithEvents dataGridView1 As New DataGridView() + + ' Declare an ArrayList to serve as the data store. + Private customers As New System.Collections.ArrayList() + + ' Declare a Customer object to store data for a row being edited. + Private customerInEdit As Customer + + ' Declare a variable to store the index of a row being edited. + ' A value of -1 indicates that there is no row currently in edit. + Private rowInEdit As Integer = -1 + + ' Declare a variable to indicate the commit scope. + ' Set this value to false to use cell-level commit scope. + Private rowScopeCommit As Boolean = True + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + ' Initialize the form. + Me.dataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.dataGridView1) + Me.Text = "DataGridView virtual-mode demo (row-level commit scope)" + End Sub + ' + + ' + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + ' Enable virtual mode. + Me.dataGridView1.VirtualMode = True + + ' Add columns to the DataGridView. + Dim companyNameColumn As New DataGridViewTextBoxColumn() + With companyNameColumn + .HeaderText = "Company Name" + .Name = "Company Name" + End With + Dim contactNameColumn As New DataGridViewTextBoxColumn() + With contactNameColumn + .HeaderText = "Contact Name" + .Name = "Contact Name" + End With + Me.dataGridView1.Columns.Add(companyNameColumn) + Me.dataGridView1.Columns.Add(contactNameColumn) + Me.dataGridView1.AutoSizeColumnsMode = _ + DataGridViewAutoSizeColumnsMode.AllCells + + ' Add some sample entries to the data store. + Me.customers.Add(New Customer("Bon app'", "Laurence Lebihan")) + Me.customers.Add(New Customer("Bottom-Dollar Markets", _ + "Elizabeth Lincoln")) + Me.customers.Add(New Customer("B's Beverages", "Victoria Ashworth")) + + ' Set the row count, including the row for new records. + Me.dataGridView1.RowCount = 4 + + End Sub + ' + + ' + Private Sub dataGridView1_CellValueNeeded(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellValueEventArgs) _ + Handles dataGridView1.CellValueNeeded + + ' If this is the row for new records, no values are needed. + If e.RowIndex = Me.dataGridView1.RowCount - 1 Then + Return + End If + + Dim customerTmp As Customer = Nothing + + ' Store a reference to the Customer object for the row being painted. + If e.RowIndex = rowInEdit Then + customerTmp = Me.customerInEdit + Else + customerTmp = CType(Me.customers(e.RowIndex), Customer) + End If + + ' Set the cell value to paint using the Customer object retrieved. + Select Case Me.dataGridView1.Columns(e.ColumnIndex).Name + Case "Company Name" + e.Value = customerTmp.CompanyName + + Case "Contact Name" + e.Value = customerTmp.ContactName + End Select + + End Sub + ' + + ' + Private Sub dataGridView1_CellValuePushed(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellValueEventArgs) _ + Handles dataGridView1.CellValuePushed + + Dim customerTmp As Customer = Nothing + + ' Store a reference to the Customer object for the row being edited. + If e.RowIndex < Me.customers.Count Then + + ' If the user is editing a new row, create a new Customer object. + If Me.customerInEdit Is Nothing Then + Me.customerInEdit = New Customer( _ + CType(Me.customers(e.RowIndex), Customer).CompanyName, _ + CType(Me.customers(e.RowIndex), Customer).ContactName) + End If + customerTmp = Me.customerInEdit + Me.rowInEdit = e.RowIndex + + Else + customerTmp = Me.customerInEdit + End If + + ' Set the appropriate Customer property to the cell value entered. + Dim newValue As String = TryCast(e.Value, String) + Select Case Me.dataGridView1.Columns(e.ColumnIndex).Name + Case "Company Name" + customerTmp.CompanyName = newValue + Case "Contact Name" + customerTmp.ContactName = newValue + End Select + + End Sub + ' + + ' + Private Sub dataGridView1_NewRowNeeded(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _ + Handles dataGridView1.NewRowNeeded + + ' Create a new Customer object when the user edits + ' the row for new records. + Me.customerInEdit = New Customer() + Me.rowInEdit = Me.dataGridView1.Rows.Count - 1 + + End Sub + ' + + ' + Private Sub dataGridView1_RowValidated(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ + Handles dataGridView1.RowValidated + + ' Save row changes if any were made and release the edited + ' Customer object if there is one. + If e.RowIndex >= Me.customers.Count AndAlso _ + e.RowIndex <> Me.dataGridView1.Rows.Count - 1 Then + + ' Add the new Customer object to the data store. + Me.customers.Add(Me.customerInEdit) + Me.customerInEdit = Nothing + Me.rowInEdit = -1 + + ElseIf (Me.customerInEdit IsNot Nothing) AndAlso _ + e.RowIndex < Me.customers.Count Then + + ' Save the modified Customer object in the data store. + Me.customers(e.RowIndex) = Me.customerInEdit + Me.customerInEdit = Nothing + Me.rowInEdit = -1 + + ElseIf Me.dataGridView1.ContainsFocus Then + + Me.customerInEdit = Nothing + Me.rowInEdit = -1 + + End If + + End Sub + ' + + ' + Private Sub dataGridView1_RowDirtyStateNeeded(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.QuestionEventArgs) _ + Handles dataGridView1.RowDirtyStateNeeded + + If Not rowScopeCommit Then + + ' In cell-level commit scope, indicate whether the value + ' of the current cell has been modified. + e.Response = Me.dataGridView1.IsCurrentCellDirty + + End If + + End Sub + ' + + ' + Private Sub dataGridView1_CancelRowEdit(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.QuestionEventArgs) _ + Handles dataGridView1.CancelRowEdit + + If Me.rowInEdit = Me.dataGridView1.Rows.Count - 2 AndAlso _ + Me.rowInEdit = Me.customers.Count Then + + ' If the user has canceled the edit of a newly created row, + ' replace the corresponding Customer object with a new, empty one. + Me.customerInEdit = New Customer() + + Else + + ' If the user has canceled the edit of an existing row, + ' release the corresponding Customer object. + Me.customerInEdit = Nothing + Me.rowInEdit = -1 + + End If + + End Sub + ' + + ' + Private Sub dataGridView1_UserDeletingRow(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewRowCancelEventArgs) _ + Handles dataGridView1.UserDeletingRow + + If e.Row.Index < Me.customers.Count Then + + ' If the user has deleted an existing row, remove the + ' corresponding Customer object from the data store. + Me.customers.RemoveAt(e.Row.Index) + + End If + + If e.Row.Index = Me.rowInEdit Then + + ' If the user has deleted a newly created row, release + ' the corresponding Customer object. + Me.rowInEdit = -1 + Me.customerInEdit = Nothing + + End If + + End Sub + ' + ' + +End Class +' +' + +' +Public Class Customer + + Private companyNameValue As String + Private contactNameValue As String + + Public Sub New() + ' Leave fields empty. + End Sub + + Public Sub New(ByVal companyName As String, ByVal contactName As String) + companyNameValue = companyName + contactNameValue = contactName + End Sub + + Public Property CompanyName() As String + Get + Return companyNameValue + End Get + Set(ByVal value As String) + companyNameValue = value + End Set + End Property + + Public Property ContactName() As String + Get + Return contactNameValue + End Get + Set(ByVal value As String) + contactNameValue = value + End Set + End Property + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb new file mode 100644 index 0000000000..966438ee47 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView.Virtual_lazyloading/VB/lazyloading.vb @@ -0,0 +1,378 @@ +' +' +Imports System.Data +Imports System.Data.SqlClient +Imports System.Drawing +Imports System.Windows.Forms + +Public Class VirtualJustInTimeDemo + Inherits System.Windows.Forms.Form + + Private WithEvents dataGridView1 As New DataGridView() + Private memoryCache As Cache + + ' Specify a connection string. Replace the given value with a + ' valid connection string for a Northwind SQL Server sample + ' database accessible to your system. + Private connectionString As String = _ + "Initial Catalog=NorthWind;Data Source=localhost;" & _ + "Integrated Security=SSPI;Persist Security Info=False" + Private table As String = "Orders" + + Private Sub VirtualJustInTimeDemo_Load( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + ' Initialize the form. + With Me + .AutoSize = True + .Controls.Add(Me.dataGridView1) + .Text = "DataGridView virtual-mode just-in-time demo" + End With + + ' Complete the initialization of the DataGridView. + With Me.dataGridView1 + .Size = New Size(800, 250) + .Dock = DockStyle.Fill + .VirtualMode = True + .ReadOnly = True + .AllowUserToAddRows = False + .AllowUserToOrderColumns = False + .SelectionMode = DataGridViewSelectionMode.FullRowSelect + End With + + ' Create a DataRetriever and use it to create a Cache object + ' and to initialize the DataGridView columns and rows. + Try + Dim retriever As New DataRetriever(connectionString, table) + memoryCache = New Cache(retriever, 16) + For Each column As DataColumn In retriever.Columns + dataGridView1.Columns.Add( _ + column.ColumnName, column.ColumnName) + Next + Me.dataGridView1.RowCount = retriever.RowCount + Catch ex As SqlException + MessageBox.Show("Connection could not be established. " & _ + "Verify that the connection string is valid.") + Application.Exit() + End Try + + ' Adjust the column widths based on the displayed values. + Me.dataGridView1.AutoResizeColumns( _ + DataGridViewAutoSizeColumnsMode.DisplayedCells) + + End Sub + + Private Sub dataGridView1_CellValueNeeded( _ + ByVal sender As Object, ByVal e As DataGridViewCellValueEventArgs) _ + Handles dataGridView1.CellValueNeeded + + e.Value = memoryCache.RetrieveElement(e.RowIndex, e.ColumnIndex) + + End Sub + + _ + Public Shared Sub Main() + Application.Run(New VirtualJustInTimeDemo()) + End Sub + +End Class +' + +' +Public Interface IDataPageRetriever + + Function SupplyPageOfData( _ + ByVal lowerPageBoundary As Integer, ByVal rowsPerPage As Integer) _ + As DataTable + +End Interface +' + +' +Public Class DataRetriever + Implements IDataPageRetriever + + Private tableName As String + Private command As SqlCommand + + Public Sub New( _ + ByVal connectionString As String, ByVal tableName As String) + + Dim connection As New SqlConnection(connectionString) + connection.Open() + command = connection.CreateCommand() + Me.tableName = tableName + + End Sub + + Private rowCountValue As Integer = -1 + + Public ReadOnly Property RowCount() As Integer + Get + ' Return the existing value if it has already been determined. + If Not rowCountValue = -1 Then + Return rowCountValue + End If + + ' Retrieve the row count from the database. + command.CommandText = "SELECT COUNT(*) FROM " & tableName + rowCountValue = CInt(command.ExecuteScalar()) + Return rowCountValue + End Get + End Property + + Private columnsValue As DataColumnCollection + + Public ReadOnly Property Columns() As DataColumnCollection + Get + ' Return the existing value if it has already been determined. + If columnsValue IsNot Nothing Then + Return columnsValue + End If + + ' Retrieve the column information from the database. + command.CommandText = "SELECT * FROM " & tableName + Dim adapter As New SqlDataAdapter() + adapter.SelectCommand = command + Dim table As New DataTable() + table.Locale = System.Globalization.CultureInfo.InvariantCulture + adapter.FillSchema(table, SchemaType.Source) + columnsValue = table.Columns + Return columnsValue + End Get + End Property + + Private commaSeparatedListOfColumnNamesValue As String = Nothing + + Private ReadOnly Property CommaSeparatedListOfColumnNames() As String + Get + ' Return the existing value if it has already been determined. + If commaSeparatedListOfColumnNamesValue IsNot Nothing Then + Return commaSeparatedListOfColumnNamesValue + End If + + ' Store a list of column names for use in the + ' SupplyPageOfData method. + Dim commaSeparatedColumnNames As New System.Text.StringBuilder() + Dim firstColumn As Boolean = True + For Each column As DataColumn In Columns + If Not firstColumn Then + commaSeparatedColumnNames.Append(", ") + End If + commaSeparatedColumnNames.Append(column.ColumnName) + firstColumn = False + Next + + commaSeparatedListOfColumnNamesValue = _ + commaSeparatedColumnNames.ToString() + Return commaSeparatedListOfColumnNamesValue + End Get + End Property + + ' Declare variables to be reused by the SupplyPageOfData method. + Private columnToSortBy As String + Private adapter As New SqlDataAdapter() + + Public Function SupplyPageOfData( _ + ByVal lowerPageBoundary As Integer, ByVal rowsPerPage As Integer) _ + As DataTable Implements IDataPageRetriever.SupplyPageOfData + + ' Store the name of the ID column. This column must contain unique + ' values so the SQL below will work properly. + If columnToSortBy Is Nothing Then + columnToSortBy = Me.Columns(0).ColumnName + End If + + If Not Me.Columns(columnToSortBy).Unique Then + Throw New InvalidOperationException(String.Format( _ + "Column {0} must contain unique values.", columnToSortBy)) + End If + + ' Retrieve the specified number of rows from the database, starting + ' with the row specified by the lowerPageBoundary parameter. + command.CommandText = _ + "Select Top " & rowsPerPage & " " & _ + CommaSeparatedListOfColumnNames & " From " & tableName & _ + " WHERE " & columnToSortBy & " NOT IN (SELECT TOP " & _ + lowerPageBoundary & " " & columnToSortBy & " From " & _ + tableName & " Order By " & columnToSortBy & _ + ") Order By " & columnToSortBy + adapter.SelectCommand = command + + Dim table As New DataTable() + table.Locale = System.Globalization.CultureInfo.InvariantCulture + adapter.Fill(table) + Return table + + End Function + +End Class +' + +' +Public Class Cache + + Private Shared RowsPerPage As Integer + + ' Represents one page of data. + Public Structure DataPage + + Public table As DataTable + Private lowestIndexValue As Integer + Private highestIndexValue As Integer + + Public Sub New(ByVal table As DataTable, ByVal rowIndex As Integer) + + Me.table = table + lowestIndexValue = MapToLowerBoundary(rowIndex) + highestIndexValue = MapToUpperBoundary(rowIndex) + System.Diagnostics.Debug.Assert(lowestIndexValue >= 0) + System.Diagnostics.Debug.Assert(highestIndexValue >= 0) + + End Sub + + Public ReadOnly Property LowestIndex() As Integer + Get + Return lowestIndexValue + End Get + End Property + + Public ReadOnly Property HighestIndex() As Integer + Get + Return highestIndexValue + End Get + End Property + + Public Shared Function MapToLowerBoundary( _ + ByVal rowIndex As Integer) As Integer + + ' Return the lowest index of a page containing the given index. + Return (rowIndex \ RowsPerPage) * RowsPerPage + + End Function + + Private Shared Function MapToUpperBoundary( _ + ByVal rowIndex As Integer) As Integer + + ' Return the highest index of a page containing the given index. + Return MapToLowerBoundary(rowIndex) + RowsPerPage - 1 + + End Function + + End Structure + + Private cachePages As DataPage() + Private dataSupply As IDataPageRetriever + + Public Sub New(ByVal dataSupplier As IDataPageRetriever, _ + ByVal rowsPerPage As Integer) + + dataSupply = dataSupplier + Cache.RowsPerPage = rowsPerPage + LoadFirstTwoPages() + + End Sub + + ' Sets the value of the element parameter if the value is in the cache. + Private Function IfPageCached_ThenSetElement(ByVal rowIndex As Integer, _ + ByVal columnIndex As Integer, ByRef element As String) As Boolean + + If IsRowCachedInPage(0, rowIndex) Then + element = cachePages(0).table.Rows(rowIndex Mod RowsPerPage) _ + .Item(columnIndex).ToString() + Return True + ElseIf IsRowCachedInPage(1, rowIndex) Then + element = cachePages(1).table.Rows(rowIndex Mod RowsPerPage) _ + .Item(columnIndex).ToString() + Return True + End If + + Return False + + End Function + + Public Function RetrieveElement(ByVal rowIndex As Integer, _ + ByVal columnIndex As Integer) As String + + Dim element As String = Nothing + If IfPageCached_ThenSetElement(rowIndex, columnIndex, element) Then + Return element + Else + Return RetrieveData_CacheIt_ThenReturnElement( _ + rowIndex, columnIndex) + End If + + End Function + + Private Sub LoadFirstTwoPages() + + cachePages = New DataPage() { _ + New DataPage(dataSupply.SupplyPageOfData( _ + DataPage.MapToLowerBoundary(0), RowsPerPage), 0), _ + New DataPage(dataSupply.SupplyPageOfData( _ + DataPage.MapToLowerBoundary(RowsPerPage), _ + RowsPerPage), RowsPerPage) _ + } + + End Sub + + Private Function RetrieveData_CacheIt_ThenReturnElement( _ + ByVal rowIndex As Integer, ByVal columnIndex As Integer) As String + + ' Retrieve a page worth of data containing the requested value. + Dim table As DataTable = dataSupply.SupplyPageOfData( _ + DataPage.MapToLowerBoundary(rowIndex), RowsPerPage) + + ' Replace the cached page furthest from the requested cell + ' with a new page containing the newly retrieved data. + cachePages(GetIndexToUnusedPage(rowIndex)) = _ + New DataPage(table, rowIndex) + + Return RetrieveElement(rowIndex, columnIndex) + + End Function + + ' Returns the index of the cached page most distant from the given index + ' and therefore least likely to be reused. + Private Function GetIndexToUnusedPage(ByVal rowIndex As Integer) _ + As Integer + + If rowIndex > cachePages(0).HighestIndex AndAlso _ + rowIndex > cachePages(1).HighestIndex Then + + Dim offsetFromPage0 As Integer = _ + rowIndex - cachePages(0).HighestIndex + Dim offsetFromPage1 As Integer = _ + rowIndex - cachePages(1).HighestIndex + If offsetFromPage0 < offsetFromPage1 Then + Return 1 + End If + Return 0 + Else + Dim offsetFromPage0 As Integer = _ + cachePages(0).LowestIndex - rowIndex + Dim offsetFromPage1 As Integer = _ + cachePages(1).LowestIndex - rowIndex + If offsetFromPage0 < offsetFromPage1 Then + Return 1 + End If + Return 0 + End If + + End Function + + ' Returns a value indicating whether the given row index is contained + ' in the given DataPage. + Private Function IsRowCachedInPage( _ + ByVal pageNumber As Integer, ByVal rowIndex As Integer) As Boolean + + Return rowIndex <= cachePages(pageNumber).HighestIndex AndAlso _ + rowIndex >= cachePages(pageNumber).LowestIndex + + End Function + +End Class +' +' + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/VB/collectionbound.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/VB/collectionbound.vb new file mode 100644 index 0000000000..a7d5c4aa03 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridView._CollectionBound/VB/collectionbound.vb @@ -0,0 +1,121 @@ +' +Imports System.Windows.Forms +Imports System.Collections.Generic +' +Public Enum Title + King + Sir +End Enum +' +Public Class EnumsAndComboBox + Inherits Form + + Private flow As New FlowLayoutPanel() + Private WithEvents checkForChange As Button = New Button() + Private knights As List(Of Knight) + Private dataGridView1 As New DataGridView() + + Public Sub New() + MyBase.New() + SetupForm() + SetupGrid() + End Sub + + Private Sub SetupForm() + AutoSize = True + End Sub + + ' + Private Sub SetupGrid() + knights = New List(Of Knight) + knights.Add(New Knight(Title.King, "Uther", True)) + knights.Add(New Knight(Title.King, "Arthur", True)) + knights.Add(New Knight(Title.Sir, "Mordred", False)) + knights.Add(New Knight(Title.Sir, "Gawain", True)) + knights.Add(New Knight(Title.Sir, "Galahad", True)) + + ' Initialize the DataGridView. + dataGridView1.AutoGenerateColumns = False + dataGridView1.AutoSize = True + dataGridView1.DataSource = knights + + dataGridView1.Columns.Add(CreateComboBoxWithEnums()) + + ' Initialize and add a text box column. + Dim column As DataGridViewColumn = _ + New DataGridViewTextBoxColumn() + column.DataPropertyName = "Name" + column.Name = "Knight" + dataGridView1.Columns.Add(column) + + ' Initialize and add a check box column. + column = New DataGridViewCheckBoxColumn() + column.DataPropertyName = "GoodGuy" + column.Name = "Good" + dataGridView1.Columns.Add(column) + + ' Initialize the form. + Controls.Add(dataGridView1) + Me.AutoSize = True + Me.Text = "DataGridView object binding demo" + End Sub + + Private Function CreateComboBoxWithEnums() As DataGridViewComboBoxColumn + Dim combo As New DataGridViewComboBoxColumn() + combo.DataSource = [Enum].GetValues(GetType(Title)) + combo.DataPropertyName = "Title" + combo.Name = "Title" + Return combo + End Function + +#Region "business object" + Private Class Knight + Private hisName As String + Private good As Boolean + Private hisTitle As Title + + Public Sub New(ByVal title As Title, ByVal name As String, _ + ByVal good As Boolean) + + hisTitle = title + hisName = name + Me.good = good + End Sub + + Public Property Name() As String + Get + Return hisName + End Get + + Set(ByVal Value As String) + hisName = Value + End Set + End Property + + Public Property GoodGuy() As Boolean + Get + Return good + End Get + Set(ByVal Value As Boolean) + good = Value + End Set + End Property + + Public Property Title() As Title + Get + Return hisTitle + End Get + Set(ByVal Value As Title) + hisTitle = Value + End Set + End Property + End Class +#End Region + ' + + Public Shared Sub Main() + Application.Run(New EnumsAndComboBox()) + End Sub + +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/VB/datagridviewboundeditable.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/VB/datagridviewboundeditable.vb new file mode 100644 index 0000000000..b523a1a121 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewBoundEditable/VB/datagridviewboundeditable.vb @@ -0,0 +1,98 @@ +Imports System.Data.SqlClient +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Private dataGridView1 As New DataGridView() + Private bindingSource1 As New BindingSource() + Private dataAdapter As New SqlDataAdapter() + Private WithEvents ReloadButton As New Button() + Private WithEvents SubmitButton As New Button() + + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + ' Initialize the form. + Public Sub New() + + dataGridView1.Dock = DockStyle.Fill + + ReloadButton.Text = "Reload" + SubmitButton.Text = "Submit" + + Dim panel As New FlowLayoutPanel With { + .Dock = DockStyle.Top, + .AutoSize = True + } + panel.Controls.AddRange(New Control() {ReloadButton, SubmitButton}) + + Controls.AddRange(New Control() {dataGridView1, panel}) + Text = "DataGridView data binding and updating demo" + + End Sub + + Private Sub GetData(ByVal selectCommand As String) + + Try + ' Specify a connection string. + ' Replace with the SQL Server for your Northwind sample database. + ' Replace "Integrated Security=True" with user login information if necessary. + Dim connectionString As String = + "Data Source=;Initial Catalog=Northwind;" + + "Integrated Security=True;" + + ' Create a new data adapter based on the specified query. + dataAdapter = New SqlDataAdapter(selectCommand, connectionString) + + ' Create a command builder to generate SQL update, insert, and + ' delete commands based on selectCommand. + Dim commandBuilder As New SqlCommandBuilder(dataAdapter) + + ' Populate a new data table and bind it to the BindingSource. + Dim table As New DataTable With { + .Locale = Globalization.CultureInfo.InvariantCulture + } + dataAdapter.Fill(table) + bindingSource1.DataSource = table + + ' Resize the DataGridView columns to fit the newly loaded content. + dataGridView1.AutoResizeColumns( + DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) + + Catch ex As SqlException + MessageBox.Show("To run this example, replace the value of the " + + "connectionString variable with a connection string that is " + + "valid for your system.") + End Try + + End Sub + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + ' Bind the DataGridView to the BindingSource + ' and load the data from the database. + dataGridView1.DataSource = bindingSource1 + GetData("select * from Customers") + + End Sub + + Private Sub ReloadButton_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles ReloadButton.Click + + ' Reload the data from the database. + GetData(dataAdapter.SelectCommand.CommandText) + + End Sub + + Private Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles SubmitButton.Click + + ' Update the database with changes. + dataAdapter.Update(CType(bindingSource1.DataSource, DataTable)) + + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/VB/datagridviewcalendarcolumn.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/VB/datagridviewcalendarcolumn.vb new file mode 100644 index 0000000000..71a438255e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCalendarColumn/VB/datagridviewcalendarcolumn.vb @@ -0,0 +1,285 @@ +' +' +Imports System.Windows.Forms +' + +' +Public Class CalendarColumn + Inherits DataGridViewColumn + + Public Sub New() + MyBase.New(New CalendarCell()) + End Sub + + Public Overrides Property CellTemplate() As DataGridViewCell + Get + Return MyBase.CellTemplate + End Get + Set(ByVal value As DataGridViewCell) + + ' Ensure that the cell used for the template is a CalendarCell. + If (value IsNot Nothing) AndAlso _ + Not value.GetType().IsAssignableFrom(GetType(CalendarCell)) _ + Then + Throw New InvalidCastException("Must be a CalendarCell") + End If + MyBase.CellTemplate = value + + End Set + End Property + +End Class +' + +' +Public Class CalendarCell + Inherits DataGridViewTextBoxCell + + Public Sub New() + ' Use the short date format. + Me.Style.Format = "d" + End Sub + + ' + Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _ + ByVal initialFormattedValue As Object, _ + ByVal dataGridViewCellStyle As DataGridViewCellStyle) + + ' Set the value of the editing control to the current cell value. + MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _ + dataGridViewCellStyle) + + Dim ctl As CalendarEditingControl = _ + CType(DataGridView.EditingControl, CalendarEditingControl) + + ' Use the default row value when Value property is null. + If (Me.Value Is Nothing) Then + ctl.Value = CType(Me.DefaultNewRowValue, DateTime) + Else + ctl.Value = CType(Me.Value, DateTime) + End If + End Sub + ' + + Public Overrides ReadOnly Property EditType() As Type + Get + ' Return the type of the editing control that CalendarCell uses. + Return GetType(CalendarEditingControl) + End Get + End Property + + Public Overrides ReadOnly Property ValueType() As Type + Get + ' Return the type of the value that CalendarCell contains. + Return GetType(DateTime) + End Get + End Property + + Public Overrides ReadOnly Property DefaultNewRowValue() As Object + Get + ' Use the current date and time as the default value. + Return DateTime.Now + End Get + End Property + +End Class +' + +' +Class CalendarEditingControl + Inherits DateTimePicker + Implements IDataGridViewEditingControl + + Private dataGridViewControl As DataGridView + Private valueIsChanged As Boolean = False + Private rowIndexNum As Integer + + Public Sub New() + Me.Format = DateTimePickerFormat.Short + End Sub + + ' + Public Property EditingControlFormattedValue() As Object _ + Implements IDataGridViewEditingControl.EditingControlFormattedValue + + Get + Return Me.Value.ToShortDateString() + End Get + + Set(ByVal value As Object) + Try + ' This will throw an exception of the string is + ' null, empty, or not in the format of a date. + Me.Value = DateTime.Parse(CStr(value)) + Catch + ' In the case of an exception, just use the default + ' value so we're not left with a null value. + Me.Value = DateTime.Now + End Try + End Set + + End Property + ' + + ' + Public Function GetEditingControlFormattedValue(ByVal context _ + As DataGridViewDataErrorContexts) As Object _ + Implements IDataGridViewEditingControl.GetEditingControlFormattedValue + + Return Me.Value.ToShortDateString() + + End Function + ' + + ' + Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As _ + DataGridViewCellStyle) _ + Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl + + Me.Font = dataGridViewCellStyle.Font + Me.CalendarForeColor = dataGridViewCellStyle.ForeColor + Me.CalendarMonthBackground = dataGridViewCellStyle.BackColor + + End Sub + ' + + ' + Public Property EditingControlRowIndex() As Integer _ + Implements IDataGridViewEditingControl.EditingControlRowIndex + + Get + Return rowIndexNum + End Get + Set(ByVal value As Integer) + rowIndexNum = value + End Set + + End Property + ' + + ' + Public Function EditingControlWantsInputKey(ByVal key As Keys, _ + ByVal dataGridViewWantsInputKey As Boolean) As Boolean _ + Implements IDataGridViewEditingControl.EditingControlWantsInputKey + + ' Let the DateTimePicker handle the keys listed. + Select Case key And Keys.KeyCode + Case Keys.Left, Keys.Up, Keys.Down, Keys.Right, _ + Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp + + Return True + + Case Else + Return Not dataGridViewWantsInputKey + End Select + + End Function + ' + + ' + Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _ + Implements IDataGridViewEditingControl.PrepareEditingControlForEdit + + ' No preparation needs to be done. + + End Sub + ' + + ' + Public ReadOnly Property RepositionEditingControlOnValueChange() _ + As Boolean Implements _ + IDataGridViewEditingControl.RepositionEditingControlOnValueChange + + Get + Return False + End Get + + End Property + ' + + ' + Public Property EditingControlDataGridView() As DataGridView _ + Implements IDataGridViewEditingControl.EditingControlDataGridView + + Get + Return dataGridViewControl + End Get + Set(ByVal value As DataGridView) + dataGridViewControl = value + End Set + + End Property + ' + + ' + Public Property EditingControlValueChanged() As Boolean _ + Implements IDataGridViewEditingControl.EditingControlValueChanged + + Get + Return valueIsChanged + End Get + Set(ByVal value As Boolean) + valueIsChanged = value + End Set + + End Property + ' + + ' + Public ReadOnly Property EditingControlCursor() As Cursor _ + Implements IDataGridViewEditingControl.EditingPanelCursor + + Get + Return MyBase.Cursor + End Get + + End Property + ' + + ' + Protected Overrides Sub OnValueChanged(ByVal eventargs As EventArgs) + + ' Notify the DataGridView that the contents of the cell have changed. + valueIsChanged = True + Me.EditingControlDataGridView.NotifyCurrentCellDirty(True) + MyBase.OnValueChanged(eventargs) + + End Sub + ' + +End Class +' + +' +Public Class Form1 + Inherits Form + + Private dataGridView1 As New DataGridView() + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Me.dataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.dataGridView1) + Me.Text = "DataGridView calendar column demo" + End Sub + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + Dim col As New CalendarColumn() + Me.dataGridView1.Columns.Add(col) + Me.dataGridView1.RowCount = 5 + Dim row As DataGridViewRow + For Each row In Me.dataGridView1.Rows + row.Cells(0).Value = DateTime.Now + Next row + + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/VB/datagridviewcell.tooltiptext.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/VB/datagridviewcell.tooltiptext.vb new file mode 100644 index 0000000000..a1f1ba12de --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCell.ToolTipText/VB/datagridviewcell.tooltiptext.vb @@ -0,0 +1,69 @@ +Imports System.Windows.Forms + +Class Form1 + Inherits Form + + Private WithEvents dataGridView1 As New DataGridView() + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Me.dataGridView1.Dock = DockStyle.Fill + ' Set the column header names. + Me.dataGridView1.ColumnCount = 5 + Me.dataGridView1.Columns(0).Name = "Recipe" + Me.dataGridView1.Columns(1).Name = "Category" + Me.dataGridView1.Columns(2).Name = "Main Ingredients" + Me.dataGridView1.Columns(3).Name = "Last Fixed" + Me.dataGridView1.Columns(4).Name = "Rating" + + ' Populate the rows. + Dim row1() As Object = {"Meatloaf", "Main Dish", "ground beef", New DateTime(2000, 3, 23), "*"} + Dim row2() As Object = {"Key Lime Pie", "Dessert", "lime juice, evaporated milk", New DateTime(2002, 4, 12), "****"} + Dim row3() As Object = {"Orange-Salsa Pork Chops", "Main Dish", "pork chops, salsa, orange juice", New DateTime(2000, 8, 9), "****"} + Dim row4() As Object = {"Black Bean and Rice Salad", "Salad", "black beans, brown rice", New DateTime(1999, 5, 7), "****"} + Dim row5() As Object = {"Chocolate Cheesecake", "Dessert", "cream cheese", New DateTime(2003, 3, 12), "***"} + Dim row6() As Object = {"Black Bean Dip", "Appetizer", "black beans, sour cream", New DateTime(2003, 12, 23), "***"} + Dim rows() As Object = {row1, row2, row3, row4, row5, row6} + + Dim rowArray As Object() + For Each rowArray In rows + Me.dataGridView1.Rows.Add(rowArray) + Next rowArray + Me.Controls.Add(Me.dataGridView1) + Me.Text = "DataGridView cell ToolTip demo" + + End Sub + + ' + ' Sets the ToolTip text for cells in the Rating column. + Sub dataGridView1_CellFormatting(ByVal sender As Object, _ + ByVal e As DataGridViewCellFormattingEventArgs) _ + Handles dataGridView1.CellFormatting + + If e.ColumnIndex = Me.dataGridView1.Columns("Rating").Index _ + AndAlso (e.Value IsNot Nothing) Then + + With Me.dataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex) + + If e.Value.Equals("*") Then + .ToolTipText = "very bad" + ElseIf e.Value.Equals("**") Then + .ToolTipText = "bad" + ElseIf e.Value.Equals("***") Then + .ToolTipText = "good" + ElseIf e.Value.Equals("****") Then + .ToolTipText = "very good" + End If + + End With + + End If + + End Sub + ' + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/VB/form1.vb new file mode 100644 index 0000000000..ecf2f512b1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCellPainting/VB/form1.vb @@ -0,0 +1,85 @@ +' +Imports System.Data +Imports System.Data.SqlClient +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Private WithEvents dataGridView1 As New DataGridView() + + Sub New() + + Dim data As New DataTable() + data.Locale = System.Globalization.CultureInfo.InvariantCulture + Dim adapter As New SqlDataAdapter( _ + "select * from customers", _ + "data source=localhost;initial catalog=northwind;" + _ + "integrated security=sspi") + adapter.Fill(data) + + Me.dataGridView1.Dock = DockStyle.Fill + Me.dataGridView1.DataSource = data + Me.Controls.Add(Me.dataGridView1) + Me.Text = "DataGridView.CellPainting demo" + + End Sub + + ' + Private Sub dataGridView1_CellPainting(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) _ + Handles dataGridView1.CellPainting + + If Me.dataGridView1.Columns("ContactName").Index = _ + e.ColumnIndex AndAlso e.RowIndex >= 0 Then + + Dim newRect As New Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1, _ + e.CellBounds.Width - 4, e.CellBounds.Height - 4) + Dim backColorBrush As New SolidBrush(e.CellStyle.BackColor) + Dim gridBrush As New SolidBrush(Me.dataGridView1.GridColor) + Dim gridLinePen As New Pen(gridBrush) + + Try + + ' Erase the cell. + e.Graphics.FillRectangle(backColorBrush, e.CellBounds) + + ' Draw the grid lines (only the right and bottom lines; + ' DataGridView takes care of the others). + e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, _ + e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, _ + e.CellBounds.Bottom - 1) + e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, _ + e.CellBounds.Top, e.CellBounds.Right - 1, _ + e.CellBounds.Bottom) + + ' Draw the inset highlight box. + e.Graphics.DrawRectangle(Pens.Blue, newRect) + + ' Draw the text content of the cell, ignoring alignment. + If (e.Value IsNot Nothing) Then + e.Graphics.DrawString(CStr(e.Value), e.CellStyle.Font, _ + Brushes.Crimson, e.CellBounds.X + 2, e.CellBounds.Y + 2, _ + StringFormat.GenericDefault) + End If + e.Handled = True + + Finally + gridLinePen.Dispose() + gridBrush.Dispose() + backColorBrush.Dispose() + End Try + + End If + + End Sub + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/VB/datagridviewclipboarddemo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/VB/datagridviewclipboarddemo.vb new file mode 100644 index 0000000000..f8161fe1be --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewClipboardDemo/VB/datagridviewclipboarddemo.vb @@ -0,0 +1,82 @@ +' +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Private WithEvents DataGridView1 As New DataGridView() + Private WithEvents CopyPasteButton As New Button() + Private TextBox1 As New TextBox() + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + + Me.DataGridView1.AllowUserToAddRows = False + Me.DataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.DataGridView1) + + Me.CopyPasteButton.Text = "copy/paste selected cells" + Me.CopyPasteButton.Dock = DockStyle.Top + Me.Controls.Add(Me.CopyPasteButton) + + Me.TextBox1.Multiline = True + Me.TextBox1.Height = 100 + Me.TextBox1.Dock = DockStyle.Bottom + Me.Controls.Add(Me.TextBox1) + + Me.Text = "DataGridView Clipboard demo" + + End Sub + + ' + Private Sub Form1_Load(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles Me.Load + + ' Initialize the DataGridView control. + Me.DataGridView1.ColumnCount = 5 + Me.DataGridView1.Rows.Add(New String() {"A", "B", "C", "D", "E"}) + Me.DataGridView1.Rows.Add(New String() {"F", "G", "H", "I", "J"}) + Me.DataGridView1.Rows.Add(New String() {"K", "L", "M", "N", "O"}) + Me.DataGridView1.Rows.Add(New String() {"P", "Q", "R", "S", "T"}) + Me.DataGridView1.Rows.Add(New String() {"U", "V", "W", "X", "Y"}) + Me.DataGridView1.AutoResizeColumns() + ' + Me.DataGridView1.ClipboardCopyMode = _ + DataGridViewClipboardCopyMode.EnableWithoutHeaderText + ' + + End Sub + + ' + Private Sub CopyPasteButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles CopyPasteButton.Click + + If Me.DataGridView1.GetCellCount( _ + DataGridViewElementStates.Selected) > 0 Then + + Try + + ' Add the selection to the clipboard. + Clipboard.SetDataObject( _ + Me.DataGridView1.GetClipboardContent()) + + ' Replace the text box contents with the clipboard text. + Me.TextBox1.Text = Clipboard.GetText() + + Catch ex As System.Runtime.InteropServices.ExternalException + Me.TextBox1.Text = _ + "The Clipboard could not be accessed. Please try again." + End Try + + End If + + End Sub + ' + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb new file mode 100644 index 0000000000..a5d1e16e6b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewComboBoxObjectBinding/vb/form1.vb @@ -0,0 +1,216 @@ +' +Imports System.Text +Imports System.Collections.Generic +Imports System.Windows.Forms + +' +Public Class Form1 + Inherits Form + + Private employees As New List(Of Employee) + Private tasks As New List(Of Task) + Private WithEvents reportButton As New Button + Private WithEvents dataGridView1 As New DataGridView + + _ + Public Sub Main() + Application.Run(New Form1) + End Sub + + Sub New() + dataGridView1.Dock = DockStyle.Fill + dataGridView1.AutoSizeColumnsMode = _ + DataGridViewAutoSizeColumnsMode.AllCells + reportButton.Text = "Generate Report" + reportButton.Dock = DockStyle.Top + + Controls.Add(dataGridView1) + Controls.Add(reportButton) + Text = "DataGridViewComboBoxColumn Demo" + End Sub + + ' Initializes the data source and populates the DataGridView control. + Private Sub Form1_Load(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Me.Load + + PopulateLists() + dataGridView1.AutoGenerateColumns = False + dataGridView1.DataSource = tasks + AddColumns() + + End Sub + + ' Populates the employees and tasks lists. + Private Sub PopulateLists() + employees.Add(New Employee("Harry")) + employees.Add(New Employee("Sally")) + employees.Add(New Employee("Roy")) + employees.Add(New Employee("Pris")) + tasks.Add(New Task(1, employees(1))) + tasks.Add(New Task(2)) + tasks.Add(New Task(3, employees(2))) + tasks.Add(New Task(4)) + End Sub + + ' Configures columns for the DataGridView control. + Private Sub AddColumns() + + Dim idColumn As New DataGridViewTextBoxColumn() + idColumn.Name = "Task" + idColumn.DataPropertyName = "Id" + idColumn.ReadOnly = True + + ' + Dim assignedToColumn As New DataGridViewComboBoxColumn() + + ' Populate the combo box drop-down list with Employee objects. + For Each e As Employee In employees + assignedToColumn.Items.Add(e) + Next + + ' Add "unassigned" to the drop-down list and display it for + ' empty AssignedTo values or when the user presses CTRL+0. + assignedToColumn.Items.Add("unassigned") + assignedToColumn.DefaultCellStyle.NullValue = "unassigned" + ' + + assignedToColumn.Name = "Assigned To" + assignedToColumn.DataPropertyName = "AssignedTo" + assignedToColumn.AutoComplete = True + ' + assignedToColumn.DisplayMember = "Name" + assignedToColumn.ValueMember = "Self" + ' + + ' Add a button column. + Dim buttonColumn As New DataGridViewButtonColumn() + buttonColumn.HeaderText = "" + buttonColumn.Name = "Status Request" + buttonColumn.Text = "Request Status" + buttonColumn.UseColumnTextForButtonValue = True + + dataGridView1.Columns.Add(idColumn) + dataGridView1.Columns.Add(assignedToColumn) + dataGridView1.Columns.Add(buttonColumn) + + End Sub + + ' Reports on task assignments. + Private Sub reportButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles reportButton.Click + + Dim report As New StringBuilder() + For Each t As Task In tasks + Dim assignment As String + If t.AssignedTo Is Nothing Then + assignment = "unassigned" + Else + assignment = "assigned to " + t.AssignedTo.Name + End If + report.AppendFormat("Task {0} is {1}.", t.Id, assignment) + report.Append(Environment.NewLine) + Next + MessageBox.Show(report.ToString(), "Task Assignments") + + End Sub + + ' Calls the Employee.RequestStatus method. + Private Sub dataGridView1_CellClick(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellClick + + ' Ignore clicks that are not on button cells. + If e.RowIndex < 0 OrElse Not e.ColumnIndex = _ + dataGridView1.Columns("Status Request").Index Then Return + + ' Retrieve the task ID. + Dim taskID As Int32 = CInt(dataGridView1(0, e.RowIndex).Value) + + ' + ' Retrieve the Employee object from the "Assigned To" cell. + Dim assignedTo As Employee = TryCast(dataGridView1.Rows(e.RowIndex) _ + .Cells("Assigned To").Value, Employee) + ' + + ' Request status through the Employee object if present. + If assignedTo IsNot Nothing Then + assignedTo.RequestStatus(taskID) + Else + MessageBox.Show(String.Format( _ + "Task {0} is unassigned.", taskID), "Status Request") + End If + + End Sub + +End Class +' + +' +Public Class Task + + Sub New(ByVal id As Int32) + idValue = id + End Sub + + Sub New(ByVal id As Int32, ByVal assignedTo As Employee) + idValue = id + assignedToValue = assignedTo + End Sub + + Private idValue As Int32 + Public Property Id() As Int32 + Get + Return idValue + End Get + Set(ByVal value As Int32) + idValue = value + End Set + End Property + + Private assignedToValue As Employee + Public Property AssignedTo() As Employee + Get + Return assignedToValue + End Get + Set(ByVal value As Employee) + assignedToValue = value + End Set + End Property + +End Class +' + +' +Public Class Employee + + Sub New(ByVal name As String) + nameValue = name + End Sub + + Private nameValue As String + Public Property Name() As String + Get + Return nameValue + End Get + Set(ByVal value As String) + nameValue = value + End Set + End Property + + ' + Public ReadOnly Property Self() As Employee + Get + Return Me + End Get + End Property + ' + + Public Sub RequestStatus(ByVal taskID As Int32) + MessageBox.Show(String.Format( _ + "Status for task {0} has been requested from {1}.", _ + taskID, nameValue), "Status Request") + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/vb/customFormatting.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/vb/customFormatting.vb new file mode 100644 index 0000000000..f01f67ca4c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewCustomizeDataFormatting/vb/customFormatting.vb @@ -0,0 +1,103 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Private WithEvents dataGridView1 As New DataGridView() + Private highPriImage As Bitmap + Private mediumPriImage As Bitmap + Private lowPriImage As Bitmap + + ' + Public Sub New() + + ' Initialize the images. + Try + highPriImage = New Bitmap("highPri.bmp") + mediumPriImage = New Bitmap("mediumPri.bmp") + lowPriImage = New Bitmap("lowPri.bmp") + Catch ex As ArgumentException + MessageBox.Show("The Priority column requires Bitmap images" & _ + "named highPri.bmp, mediumPri.bmp, and lowPri.bmp " & _ + "residing in the same directory as the executable file.") + End Try + + ' Initialize the DataGridView. + With dataGridView1 + .Dock = DockStyle.Fill + .AllowUserToAddRows = False + .Columns.AddRange( _ + New DataGridViewTextBoxColumn(), _ + New DataGridViewImageColumn()) + .Columns(0).Name = "Balance" + .Columns(1).Name = "Priority" + .Rows.Add("-100", "high") + .Rows.Add("0", "medium") + .Rows.Add("100", "low") + End With + + Me.Controls.Add(dataGridView1) + + End Sub + ' + + ' + ' Changes how cells are displayed depending on their columns and values. + Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _ + Handles dataGridView1.CellFormatting + + ' + ' Set the background to red for negative values in the Balance column. + If dataGridView1.Columns(e.ColumnIndex).Name.Equals("Balance") Then + + 'Dim intValue As Int32 + If CInt(e.Value) < 0 Then + 'if Int32.TryParse((String)e.Value, out intValue) && + ' (intValue < 0)) + + e.CellStyle.BackColor = Color.Red + e.CellStyle.SelectionBackColor = Color.DarkRed + End If + End If + ' + + ' + ' Replace string values in the Priority column with images. + If dataGridView1.Columns(e.ColumnIndex).Name.Equals("Priority") Then + + ' Ensure that the value is a string. + Dim stringValue As String = TryCast(e.Value, String) + If stringValue Is Nothing Then Return + + ' Set the cell ToolTip to the text value. + Dim cell As DataGridViewCell = _ + dataGridView1(e.ColumnIndex, e.RowIndex) + cell.ToolTipText = stringValue + + ' Replace the string value with the image value. + Select Case stringValue + + Case "high" + e.Value = highPriImage + Case "medium" + e.Value = mediumPriImage + Case "low" + e.Value = lowPriImage + + End Select + + End If + ' + + End Sub + ' + + Public Sub Main() + Application.Run(New Form1()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb new file mode 100644 index 0000000000..07ffce8514 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewDataValidation/VB/datavalidation.vb @@ -0,0 +1,94 @@ +' +' +Imports System.Data +Imports System.Data.SqlClient +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Private WithEvents dataGridView1 As New DataGridView() + Private bindingSource1 As New BindingSource() + + Public Sub New() + + ' Initialize the form. + Me.dataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(dataGridView1) + Me.Text = "DataGridView validation demo (disallows empty CompanyName)" + + End Sub + ' + + ' + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles Me.Load + + ' Initialize the BindingSource and bind the DataGridView to it. + bindingSource1.DataSource = GetData("select * from Customers") + Me.dataGridView1.DataSource = bindingSource1 + Me.dataGridView1.AutoResizeColumns( _ + DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) + + End Sub + ' + + ' + Private Sub dataGridView1_CellValidating(ByVal sender As Object, _ + ByVal e As DataGridViewCellValidatingEventArgs) _ + Handles dataGridView1.CellValidating + + Dim headerText As String = _ + dataGridView1.Columns(e.ColumnIndex).HeaderText + + ' Abort validation if cell is not in the CompanyName column. + If Not headerText.Equals("CompanyName") Then Return + + ' Confirm that the cell is not empty. + If (String.IsNullOrEmpty(e.FormattedValue.ToString())) Then + dataGridView1.Rows(e.RowIndex).ErrorText = _ + "Company Name must not be empty" + e.Cancel = True + End If + End Sub + + ' + Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ + Handles dataGridView1.CellEndEdit + + ' Clear the row error in case the user presses ESC. + dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty + + End Sub + ' + ' + + ' + Private Shared Function GetData(ByVal selectCommand As String) As DataTable + + Dim connectionString As String = _ + "Integrated Security=SSPI;Persist Security Info=False;" + _ + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096" + + ' Connect to the database and fill a data table. + Dim adapter As New SqlDataAdapter(selectCommand, connectionString) + Dim data As New DataTable() + data.Locale = System.Globalization.CultureInfo.InvariantCulture + adapter.Fill(data) + + Return data + + End Function + ' + + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/vb/fillcolumns.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/vb/fillcolumns.vb new file mode 100644 index 0000000000..107d95c56f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewFillColumnsDemo/vb/fillcolumns.vb @@ -0,0 +1,229 @@ +' +Imports System.ComponentModel +Imports System.Reflection +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Private WithEvents dataGridView1 As New DataGridView() + + Public Sub New() + dataGridView1.Dock = DockStyle.Fill + Controls.Add(dataGridView1) + InitializeDataGridView() + Width = Width * 2 + Text = "Column Fill-Mode Demo" + End Sub + + Private Sub InitializeDataGridView() + + ' Add columns to the DataGridView, binding them to the + ' specified DataGridViewColumn properties. + AddReadOnlyColumn("HeaderText", "Column") + AddColumn("AutoSizeMode") + AddColumn("FillWeight") + AddColumn("MinimumWidth") + AddColumn("Width") + + ' Bind the DataGridView to its own Columns collection. + dataGridView1.AutoGenerateColumns = False + dataGridView1.DataSource = dataGridView1.Columns + + ' Configure the DataGridView so that users can manually change + ' only the column widths, which are set to fill mode. + dataGridView1.AllowUserToAddRows = False + dataGridView1.AllowUserToDeleteRows = False + dataGridView1.AllowUserToResizeRows = False + dataGridView1.RowHeadersWidthSizeMode = _ + DataGridViewRowHeadersWidthSizeMode.DisableResizing + dataGridView1.ColumnHeadersHeightSizeMode = _ + DataGridViewColumnHeadersHeightSizeMode.DisableResizing + dataGridView1.AutoSizeColumnsMode = _ + DataGridViewAutoSizeColumnsMode.Fill + + ' Configure the top left header cell as a reset button. + dataGridView1.TopLeftHeaderCell.Value = "reset" + dataGridView1.TopLeftHeaderCell.Style.ForeColor = _ + System.Drawing.Color.Blue + + End Sub + + Private Sub AddReadOnlyColumn(ByVal dataPropertyName As String, _ + ByVal columnName As String) + + AddColumn(GetType(DataGridViewColumn), dataPropertyName, True, _ + columnName) + End Sub + + Private Sub AddColumn(ByVal dataPropertyName As String) + AddColumn(GetType(DataGridViewColumn), dataPropertyName, False, _ + dataPropertyName) + End Sub + + ' + ' Adds a column to the DataGridView control, binding it to specified + ' property of the specified type and optionally making it read-only. + Private Sub AddColumn( _ + ByVal type As Type, _ + ByVal dataPropertyName As String, _ + ByVal isReadOnly As Boolean, _ + ByVal columnName As String) + + ' Retrieve information about the property through reflection. + Dim propertyInfo1 As PropertyInfo = type.GetProperty(dataPropertyName) + + ' Confirm that the property exists and is accessible. + If propertyInfo1 Is Nothing Then + Throw New ArgumentException("No accessible " & dataPropertyName & _ + " property was found in the " & type.Name & " type.") + End If + + ' Confirm that the property is browsable. + Dim browsables As BrowsableAttribute() = CType( _ + propertyInfo1.GetCustomAttributes(GetType(BrowsableAttribute), _ + False), BrowsableAttribute()) + If browsables.Length > 0 AndAlso Not browsables(0).Browsable Then + Throw New ArgumentException("The " & dataPropertyName & " property has a " & _ + "Browsable(false) attribute, and therefore cannot be bound.") + End If + + ' Create and initialize a column, using a combo box column for + ' enumeration properties, a check box column for Boolean properties, + ' and a text box column otherwise. + Dim column As DataGridViewColumn + Dim valueType As Type = propertyInfo1.PropertyType + + If valueType.IsEnum Then + + column = New DataGridViewComboBoxColumn() + + ' Populate the drop-down list with the enumeration values. + CType(column, DataGridViewComboBoxColumn).DataSource = _ + [Enum].GetValues(valueType) + + ElseIf valueType.Equals(GetType(Boolean)) Then + column = New DataGridViewCheckBoxColumn() + Else + column = New DataGridViewTextBoxColumn() + End If + + ' Initialize and bind the column. + column.ValueType = valueType + column.Name = columnName + column.DataPropertyName = dataPropertyName + column.ReadOnly = isReadOnly + + ' Add the column to the control. + dataGridView1.Columns.Add(column) + + End Sub + ' + + ' + Private Sub ResetDataGridView() + dataGridView1.CancelEdit() + dataGridView1.Columns.Clear() + dataGridView1.DataSource = Nothing + InitializeDataGridView() + End Sub + ' + + Private Sub dataGridView1_CellClick( _ + ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellClick + + If e.ColumnIndex = -1 AndAlso e.RowIndex = -1 Then + ResetDataGridView() + End If + + End Sub + + Private Sub dataGridView1_ColumnWidthChanged( _ + ByVal sender As Object, ByVal e As DataGridViewColumnEventArgs) _ + Handles dataGridView1.ColumnWidthChanged + + ' Invalidate the row corresponding to the column that changed + ' to ensure that the FillWeight and Width entries are updated. + dataGridView1.InvalidateRow(e.Column.Index) + + End Sub + + Private Sub dataGridView1_CurrentCellDirtyStateChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles dataGridView1.CurrentCellDirtyStateChanged + + ' For combo box and check box cells, commit any value change as soon + ' as it is made rather than waiting for the focus to leave the cell. + If Not dataGridView1.CurrentCell.OwningColumn.GetType() _ + .Equals(GetType(DataGridViewTextBoxColumn)) Then + + dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit) + + End If + + End Sub + + Private Sub dataGridView1_DataError( _ + ByVal sender As Object, ByVal e As DataGridViewDataErrorEventArgs) _ + Handles dataGridView1.DataError + + If e.Exception Is Nothing Then Return + + ' If the user-specified value is invalid, cancel the change + ' and display the error icon in the row header. + If Not (e.Context And DataGridViewDataErrorContexts.Commit) = 0 AndAlso _ + (GetType(FormatException).IsAssignableFrom(e.Exception.GetType()) Or _ + GetType(ArgumentException).IsAssignableFrom(e.Exception.GetType())) Then + + dataGridView1.Rows(e.RowIndex).ErrorText = e.Exception.Message + e.Cancel = True + + Else + ' Rethrow any exceptions that aren't related to the user input. + e.ThrowException = True + End If + + End Sub + + Private Sub dataGridView1_CellEndEdit( _ + ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellEndEdit + + ' Ensure that the error icon in the row header is hidden. + dataGridView1.Rows(e.RowIndex).ErrorText = "" + + End Sub + + Private Sub dataGridView1_CellValueChanged( _ + ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellValueChanged + + ' Ignore the change to the top-left header cell. + If e.ColumnIndex < 0 Then Return + + ' Retrieve the property to change. + Dim nameOfPropertyToChange As String = _ + dataGridView1.Columns(e.ColumnIndex).Name + Dim propertyToChange As PropertyInfo = _ + GetType(DataGridViewColumn).GetProperty(nameOfPropertyToChange) + + ' Retrieve the column to change. + Dim nameOfColumnToChange As String = _ + CStr(dataGridView1("Column", e.RowIndex).Value) + Dim columnToChange As DataGridViewColumn = _ + dataGridView1.Columns(nameOfColumnToChange) + + ' Use reflection to update the value of the column property. + propertyToChange.SetValue(columnToChange, _ + dataGridView1(nameOfPropertyToChange, e.RowIndex).Value, Nothing) + + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/VB/form1.vb new file mode 100644 index 0000000000..34f8ac38eb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewIComparerSort/VB/form1.vb @@ -0,0 +1,118 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Private WithEvents DataGridView1 As New DataGridView() + Private FlowLayoutPanel1 As New FlowLayoutPanel() + Private WithEvents Button1 As New Button() + Private RadioButton1 As New RadioButton() + Private RadioButton2 As New RadioButton() + + ' Establish the main entry point for the application. + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + ' Initialize the form. + ' This code can be replaced with designer generated code. + AutoSize = True + Text = "DataGridView IComparer sort demo" + + FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + FlowLayoutPanel1.Location = New System.Drawing.Point(304, 0) + FlowLayoutPanel1.AutoSize = True + + FlowLayoutPanel1.Controls.Add(RadioButton1) + FlowLayoutPanel1.Controls.Add(RadioButton2) + FlowLayoutPanel1.Controls.Add(Button1) + + Button1.Text = "Sort" + RadioButton1.Text = "Ascending" + RadioButton2.Text = "Descending" + RadioButton1.Checked = True + + Controls.Add(FlowLayoutPanel1) + Controls.Add(DataGridView1) + + PopulateDataGridView() + End Sub + + ' Replace this with your own code to populate the DataGridView. + Private Sub PopulateDataGridView() + + DataGridView1.Size = New Size(300, 300) + + ' Add columns to the DataGridView. + DataGridView1.ColumnCount = 2 + + ' Set the properties of the DataGridView columns. + DataGridView1.Columns(0).Name = "First" + DataGridView1.Columns(1).Name = "Last" + DataGridView1.Columns("First").HeaderText = "First Name" + DataGridView1.Columns("Last").HeaderText = "Last Name" + DataGridView1.Columns("First").SortMode = _ + DataGridViewColumnSortMode.Programmatic + DataGridView1.Columns("Last").SortMode = _ + DataGridViewColumnSortMode.Programmatic + + ' Add rows of data to the DataGridView. + DataGridView1.Rows.Add(New String() {"Peter", "Parker"}) + DataGridView1.Rows.Add(New String() {"James", "Jameson"}) + DataGridView1.Rows.Add(New String() {"May", "Parker"}) + DataGridView1.Rows.Add(New String() {"Mary", "Watson"}) + DataGridView1.Rows.Add(New String() {"Eddie", "Brock"}) + End Sub + + ' + Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Button1.Click + If RadioButton1.Checked = True Then + DataGridView1.Sort(New RowComparer(SortOrder.Ascending)) + ElseIf RadioButton2.Checked = True Then + DataGridView1.Sort(New RowComparer(SortOrder.Descending)) + End If + End Sub + + Private Class RowComparer + Implements System.Collections.IComparer + + Private sortOrderModifier As Integer = 1 + + Public Sub New(ByVal sortOrder As SortOrder) + If sortOrder = sortOrder.Descending Then + sortOrderModifier = -1 + ElseIf sortOrder = sortOrder.Ascending Then + + sortOrderModifier = 1 + End If + End Sub + + Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _ + Implements System.Collections.IComparer.Compare + + Dim DataGridViewRow1 As DataGridViewRow = CType(x, DataGridViewRow) + Dim DataGridViewRow2 As DataGridViewRow = CType(y, DataGridViewRow) + + ' Try to sort based on the Last Name column. + Dim CompareResult As Integer = System.String.Compare( _ + DataGridViewRow1.Cells(1).Value.ToString(), _ + DataGridViewRow2.Cells(1).Value.ToString()) + + ' If the Last Names are equal, sort based on the First Name. + If CompareResult = 0 Then + CompareResult = System.String.Compare( _ + DataGridViewRow1.Cells(0).Value.ToString(), _ + DataGridViewRow2.Cells(0).Value.ToString()) + End If + Return CompareResult * sortOrderModifier + End Function + End Class + ' +End Class +' + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb new file mode 100644 index 0000000000..ea5284127c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMasterDetails/VB/masterdetails.vb @@ -0,0 +1,112 @@ +' +' +Imports System.Data +Imports System.Data.SqlClient +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Private masterDataGridView As New DataGridView() + Private masterBindingSource As New BindingSource() + Private detailsDataGridView As New DataGridView() + Private detailsBindingSource As New BindingSource() + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + ' Initializes the form. + Public Sub New() + + masterDataGridView.Dock = DockStyle.Fill + detailsDataGridView.Dock = DockStyle.Fill + + Dim splitContainer1 As New SplitContainer() + splitContainer1.Dock = DockStyle.Fill + splitContainer1.Orientation = Orientation.Horizontal + splitContainer1.Panel1.Controls.Add(masterDataGridView) + splitContainer1.Panel2.Controls.Add(detailsDataGridView) + + Me.Controls.Add(splitContainer1) + Me.Text = "DataGridView master/detail demo" + + End Sub + ' + + ' + Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ + Handles Me.Load + + ' Bind the DataGridView controls to the BindingSource + ' components and load the data from the database. + masterDataGridView.DataSource = masterBindingSource + detailsDataGridView.DataSource = detailsBindingSource + GetData() + + ' Resize the master DataGridView columns to fit the newly loaded data. + masterDataGridView.AutoResizeColumns() + + ' Configure the details DataGridView so that its columns automatically + ' adjust their widths when the data changes. + detailsDataGridView.AutoSizeColumnsMode = _ + DataGridViewAutoSizeColumnsMode.AllCells + + End Sub + ' + + ' + Private Sub GetData() + + Try + ' Specify a connection string. Replace the given value with a + ' valid connection string for a Northwind SQL Server sample + ' database accessible to your system. + Dim connectionString As String = _ + "Integrated Security=SSPI;Persist Security Info=False;" & _ + "Initial Catalog=Northwind;Data Source=localhost" + Dim connection As New SqlConnection(connectionString) + + ' Create a DataSet. + Dim data As New DataSet() + data.Locale = System.Globalization.CultureInfo.InvariantCulture + + ' Add data from the Customers table to the DataSet. + Dim masterDataAdapter As _ + New SqlDataAdapter("select * from Customers", connection) + masterDataAdapter.Fill(data, "Customers") + + ' Add data from the Orders table to the DataSet. + Dim detailsDataAdapter As _ + New SqlDataAdapter("select * from Orders", connection) + detailsDataAdapter.Fill(data, "Orders") + + ' Establish a relationship between the two tables. + Dim relation As New DataRelation("CustomersOrders", _ + data.Tables("Customers").Columns("CustomerID"), _ + data.Tables("Orders").Columns("CustomerID")) + data.Relations.Add(relation) + + ' Bind the master data connector to the Customers table. + masterBindingSource.DataSource = data + masterBindingSource.DataMember = "Customers" + + ' Bind the details data connector to the master data connector, + ' using the DataRelation name to filter the information in the + ' details table based on the current row in the master table. + detailsBindingSource.DataSource = masterBindingSource + detailsBindingSource.DataMember = "CustomersOrders" + Catch ex As SqlException + MessageBox.Show("To run this example, replace the value of the " & _ + "connectionString variable with a connection string that is " & _ + "valid for your system.") + End Try + + End Sub + ' + + ' +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb new file mode 100644 index 0000000000..cc98c27143 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewMisc/VB/datagridviewmisc.vb @@ -0,0 +1,614 @@ +' This file is for miscellaneous, tiny snippets that do not need to exist within a wider scope. +' Do not wrap the entire file in a snippet tag for use in any topic. + +Imports System.Windows.Forms +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing + +Public Class DataGridViewMisc + Inherits Form + + Private WithEvents dataGridView1 As New DataGridView() + + _ + Public Shared Sub Main() + + End Sub + + ' How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control + ' + Private Sub CreateUnboundButtonColumn() + + ' Initialize the button column. + Dim buttonColumn As New DataGridViewButtonColumn + + With buttonColumn + .HeaderText = "Details" + .Name = "Details" + .Text = "View Details" + + ' Use the Text property for the button text for all cells rather + ' than using each cell's value as the text for its own button. + .UseColumnTextForButtonValue = True + End With + + ' Add the button column to the control. + dataGridView1.Columns.Insert(0, buttonColumn) + + End Sub + ' + + ' How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control + Private customersDataGridView As New DataGridView() + Private customersDataSet As New DataSet() + ' + Private Sub BindData() + + With customersDataGridView + .AutoGenerateColumns = True + .DataSource = customersDataSet + .DataMember = "Customers" + End With + + End Sub + ' + + ' How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control + ' + Private Sub SetBorderAndGridlineStyles() + + With Me.dataGridView1 + .GridColor = Color.BlueViolet + .BorderStyle = BorderStyle.Fixed3D + .CellBorderStyle = DataGridViewCellBorderStyle.None + .RowHeadersBorderStyle = _ + DataGridViewHeaderBorderStyle.Single + .ColumnHeadersBorderStyle = _ + DataGridViewHeaderBorderStyle.Single + End With + + End Sub + ' + + ' This version of the above is necessary for the sub-snippets, given the With above. + Private Sub SetBorderAndGridlineStyles2() + + ' + Me.dataGridView1.GridColor = Color.BlueViolet + ' + ' + Me.dataGridView1.BorderStyle = BorderStyle.Fixed3D + ' + ' + With Me.dataGridView1 + .CellBorderStyle = DataGridViewCellBorderStyle.None + .RowHeadersBorderStyle = _ + DataGridViewHeaderBorderStyle.Single + .ColumnHeadersBorderStyle = _ + DataGridViewHeaderBorderStyle.Single + End With + ' + + End Sub + + ' How to: Change the Order of the Columns in the Windows Forms DataGridView Control + ' + Private Sub AdjustColumnOrder() + + With customersDataGridView + .Columns("CustomerID").Visible = False + .Columns("ContactName").DisplayIndex = 0 + .Columns("ContactTitle").DisplayIndex = 1 + .Columns("City").DisplayIndex = 2 + .Columns("Country").DisplayIndex = 3 + .Columns("CompanyName").DisplayIndex = 4 + End With + + End Sub + ' + + ' 1 of 2 for How to: Display Images in Cells of the Windows Forms DataGridView Control + ' + Public Sub CreateGraphicsColumn() + + Dim treeIcon As New Icon(Me.GetType(), "tree.ico") + Dim iconColumn As New DataGridViewImageColumn() + + With iconColumn + .Image = treeIcon.ToBitmap() + .Name = "Tree" + .HeaderText = "Nice tree" + End With + + dataGridView1.Columns.Insert(2, iconColumn) + + End Sub + ' + + ' 2 of 2 for How to: Display Images in Cells of the Windows Forms DataGridView Control + ' + Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _ + Handles dataGridView1.CellFormatting + + If dataGridView1.Columns(e.ColumnIndex).Name = "Icon" Then + If e.RowIndex Mod 5 = 0 Then + Dim bmp As New Bitmap(Me.GetType(), "Bitmap2.bmp") + e.Value = bmp + End If + End If + + End Sub + ' + + ' Put one- and two-liners that don't really need to be wrapped in methods here. + ' If more than ten tiny snippets are needed, create a TinySnippet2() method. + Private Sub TinySnippets() + + ' How to: Enable Column Reordering in the Windows Forms DataGridView Control + ' + dataGridView1.AllowUserToOrderColumns = True + ' + + ' How to: Freeze Columns in the Windows Forms DataGridView Control + ' + Me.dataGridView1.Columns("AddToCartButton").Frozen = True + ' + + ' How to: Hide Column Headers in the Windows Forms DataGridView Control + ' + dataGridView1.ColumnHeadersVisible = False + ' + + ' How to: Hide Columns in the Windows Forms DataGridView Control + ' + Me.dataGridView1.Columns("CustomerID").Visible = False + ' + + ' How to: Make Columns in the Windows Forms DataGridView Control Read-Only + ' + dataGridView1.Columns("CompanyName").ReadOnly = True + ' + + ' How to: Set the Selection Mode of the Windows Forms DataGridView Control + ' + With Me.dataGridView1 + .SelectionMode = DataGridViewSelectionMode.FullRowSelect + .MultiSelect = False + End With + ' + + ' How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control + ' + Me.dataGridView1.Columns("Priority").SortMode = _ + DataGridViewColumnSortMode.Automatic + ' + + ' How to: Specify the Edit Mode for the Windows Forms DataGridView Control + ' + Me.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter + ' + + ' How to: Set Alternating Row Styles for the Windows Forms DataGridView Control + ' + With Me.dataGridView1 + .RowsDefaultCellStyle.BackColor = Color.Bisque + .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige + End With + ' + + ' + Me.dataGridView1.EditingPanel.BorderStyle = BorderStyle.Fixed3D + ' + + End Sub + + ' How to: Format Data in the Windows Forms DataGridView Control + ' + Private Sub SetFormatting() + With Me.dataGridView1 + .Columns("UnitPrice").DefaultCellStyle.Format = "c" + .Columns("ShipDate").DefaultCellStyle.Format = "d" + .Columns("CustomerName").DefaultCellStyle.Alignment = _ + DataGridViewContentAlignment.MiddleRight + .DefaultCellStyle.NullValue = "no entry" + .DefaultCellStyle.WrapMode = DataGridViewTriState.True + End With + End Sub + ' + + ' This version of the above is necessary for the sub-snippets, given the With above. + Private Sub SetFormatting2() + ' + Me.dataGridView1.Columns("UnitPrice").DefaultCellStyle.Format = "c" + Me.dataGridView1.Columns("ShipDate").DefaultCellStyle.Format = "d" + ' + + ' + Me.dataGridView1.Columns("CustomerName").DefaultCellStyle _ + .Alignment = DataGridViewContentAlignment.MiddleRight + ' + + ' + Me.dataGridView1.DefaultCellStyle.NullValue = "no entry" + ' + + ' + Me.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True + ' + End Sub + + ' 1 of 2 for How to: Get and Set the Current Cell in the Windows Forms DataGridView Control + Private WithEvents getCurrentCellButton As New Button() + ' + Private Sub getCurrentCellButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles getCurrentCellButton.Click + + Dim msg As String = String.Format("Row: {0}, Column: {1}", _ + dataGridView1.CurrentCell.RowIndex, _ + dataGridView1.CurrentCell.ColumnIndex) + MessageBox.Show(msg, "Current Cell") + + End Sub + ' + + ' 2 of 2 for How to: Get and Set the Current Cell in the Windows Forms DataGridView Control + Private WithEvents setCurrentCellButton As New Button() + ' + Private Sub setCurrentCellButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles setCurrentCellButton.Click + + ' Set the current cell to the cell in column 1, Row 0. + Me.dataGridView1.CurrentCell = Me.dataGridView1(1, 0) + + End Sub + ' + + ' How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control + ' + Private Sub MakeReadOnly() + + With dataGridView1 + .AllowUserToAddRows = False + .AllowUserToDeleteRows = False + .ReadOnly = True + End With + + End Sub + ' + + ' How to: Set Font and Color Styles in the Windows Forms DataGridView Control + ' + Private Sub SetFontAndColors() + + With Me.dataGridView1.DefaultCellStyle + .Font = New Font("Tahoma", 15) + .ForeColor = Color.Blue + .BackColor = Color.Beige + .SelectionForeColor = Color.Yellow + .SelectionBackColor = Color.Black + End With + + End Sub + ' + + ' This version of the above is necessary for the sub-snippets, given the With above. + Private Sub SetFontAndColors2() + + ' + Me.dataGridView1.DefaultCellStyle.Font = New Font("Tahoma", 15) + ' + + ' + Me.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue + Me.dataGridView1.DefaultCellStyle.BackColor = Color.Beige + ' + + ' + Me.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow + Me.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black + ' + + End Sub + + ' How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control + ' + Private Sub BindDataAndInitializeColumns() + + With dataGridView1 + .AutoGenerateColumns = True + .DataSource = customersDataSet + .Columns.Remove("Fax") + .Columns("CustomerID").Visible = False + End With + + End Sub + ' + + ' This version of the above is necessary for the sub-snippets, given the With above. + Private Sub BindDataAndInitializeColumns2() + + ' + With dataGridView1 + .AutoGenerateColumns = True + .DataSource = customersDataSet + .Columns.Remove("Fax") + End With + ' + ' + dataGridView1.Columns("CustomerID").Visible = False + ' + + End Sub + + ' How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control + Private Function NewCustomerId() As Object + Return New Object() + End Function + ' + Private Sub dataGridView1_DefaultValuesNeeded(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _ + Handles dataGridView1.DefaultValuesNeeded + + With e.Row + .Cells("Region").Value = "WA" + .Cells("City").Value = "Redmond" + .Cells("PostalCode").Value = "98052-6399" + .Cells("Country").Value = "USA" + .Cells("CustomerID").Value = NewCustomerId() + End With + + End Sub + ' + + ' 1 of 2 for How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control + ' + Private Sub dataGridView1_CellValueChanged(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellValueChanged + + Dim msg As String = String.Format( _ + "Cell at row {0}, column {1} value changed", _ + e.RowIndex, e.ColumnIndex) + MessageBox.Show(msg, "Cell Value Changed") + + End Sub + ' + + ' 2 of 2 for How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control + ' + Private Sub dataGridView1_CellStateChanged(ByVal sender As Object, _ + ByVal e As DataGridViewCellStateChangedEventArgs) _ + Handles dataGridView1.CellStateChanged + + Dim state As DataGridViewElementStates = e.StateChanged + Dim msg As String = String.Format( _ + "Row {0}, Column {1}, {2}", _ + e.Cell.RowIndex, e.Cell.ColumnIndex, e.StateChanged) + MessageBox.Show(msg, "Cell State Changed") + + End Sub + ' + + ' How to: Set Default Cell Styles for the Windows Forms DataGridView Control + ' + Private Sub SetDefaultCellStyles() + + Dim highlightCellStyle As New DataGridViewCellStyle + highlightCellStyle.BackColor = Color.Red + + Dim currencyCellStyle As New DataGridViewCellStyle + currencyCellStyle.Format = "C" + currencyCellStyle.ForeColor = Color.Green + + With Me.dataGridView1 + .DefaultCellStyle.BackColor = Color.Beige + .DefaultCellStyle.Font = New Font("Tahoma", 12) + .Rows(3).DefaultCellStyle = highlightCellStyle + .Rows(8).DefaultCellStyle = highlightCellStyle + .Columns("UnitPrice").DefaultCellStyle = currencyCellStyle + .Columns("TotalPrice").DefaultCellStyle = currencyCellStyle + End With + + End Sub + ' + + ' This version of the above is necessary for the sub-snippets, given the With above. + Private Sub SetDefaultCellStyles2() + + ' + Me.dataGridView1.DefaultCellStyle.BackColor = Color.Beige + Me.dataGridView1.DefaultCellStyle.Font = New Font("Tahoma", 12) + ' + + ' + Dim highlightCellStyle As New DataGridViewCellStyle + highlightCellStyle.BackColor = Color.Red + + Dim currencyCellStyle As New DataGridViewCellStyle + currencyCellStyle.Format = "C" + currencyCellStyle.ForeColor = Color.Green + ' + + ' + With Me.dataGridView1 + .Rows(3).DefaultCellStyle = highlightCellStyle + .Rows(8).DefaultCellStyle = highlightCellStyle + .Columns("UnitPrice").DefaultCellStyle = currencyCellStyle + .Columns("TotalPrice").DefaultCellStyle = currencyCellStyle + End With + ' + + End Sub + + ' + Private Sub dataGridView1_Sorted(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles dataGridView1.Sorted + + Me.dataGridView1.FirstDisplayedCell = Me.dataGridView1.CurrentCell + + End Sub + ' + + ' + Private Sub dataGridView1_ColumnHeaderMouseClick(ByVal sender As Object, _ + ByVal e As DataGridViewCellMouseEventArgs) _ + Handles dataGridView1.ColumnHeaderMouseClick + + Dim newColumn As DataGridViewColumn = _ + dataGridView1.Columns(e.ColumnIndex) + Dim oldColumn As DataGridViewColumn = dataGridView1.SortedColumn + Dim direction As ListSortDirection + + ' If oldColumn is null, then the DataGridView is not currently sorted. + If oldColumn IsNot Nothing Then + + ' Sort the same column again, reversing the SortOrder. + If oldColumn Is newColumn AndAlso dataGridView1.SortOrder = _ + SortOrder.Ascending Then + direction = ListSortDirection.Descending + Else + + ' Sort a new column and remove the old SortGlyph. + direction = ListSortDirection.Ascending + oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None + End If + Else + direction = ListSortDirection.Ascending + End If + + ' Sort the selected column. + dataGridView1.Sort(newColumn, direction) + If direction = ListSortDirection.Ascending Then + newColumn.HeaderCell.SortGlyphDirection = SortOrder.Ascending + Else + newColumn.HeaderCell.SortGlyphDirection = SortOrder.Descending + End If + + End Sub + + Private Sub dataGridView1_DataBindingComplete(ByVal sender As Object, _ + ByVal e As DataGridViewBindingCompleteEventArgs) _ + Handles dataGridView1.DataBindingComplete + + ' Put each of the columns into programmatic sort mode. + For Each column As DataGridViewColumn In dataGridView1.Columns + column.SortMode = DataGridViewColumnSortMode.Programmatic + Next + End Sub + ' + + Dim WithEvents clearSelectionButton As Button + ' + Private Sub clearSelectionButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles clearSelectionButton.Click + + dataGridView1.ClearSelection() + + End Sub + ' + + Dim WithEvents selectAllButton As Button + ' + Private Sub selectAllButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles clearSelectionButton.Click + + dataGridView1.SelectAll() + + End Sub + ' + + ' + Private Sub dataGridView1_CellEnter(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellEnter + + dataGridView1(e.ColumnIndex, e.RowIndex).Style _ + .SelectionBackColor = Color.Blue + + End Sub + + Private Sub dataGridView1_CellLeave(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.CellLeave + + dataGridView1(e.ColumnIndex, e.RowIndex).Style _ + .SelectionBackColor = Color.Empty + + End Sub + ' + + ' + Private Sub dataGridView1_RowEnter(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.RowEnter + + Dim i As Integer + For i = 0 To dataGridView1.Rows(e.RowIndex).Cells.Count - 1 + dataGridView1(i, e.RowIndex).Style _ + .BackColor = Color.Yellow + Next i + + End Sub + + Private Sub dataGridView1_RowLeave(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles dataGridView1.RowLeave + + Dim i As Integer + For i = 0 To dataGridView1.Rows(e.RowIndex).Cells.Count - 1 + dataGridView1(i, e.RowIndex).Style _ + .BackColor = Color.Empty + Next i + + End Sub + ' + + ' + Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, _ + ByVal e As DataGridViewEditingControlShowingEventArgs) _ + Handles dataGridView1.EditingControlShowing + + e.CellStyle.BackColor = Color.Aquamarine + + End Sub + ' + + ' + Private Sub dataGridView1_CellBeginEdit(ByVal sender As Object, _ + ByVal e As DataGridViewCellCancelEventArgs) _ + Handles DataGridView1.CellBeginEdit + + Dim msg As String = _ + String.Format("Editing Cell at ({0}, {1})", _ + e.ColumnIndex, e.RowIndex) + Me.Text = msg + + End Sub + + Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _ + ByVal e As DataGridViewCellEventArgs) _ + Handles DataGridView1.CellEndEdit + + Dim msg As String = _ + String.Format("Finished Editing Cell at ({0}, {1})", _ + e.ColumnIndex, e.RowIndex) + Me.Text = msg + + End Sub + ' + + Private Sub DemonstrateIndexer() + + ' + ' Retrieve the cell value for the cell at column 3, row 7. + Dim testValue1 As String = CStr(dataGridView1(3, 7).Value) + + ' Retrieve the cell value for the cell in the Name column at row 4. + Dim testValue2 As String = CStr(dataGridView1("Name", 4).Value) + ' + + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/VB/datagridviewobjectbinding.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/VB/datagridviewobjectbinding.vb new file mode 100644 index 0000000000..fc10f8add4 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewObjectBinding/VB/datagridviewobjectbinding.vb @@ -0,0 +1,93 @@ +' +Imports System.Windows.Forms + +Public Class DataGridViewObjectBinding + Inherits Form + + ' These declarations and the Main() and New() methods + ' below can be replaced with designer-generated code. + Private WithEvents InvoiceButton As New Button() + Private WithEvents DataGridView1 As New DataGridView() + + ' Entry point code. + _ + Public Shared Sub Main() + + Application.Run(New DataGridViewObjectBinding()) + + End Sub + + ' Sets up the form. + Public Sub New() + + Me.DataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.DataGridView1) + + Me.InvoiceButton.Text = "invoice the selected customers" + Me.InvoiceButton.Dock = DockStyle.Top + Me.Controls.Add(Me.InvoiceButton) + Me.Text = "DataGridView collection-binding demo" + + End Sub + + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles MyBase.Load + + ' Set up a collection of objects for binding. + Dim customers As New System.Collections.ArrayList() + customers.Add(New Customer("Harry")) + customers.Add(New Customer("Sally")) + customers.Add(New Customer("Roy")) + customers.Add(New Customer("Pris")) + + ' Initialize and bind the DataGridView. + Me.DataGridView1.SelectionMode = _ + DataGridViewSelectionMode.FullRowSelect + Me.DataGridView1.AutoGenerateColumns = True + Me.DataGridView1.DataSource = customers + + End Sub + + ' Calls the SendInvoice() method for the Customer + ' object bound to each selected row. + ' + Private Sub InvoiceButton_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles InvoiceButton.Click + + For Each row As DataGridViewRow In Me.DataGridView1.SelectedRows + + Dim cust As Customer = TryCast(row.DataBoundItem, Customer) + If cust IsNot Nothing Then + cust.SendInvoice() + End If + + Next + + End Sub + ' + +End Class + +Public Class Customer + + Private nameValue As String + + Public Sub New(ByVal name As String) + nameValue = name + End Sub + + Public Property Name() As String + Get + Return nameValue + End Get + Set(ByVal value As String) + nameValue = value + End Set + End Property + + Public Sub SendInvoice() + MsgBox(nameValue & " has been billed.") + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/VB/form1.vb new file mode 100644 index 0000000000..df334ee144 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewProgrammaticSort/VB/form1.vb @@ -0,0 +1,114 @@ +' +Imports System.ComponentModel +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Private WithEvents sortButton As New Button() + Private WithEvents dataGridView1 As New DataGridView() + + ' Initializes the form. + ' You can replace this code with designer-generated code. + Public Sub New() + With dataGridView1 + .Dock = DockStyle.Fill + .AllowUserToAddRows = False + .SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect + .MultiSelect = False + End With + + sortButton.Dock = DockStyle.Bottom + sortButton.Text = "Sort" + + Controls.Add(dataGridView1) + Controls.Add(sortButton) + Text = "DataGridView programmatic sort demo" + + PopulateDataGridView() + End Sub + + ' Establish the main entry point for the application. + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + ' + ' Populates the DataGridView. + ' Replace this with your own code to populate the DataGridView. + Public Sub PopulateDataGridView() + + ' Add columns to the DataGridView. + dataGridView1.ColumnCount = 2 + dataGridView1.Columns(0).HeaderText = "Last Name" + dataGridView1.Columns(1).HeaderText = "City" + ' Put the new columns into programmatic sort mode + dataGridView1.Columns(0).SortMode = _ + DataGridViewColumnSortMode.Programmatic + dataGridView1.Columns(1).SortMode = _ + DataGridViewColumnSortMode.Programmatic + + + ' Populate the DataGridView. + dataGridView1.Rows.Add(New String() {"Parker", "Seattle"}) + dataGridView1.Rows.Add(New String() {"Watson", "Seattle"}) + dataGridView1.Rows.Add(New String() {"Osborn", "New York"}) + dataGridView1.Rows.Add(New String() {"Jameson", "New York"}) + dataGridView1.Rows.Add(New String() {"Brock", "New Jersey"}) + End Sub + ' + + ' + Private Sub SortButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles sortButton.Click + + ' Check which column is selected, otherwise set NewColumn to Nothing. + Dim newColumn As DataGridViewColumn + If dataGridView1.Columns.GetColumnCount(DataGridViewElementStates _ + .Selected) = 1 Then + newColumn = dataGridView1.SelectedColumns(0) + Else + newColumn = Nothing + End If + + Dim oldColumn As DataGridViewColumn = dataGridView1.SortedColumn + Dim direction As ListSortDirection + + ' If oldColumn is null, then the DataGridView is not currently sorted. + If oldColumn IsNot Nothing Then + + ' Sort the same column again, reversing the SortOrder. + If oldColumn Is newColumn AndAlso dataGridView1.SortOrder = _ + SortOrder.Ascending Then + direction = ListSortDirection.Descending + Else + + ' Sort a new column and remove the old SortGlyph. + direction = ListSortDirection.Ascending + oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None + End If + Else + direction = ListSortDirection.Ascending + End If + + + ' If no column has been selected, display an error dialog box. + If newColumn Is Nothing Then + MessageBox.Show("Select a single column and try again.", _ + "Error: Invalid Selection", MessageBoxButtons.OK, _ + MessageBoxIcon.Error) + Else + dataGridView1.Sort(newColumn, direction) + If direction = ListSortDirection.Ascending Then + newColumn.HeaderCell.SortGlyphDirection = SortOrder.Ascending + Else + newColumn.HeaderCell.SortGlyphDirection = SortOrder.Descending + End If + End If + + End Sub + ' + +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb new file mode 100644 index 0000000000..0f1a0cd3ae --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRolloverCell/VB/rollovercell.vb @@ -0,0 +1,96 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +' +Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Dim dataGridView1 As New DataGridView() + Dim col As New DataGridViewRolloverCellColumn() + dataGridView1.Columns.Add(col) + dataGridView1.Rows.Add(New String() {""}) + dataGridView1.Rows.Add(New String() {""}) + dataGridView1.Rows.Add(New String() {""}) + dataGridView1.Rows.Add(New String() {""}) + Me.Controls.Add(dataGridView1) + Me.Text = "DataGridView rollover-cell demo" + End Sub + +End Class +' + +' +' +Public Class DataGridViewRolloverCell + Inherits DataGridViewTextBoxCell +' + + ' + Protected Overrides Sub Paint( _ + ByVal graphics As Graphics, _ + ByVal clipBounds As Rectangle, _ + ByVal cellBounds As Rectangle, _ + ByVal rowIndex As Integer, _ + ByVal elementState As DataGridViewElementStates, _ + ByVal value As Object, _ + ByVal formattedValue As Object, _ + ByVal errorText As String, _ + ByVal cellStyle As DataGridViewCellStyle, _ + ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _ + ByVal paintParts As DataGridViewPaintParts) + + ' Call the base class method to paint the default cell appearance. + MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, _ + value, formattedValue, errorText, cellStyle, _ + advancedBorderStyle, paintParts) + + ' Retrieve the client location of the mouse pointer. + Dim cursorPosition As Point = _ + Me.DataGridView.PointToClient(Cursor.Position) + + ' If the mouse pointer is over the current cell, draw a custom border. + If cellBounds.Contains(cursorPosition) Then + Dim newRect As New Rectangle(cellBounds.X + 1, _ + cellBounds.Y + 1, cellBounds.Width - 4, _ + cellBounds.Height - 4) + graphics.DrawRectangle(Pens.Red, newRect) + End If + + End Sub + ' + + ' + ' Force the cell to repaint itself when the mouse pointer enters it. + Protected Overrides Sub OnMouseEnter(ByVal rowIndex As Integer) + Me.DataGridView.InvalidateCell(Me) + End Sub + + ' Force the cell to repaint itself when the mouse pointer leaves it. + Protected Overrides Sub OnMouseLeave(ByVal rowIndex As Integer) + Me.DataGridView.InvalidateCell(Me) + End Sub + ' + +' +End Class +' +' + +' +Public Class DataGridViewRolloverCellColumn + Inherits DataGridViewColumn + + Public Sub New() + Me.CellTemplate = New DataGridViewRolloverCell() + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/VB/datagridviewrowpainting.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/VB/datagridviewrowpainting.vb new file mode 100644 index 0000000000..3d93e193d5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewRowPainting/VB/datagridviewrowpainting.vb @@ -0,0 +1,250 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Class DataGridViewRowPainting + Inherits Form + Private WithEvents dataGridView1 As New DataGridView() + Private oldRowIndex As Int32 = 0 + Private Const CUSTOM_CONTENT_HEIGHT As Int32 = 30 + + _ + Public Shared Sub Main() + + Application.Run(New DataGridViewRowPainting()) + + End Sub + + Public Sub New() + + Me.dataGridView1.Dock = DockStyle.Fill + Me.Controls.Add(Me.dataGridView1) + Me.Text = "DataGridView row painting demo" + + End Sub + + Sub DataGridViewRowPainting_Load(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Me.Load + + ' + ' Set a cell padding to provide space for the top of the focus + ' rectangle and for the content that spans multiple columns. + Dim newPadding As New Padding(0, 1, 0, CUSTOM_CONTENT_HEIGHT) + Me.dataGridView1.RowTemplate.DefaultCellStyle.Padding = newPadding + + ' Set the selection background color to transparent so + ' the cell won't paint over the custom selection background. + Me.dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor = _ + Color.Transparent + + ' Set the row height to accommodate the normal cell content and the + ' content that spans multiple columns. + Me.dataGridView1.RowTemplate.Height += CUSTOM_CONTENT_HEIGHT + ' + + ' Initialize other DataGridView properties. + Me.dataGridView1.AllowUserToAddRows = False + Me.dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2 + Me.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None + Me.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect + + ' Set the column header names. + Me.dataGridView1.ColumnCount = 4 + Me.dataGridView1.Columns(0).Name = "Recipe" + Me.dataGridView1.Columns(0).SortMode = _ + DataGridViewColumnSortMode.NotSortable + Me.dataGridView1.Columns(1).Name = "Category" + Me.dataGridView1.Columns(2).Name = "Main Ingredients" + Me.dataGridView1.Columns(3).Name = "Rating" + + ' Hide the column that contains the content that spans + ' multiple columns. + Me.dataGridView1.Columns(2).Visible = False + + ' Populate the rows of the DataGridView. + Dim row1() As String = {"Meatloaf", "Main Dish", _ + "1 lb. lean ground beef, 1/2 cup bread crumbs, " + _ + "1/4 cup ketchup, 1/3 tsp onion powder, 1 clove of garlic, " + _ + "1/2 pack onion soup mix, dash of your favorite BBQ Sauce", "****"} + Dim row2() As String = {"Key Lime Pie", "Dessert", _ + "lime juice, whipped cream, eggs, evaporated milk", "****"} + Dim row3() As String = {"Orange-Salsa Pork Chops", "Main Dish", _ + "pork chops, salsa, orange juice, pineapple", "****"} + Dim row4() As String = {"Black Bean and Rice Salad", "Salad", _ + "black beans, brown rice", "****"} + Dim row5() As String = {"Chocolate Cheesecake", "Dessert", _ + "cream cheese, unsweetened chocolate", "***"} + Dim row6() As String = {"Black Bean Dip", "Appetizer", _ + "black beans, sour cream, salsa, chips", "***"} + Dim rows() As Object = {row1, row2, row3, row4, row5, row6} + Dim rowArray As String() + For Each rowArray In rows + Me.dataGridView1.Rows.Add(rowArray) + Next rowArray + + ' Adjust the row heights to accommodate the normal cell content. + Me.dataGridView1.AutoResizeRows( _ + DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders) + End Sub + + ' + ' Forces the control to repaint itself when the user + ' manually changes the width of a column. + Sub dataGridView1_ColumnWidthChanged(ByVal sender As Object, _ + ByVal e As DataGridViewColumnEventArgs) _ + Handles dataGridView1.ColumnWidthChanged + + Me.dataGridView1.Invalidate() + + End Sub + ' + + ' + ' Forces the row to repaint itself when the user changes the + ' current cell. This is necessary to refresh the focus rectangle. + Sub dataGridView1_CurrentCellChanged(ByVal sender As Object, _ + ByVal e As EventArgs) Handles dataGridView1.CurrentCellChanged + + If oldRowIndex <> -1 Then + Me.dataGridView1.InvalidateRow(oldRowIndex) + End If + oldRowIndex = Me.dataGridView1.CurrentCellAddress.Y + + End Sub + ' + + ' + ' Paints the custom selection background for selected rows. + Sub dataGridView1_RowPrePaint(ByVal sender As Object, _ + ByVal e As DataGridViewRowPrePaintEventArgs) _ + Handles dataGridView1.RowPrePaint + + ' Do not automatically paint the focus rectangle. + e.PaintParts = e.PaintParts And Not DataGridViewPaintParts.Focus + + ' + ' Determine whether the cell should be painted with the + ' custom selection background. + If (e.State And DataGridViewElementStates.Selected) = _ + DataGridViewElementStates.Selected Then + + ' Calculate the bounds of the row. + Dim rowBounds As New Rectangle( _ + Me.dataGridView1.RowHeadersWidth, e.RowBounds.Top, _ + Me.dataGridView1.Columns.GetColumnsWidth( _ + DataGridViewElementStates.Visible) - _ + Me.dataGridView1.HorizontalScrollingOffset + 1, _ + e.RowBounds.Height) + + ' Paint the custom selection background. + Dim backbrush As New _ + System.Drawing.Drawing2D.LinearGradientBrush(rowBounds, _ + Me.dataGridView1.DefaultCellStyle.SelectionBackColor, _ + e.InheritedRowStyle.ForeColor, _ + System.Drawing.Drawing2D.LinearGradientMode.Horizontal) + Try + e.Graphics.FillRectangle(backbrush, rowBounds) + Finally + backbrush.Dispose() + End Try + End If + ' + + End Sub + ' + + ' + ' Paints the content that spans multiple columns and the focus rectangle. + Sub dataGridView1_RowPostPaint(ByVal sender As Object, _ + ByVal e As DataGridViewRowPostPaintEventArgs) _ + Handles dataGridView1.RowPostPaint + + ' Calculate the bounds of the row. + Dim rowBounds As New Rectangle(Me.dataGridView1.RowHeadersWidth, _ + e.RowBounds.Top, Me.dataGridView1.Columns.GetColumnsWidth( _ + DataGridViewElementStates.Visible) - _ + Me.dataGridView1.HorizontalScrollingOffset + 1, e.RowBounds.Height) + + Dim forebrush As SolidBrush = Nothing + Try + ' + ' Determine the foreground color. + If (e.State And DataGridViewElementStates.Selected) = _ + DataGridViewElementStates.Selected Then + + forebrush = New SolidBrush(e.InheritedRowStyle.SelectionForeColor) + Else + forebrush = New SolidBrush(e.InheritedRowStyle.ForeColor) + End If + ' + + ' + ' Get the content that spans multiple columns. + Dim recipe As Object = _ + Me.dataGridView1.Rows.SharedRow(e.RowIndex).Cells(2).Value + + If (recipe IsNot Nothing) Then + Dim text As String = recipe.ToString() + + ' Calculate the bounds for the content that spans multiple + ' columns, adjusting for the horizontal scrolling position + ' and the current row height, and displaying only whole + ' lines of text. + Dim textArea As Rectangle = rowBounds + textArea.X -= Me.dataGridView1.HorizontalScrollingOffset + textArea.Width += Me.dataGridView1.HorizontalScrollingOffset + textArea.Y += rowBounds.Height - e.InheritedRowStyle.Padding.Bottom + textArea.Height -= rowBounds.Height - e.InheritedRowStyle.Padding.Bottom + textArea.Height = (textArea.Height \ e.InheritedRowStyle.Font.Height) * _ + e.InheritedRowStyle.Font.Height + + ' Calculate the portion of the text area that needs painting. + Dim clip As RectangleF = textArea + clip.Width -= Me.dataGridView1.RowHeadersWidth + 1 - clip.X + clip.X = Me.dataGridView1.RowHeadersWidth + 1 + Dim oldClip As RectangleF = e.Graphics.ClipBounds + e.Graphics.SetClip(clip) + + ' Draw the content that spans multiple columns. + e.Graphics.DrawString(text, e.InheritedRowStyle.Font, forebrush, _ + textArea) + + e.Graphics.SetClip(oldClip) + End If + ' + Finally + forebrush.Dispose() + End Try + + If Me.dataGridView1.CurrentCellAddress.Y = e.RowIndex Then + ' Paint the focus rectangle. + e.DrawFocus(rowBounds, True) + End If + + End Sub + ' + + ' + ' Adjusts the padding when the user changes the row height so that + ' the normal cell content is fully displayed and any extra + ' height is used for the content that spans multiple columns. + Sub dataGridView1_RowHeightChanged(ByVal sender As Object, _ + ByVal e As DataGridViewRowEventArgs) _ + Handles dataGridView1.RowHeightChanged + + ' Calculate the new height of the normal cell content. + Dim preferredNormalContentHeight As Int32 = _ + e.Row.GetPreferredHeight(e.Row.Index, _ + DataGridViewAutoSizeRowMode.AllCellsExceptHeader, True) - _ + e.Row.DefaultCellStyle.Padding.Bottom() + + ' Specify a new padding. + Dim newPadding As Padding = e.Row.DefaultCellStyle.Padding + newPadding.Bottom = e.Row.Height - preferredNormalContentHeight + e.Row.DefaultCellStyle.Padding = newPadding + + End Sub + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/VB/DataGridViewSelectedCollections.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/VB/DataGridViewSelectedCollections.vb new file mode 100644 index 0000000000..7518753191 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSelectedCollections/VB/DataGridViewSelectedCollections.vb @@ -0,0 +1,169 @@ +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Private WithEvents dataGridView1 As New DataGridView() + Private WithEvents selectedCellsButton As New Button() + Private WithEvents selectedRowsButton As New Button() + Private WithEvents selectedColumnsButton As New Button() + + Protected Overrides Sub OnLoad(ByVal e As EventArgs) + + Me.dataGridView1.Dock = DockStyle.Fill + Me.dataGridView1.ColumnCount = 5 + Me.dataGridView1.RowCount = 5 + + selectedCellsButton.AutoSize = True + selectedCellsButton.Text = "selected cells" + selectedRowsButton.AutoSize = True + selectedRowsButton.Text = "selected rows" + selectedColumnsButton.AutoSize = True + selectedColumnsButton.Text = "selected columns" + + Dim panel As New FlowLayoutPanel() + panel.Dock = DockStyle.Top + panel.AutoSize = True + panel.Controls.AddRange(New Control() { _ + Me.selectedCellsButton, Me.selectedRowsButton, _ + Me.selectedColumnsButton}) + + Me.Controls.AddRange(New Control() {dataGridView1, panel}) + Me.Text = "DataGridView selected collections demo" + + MyBase.OnLoad(e) + + End Sub + + ' + Private Sub dataGridView1_ColumnHeaderMouseClick( _ + ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs) _ + Handles dataGridView1.ColumnHeaderMouseClick + + Me.dataGridView1.SelectionMode = _ + DataGridViewSelectionMode.ColumnHeaderSelect + Me.dataGridView1.Columns(e.ColumnIndex).HeaderCell _ + .SortGlyphDirection = SortOrder.None + Me.dataGridView1.Columns(e.ColumnIndex).Selected = True + + End Sub + + Private Sub dataGridView1_RowHeaderMouseClick( _ + ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs) _ + Handles dataGridView1.RowHeaderMouseClick + + Me.dataGridView1.SelectionMode = _ + DataGridViewSelectionMode.RowHeaderSelect + Me.dataGridView1.Rows(e.RowIndex).Selected = True + + End Sub + ' + + ' + Private Sub selectedCellsButton_Click( _ + ByVal sender As Object, ByVal e As System.EventArgs) _ + Handles selectedCellsButton.Click + + Dim selectedCellCount As Integer = _ + dataGridView1.GetCellCount(DataGridViewElementStates.Selected) + + If selectedCellCount > 0 Then + + If dataGridView1.AreAllCellsSelected(True) Then + + MessageBox.Show("All cells are selected", "Selected Cells") + + Else + + Dim sb As New System.Text.StringBuilder() + + Dim i As Integer + For i = 0 To selectedCellCount - 1 + + sb.Append("Row: ") + sb.Append(dataGridView1.SelectedCells(i).RowIndex _ + .ToString()) + sb.Append(", Column: ") + sb.Append(dataGridView1.SelectedCells(i).ColumnIndex _ + .ToString()) + sb.Append(Environment.NewLine) + + Next i + + sb.Append("Total: " + selectedCellCount.ToString()) + MessageBox.Show(sb.ToString(), "Selected Cells") + + End If + + End If + + End Sub + ' + + ' + Private Sub selectedRowsButton_Click( _ + ByVal sender As Object, ByVal e As System.EventArgs) _ + Handles selectedRowsButton.Click + + Dim selectedRowCount As Integer = _ + dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected) + + If selectedRowCount > 0 Then + + Dim sb As New System.Text.StringBuilder() + + Dim i As Integer + For i = 0 To selectedRowCount - 1 + + sb.Append("Row: ") + sb.Append(dataGridView1.SelectedRows(i).Index.ToString()) + sb.Append(Environment.NewLine) + + Next i + + sb.Append("Total: " + selectedRowCount.ToString()) + MessageBox.Show(sb.ToString(), "Selected Rows") + + End If + + End Sub + ' + + ' + Private Sub selectedColumnsButton_Click( _ + ByVal sender As Object, ByVal e As System.EventArgs) _ + Handles selectedColumnsButton.Click + + Dim selectedColumnCount As Integer = dataGridView1.Columns _ + .GetColumnCount(DataGridViewElementStates.Selected) + + If selectedColumnCount > 0 Then + + Dim sb As New System.Text.StringBuilder() + + Dim i As Integer + For i = 0 To selectedColumnCount - 1 + + sb.Append("Column: ") + sb.Append(dataGridView1.SelectedColumns(i).Index.ToString()) + sb.Append(Environment.NewLine) + + Next i + + sb.Append("Total: " + selectedColumnCount.ToString()) + MessageBox.Show(sb.ToString(), "Selected Columns") + + End If + + End Sub + ' + +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb new file mode 100644 index 0000000000..3e0b9adc99 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSimpleUnbound/VB/simpleunbound.vb @@ -0,0 +1,185 @@ +' +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Private buttonPanel As New Panel + Private WithEvents songsDataGridView As New DataGridView + Private WithEvents addNewRowButton As New Button + Private WithEvents deleteRowButton As New Button + ' + + ' + Private Sub Form1_Load(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles MyBase.Load + + SetupLayout() + SetupDataGridView() + PopulateDataGridView() + + End Sub + + Private Sub songsDataGridView_CellFormatting(ByVal sender As Object, _ + ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _ + Handles songsDataGridView.CellFormatting + + If e IsNot Nothing Then + + If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _ + "Release Date" Then + If e.Value IsNot Nothing Then + Try + e.Value = DateTime.Parse(e.Value.ToString()) _ + .ToLongDateString() + e.FormattingApplied = True + Catch ex As FormatException + Console.WriteLine("{0} is not a valid date.", e.Value.ToString()) + End Try + End If + End If + + End If + + End Sub + + Private Sub addNewRowButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles addNewRowButton.Click + + Me.songsDataGridView.Rows.Add() + + End Sub + + Private Sub deleteRowButton_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles deleteRowButton.Click + + If Me.songsDataGridView.SelectedRows.Count > 0 AndAlso _ + Not Me.songsDataGridView.SelectedRows(0).Index = _ + Me.songsDataGridView.Rows.Count - 1 Then + + Me.songsDataGridView.Rows.RemoveAt( _ + Me.songsDataGridView.SelectedRows(0).Index) + + End If + + End Sub + ' + + ' + Private Sub SetupLayout() + + Me.Size = New Size(600, 500) + + With addNewRowButton + .Text = "Add Row" + .Location = New Point(10, 10) + End With + + With deleteRowButton + .Text = "Delete Row" + .Location = New Point(100, 10) + End With + + With buttonPanel + .Controls.Add(addNewRowButton) + .Controls.Add(deleteRowButton) + .Height = 50 + .Dock = DockStyle.Bottom + End With + + Me.Controls.Add(Me.buttonPanel) + + End Sub + ' + + ' + Private Sub SetupDataGridView() + + Me.Controls.Add(songsDataGridView) + + songsDataGridView.ColumnCount = 5 + With songsDataGridView.ColumnHeadersDefaultCellStyle + .BackColor = Color.Navy + .ForeColor = Color.White + .Font = New Font(songsDataGridView.Font, FontStyle.Bold) + End With + + With songsDataGridView + .Name = "songsDataGridView" + .Location = New Point(8, 8) + .Size = New Size(500, 250) + .AutoSizeRowsMode = _ + DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders + .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single + .CellBorderStyle = DataGridViewCellBorderStyle.Single + .GridColor = Color.Black + .RowHeadersVisible = False + + .Columns(0).Name = "Release Date" + .Columns(1).Name = "Track" + .Columns(2).Name = "Title" + .Columns(3).Name = "Artist" + .Columns(4).Name = "Album" + .Columns(4).DefaultCellStyle.Font = _ + New Font(Me.songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic) + + .SelectionMode = DataGridViewSelectionMode.FullRowSelect + .MultiSelect = False + .Dock = DockStyle.Fill + End With + + End Sub + ' + + ' + Private Sub PopulateDataGridView() + + Dim row0 As String() = {"11/22/1968", "29", "Revolution 9", _ + "Beatles", "The Beatles [White Album]"} + Dim row1 As String() = {"1960", "6", "Fools Rush In", _ + "Frank Sinatra", "Nice 'N' Easy"} + Dim row2 As String() = {"11/11/1971", "1", "One of These Days", _ + "Pink Floyd", "Meddle"} + Dim row3 As String() = {"1988", "7", "Where Is My Mind?", _ + "Pixies", "Surfer Rosa"} + Dim row4 As String() = {"5/1981", "9", "Can't Find My Mind", _ + "Cramps", "Psychedelic Jungle"} + Dim row5 As String() = {"6/10/2003", "13", _ + "Scatterbrain. (As Dead As Leaves.)", _ + "Radiohead", "Hail to the Thief"} + Dim row6 As String() = {"6/30/1992", "3", "Dress", "P J Harvey", "Dry"} + + With Me.songsDataGridView.Rows + .Add(row0) + .Add(row1) + .Add(row2) + .Add(row3) + .Add(row4) + .Add(row5) + .Add(row6) + End With + + With Me.songsDataGridView + .Columns(0).DisplayIndex = 3 + .Columns(1).DisplayIndex = 4 + .Columns(2).DisplayIndex = 0 + .Columns(3).DisplayIndex = 1 + .Columns(4).DisplayIndex = 2 + End With + + End Sub + ' + + ' + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb new file mode 100644 index 0000000000..9b9a9b32d3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataGridViewSizingScenarios/vb/sizingscenarios.vb @@ -0,0 +1,77 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Private dataGridView1 As New DataGridView() + + Public Sub New() + dataGridView1.Dock = DockStyle.Fill + Controls.Add(dataGridView1) + Width *= 2 + Text = "DataGridView Sizing Scenarios" + End Sub + + Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) + + ' + Dim idColumn As New DataGridViewTextBoxColumn() + idColumn.HeaderText = "ID" + idColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None + idColumn.Resizable = DataGridViewTriState.False + idColumn.ReadOnly = True + idColumn.Width = 20 + ' + + ' + Dim titleColumn As New DataGridViewTextBoxColumn() + titleColumn.HeaderText = "Title" + titleColumn.AutoSizeMode = _ + DataGridViewAutoSizeColumnMode.AllCellsExceptHeader + ' + + ' + dataGridView1.AutoSizeColumnsMode = _ + DataGridViewAutoSizeColumnsMode.Fill + + Dim subTitleColumn As new DataGridViewTextBoxColumn() + subTitleColumn.HeaderText = "Subtitle" + subTitleColumn.MinimumWidth = 50 + subTitleColumn.FillWeight = 100 + + Dim summaryColumn As new DataGridViewTextBoxColumn() + summaryColumn.HeaderText = "Summary" + summaryColumn.MinimumWidth = 50 + summaryColumn.FillWeight = 200 + + Dim contentColumn As new DataGridViewTextBoxColumn() + contentColumn.HeaderText = "Content" + contentColumn.MinimumWidth = 50 + contentColumn.FillWeight = 300 + ' + + ' + dataGridView1.Columns.AddRange(New DataGridViewTextBoxColumn() { _ + idColumn, titleColumn, subTitleColumn, _ + summaryColumn, contentColumn}) + dataGridView1.Rows.Add(New String() {"1", _ + "A Short Title", "A Longer SubTitle", _ + "A short description of the main point.", _ + "The full contents of the topic, with detailed examples."}) + ' + + MyBase.OnLoad(e) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/VB/form1.vb new file mode 100644 index 0000000000..cd8c8c7f45 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DataNavigator/VB/form1.vb @@ -0,0 +1,82 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Data.SqlClient +Imports System.Windows.Forms + + +' This form demonstrates using a BindingNavigator to display +' rows from a database query sequentially. +Public Class Form1 + Inherits Form + ' This is the BindingNavigator that allows the user + ' to navigate through the rows in a DataSet. + Private customersBindingNavigator As New BindingNavigator(True) + + ' This is the BindingSource that provides data for + ' the Textbox control. + Private customersBindingSource As New BindingSource() + + ' This is the TextBox control that displays the CompanyName + ' field from the DataSet. + Private companyNameTextBox As New TextBox() + + + Public Sub New() + ' Set up the BindingSource component. + Me.customersBindingNavigator.BindingSource = Me.customersBindingSource + Me.customersBindingNavigator.Dock = DockStyle.Top + Me.Controls.Add(Me.customersBindingNavigator) + + ' Set up the TextBox control for displaying company names. + Me.companyNameTextBox.Dock = DockStyle.Bottom + Me.Controls.Add(Me.companyNameTextBox) + + ' Set up the form. + Me.Size = New Size(800, 200) + AddHandler Me.Load, AddressOf Form1_Load + + End Sub + + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) + ' Open a connection to the database. + ' Replace the value of connectString with a valid + ' connection string to a Northwind database accessible + ' to your system. + Dim connectString As String = _ + "Integrated Security=SSPI;Persist Security Info=False;" & _ + "Initial Catalog=Northwind;Data Source=localhost" + + Dim connection As New SqlConnection(connectString) + Try + + Dim dataAdapter1 As New SqlDataAdapter( _ + New SqlCommand("Select * From Customers", connection)) + Dim ds As New DataSet("Northwind Customers") + ds.Tables.Add("Customers") + dataAdapter1.Fill(ds.Tables("Customers")) + + ' Assign the DataSet as the DataSource for the BindingSource. + Me.customersBindingSource.DataSource = ds.Tables("Customers") + + ' Bind the CompanyName field to the TextBox control. + Me.companyNameTextBox.DataBindings.Add(New Binding("Text", _ + Me.customersBindingSource, "CompanyName", True)) + Finally + connection.Dispose() + End Try + + End Sub + + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePicker/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePicker/VB/form1.vb new file mode 100644 index 0000000000..67008cfa63 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePicker/VB/form1.vb @@ -0,0 +1,117 @@ +' This example demonstrates using the read-only fields DateTimePicker.MaxDateTime +' and DateTimePicker.MinDateTime. + +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + +#Region " Windows Form Designer generated code " + + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + InitializeDateTimePicker() + + 'Add any initialization after the InitializeComponent() call + + End Sub + + 'Form overrides dispose to clean up the component list. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + 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. + + Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container + + Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components) + Me.SuspendLayout() + ' + 'DateTimePicker1 + ' + + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + +#End Region + + Public Shared Sub Main() + Application.Run(New Form1) + End Sub + + + ' + + ' Declare the DateTimePicker. + Friend WithEvents DateTimePicker1 As System.Windows.Forms.DateTimePicker + + + Private Sub InitializeDateTimePicker() + + ' Construct the DateTimePicker. + Me.DateTimePicker1 = New System.Windows.Forms.DateTimePicker + + 'Set size and location. + Me.DateTimePicker1.Location = New System.Drawing.Point(40, 88) + Me.DateTimePicker1.Size = New Size(160, 21) + + ' Set the alignment of the drop-down MonthCalendar to right. + Me.DateTimePicker1.DropDownAlign = LeftRightAlignment.Right + + ' Set the Value property to 50 years before today. + DateTimePicker1.Value = (DateTime.Now.AddYears(-50)) + + 'Set a custom format containing the string "of the year" + DateTimePicker1.Format = DateTimePickerFormat.Custom + DateTimePicker1.CustomFormat = "MMM dd, 'of the year' yyyy " + + ' Add the DateTimePicker to the form. + Me.Controls.Add(Me.DateTimePicker1) + End Sub + ' + + ' + + ' When the calendar drops down, display a MessageBox indicating + ' that DateTimePicker will not accept dates before MinDateTime or + ' after MaxDateTime. Use a StringBuilder object to build the string + ' for efficiency. + Private Sub DateTimePicker1_DropDown(ByVal sender As Object, _ + ByVal e As EventArgs) Handles DateTimePicker1.DropDown + + Dim messageBuilder As New System.Text.StringBuilder + messageBuilder.Append("Choose a date after: ") + messageBuilder.Append(DateTimePicker.MinDateTime.ToShortDateString) + messageBuilder.Append(" and a date before: ") + messageBuilder.Append(DateTimePicker.MaxDateTime.ToShortDateString) + MessageBox.Show(messageBuilder.ToString()) + End Sub + ' + + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/VB/Form1.vb new file mode 100644 index 0000000000..a8dd90e573 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DateTimePickerTimeOnly/VB/Form1.vb @@ -0,0 +1,41 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeTimePicker() + + End Sub + ' + Private timePicker As DateTimePicker + + + Private Sub InitializeTimePicker() + timePicker = New DateTimePicker() + ' + timePicker.Format = DateTimePickerFormat.Time + ' + ' + timePicker.ShowUpDown = True + ' + timePicker.Location = New Point(10, 10) + timePicker.Width = 100 + Controls.Add(timePicker) + + End Sub + + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/imarqueewidget.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/imarqueewidget.vb new file mode 100644 index 0000000000..993d8b6022 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/imarqueewidget.vb @@ -0,0 +1,27 @@ + ' +' +' +' This interface defines the contract for any class that is to +' be used in constructing a MarqueeControl. +Public Interface IMarqueeWidget + ' + + ' This method starts the animation. If the control can + ' contain other classes that implement IMarqueeWidget as + ' children, the control should call StartMarquee on all + ' its IMarqueeWidget child controls. + Sub StartMarquee() + + ' This method stops the animation. If the control can + ' contain other classes that implement IMarqueeWidget as + ' children, the control should call StopMarquee on all + ' its IMarqueeWidget child controls. + Sub StopMarquee() + + ' This method specifies the refresh rate for the animation, + ' in milliseconds. + Property UpdatePeriod() As Integer + +End Interface +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb new file mode 100644 index 0000000000..2c5cacc166 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/lightshapeselectioncontrol.vb @@ -0,0 +1,205 @@ +' +' +Imports System.Collections +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.Design +' + +' +' This control provides the custom UI for the LightShape property +' of the MarqueeBorder. It is used by the LightShapeEditor. +Public Class LightShapeSelectionControl + Inherits System.Windows.Forms.UserControl + + ' + Private lightShapeValue As MarqueeLightShape = MarqueeLightShape.Square + ' + + Private editorService As IWindowsFormsEditorService + Private squarePanel As System.Windows.Forms.Panel + Private circlePanel As System.Windows.Forms.Panel + + ' Required designer variable. + Private components As System.ComponentModel.Container = Nothing + + + ' + ' This constructor takes a MarqueeLightShape value from the + ' design-time environment, which will be used to display + ' the initial state. + Public Sub New( _ + ByVal lightShape As MarqueeLightShape, _ + ByVal editorService As IWindowsFormsEditorService) + ' This call is required by the Windows.Forms Form Designer. + InitializeComponent() + + ' Cache the light shape value provided by the + ' design-time environment. + Me.lightShapeValue = lightShape + + ' Cache the reference to the editor service. + Me.editorService = editorService + + ' Handle the Click event for the two panels. + AddHandler Me.squarePanel.Click, AddressOf squarePanel_Click + AddHandler Me.circlePanel.Click, AddressOf circlePanel_Click + End Sub + ' + + ' + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + + ' Be sure to unhook event handlers + ' to prevent "lapsed listener" leaks. + RemoveHandler Me.squarePanel.Click, AddressOf squarePanel_Click + RemoveHandler Me.circlePanel.Click, AddressOf circlePanel_Click + + If (components IsNot Nothing) Then + components.Dispose() + End If + + End If + MyBase.Dispose(disposing) + End Sub + ' + + ' + ' LightShape is the property for which this control provides + ' a custom user interface in the Properties window. + Public Property LightShape() As MarqueeLightShape + + Get + Return Me.lightShapeValue + End Get + + Set(ByVal Value As MarqueeLightShape) + If Me.lightShapeValue <> Value Then + Me.lightShapeValue = Value + End If + End Set + + End Property + ' + + ' + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + MyBase.OnPaint(e) + + Dim gCircle As Graphics = Me.circlePanel.CreateGraphics() + Try + Dim gSquare As Graphics = Me.squarePanel.CreateGraphics() + Try + ' Draw a filled square in the client area of + ' the squarePanel control. + gSquare.FillRectangle( _ + Brushes.Red, _ + 0, _ + 0, _ + Me.squarePanel.Width, _ + Me.squarePanel.Height) + + ' If the Square option has been selected, draw a + ' border inside the squarePanel. + If Me.lightShapeValue = MarqueeLightShape.Square Then + gSquare.DrawRectangle( _ + Pens.Black, _ + 0, _ + 0, _ + Me.squarePanel.Width - 1, _ + Me.squarePanel.Height - 1) + End If + + ' Draw a filled circle in the client area of + ' the circlePanel control. + gCircle.Clear(Me.circlePanel.BackColor) + gCircle.FillEllipse( _ + Brushes.Blue, _ + 0, _ + 0, _ + Me.circlePanel.Width, _ + Me.circlePanel.Height) + + ' If the Circle option has been selected, draw a + ' border inside the circlePanel. + If Me.lightShapeValue = MarqueeLightShape.Circle Then + gCircle.DrawRectangle( _ + Pens.Black, _ + 0, _ + 0, _ + Me.circlePanel.Width - 1, _ + Me.circlePanel.Height - 1) + End If + Finally + gSquare.Dispose() + End Try + Finally + gCircle.Dispose() + End Try + End Sub + ' + + ' + Private Sub squarePanel_Click( _ + ByVal sender As Object, _ + ByVal e As EventArgs) + + Me.lightShapeValue = MarqueeLightShape.Square + Me.Invalidate(False) + Me.editorService.CloseDropDown() + + End Sub + + + Private Sub circlePanel_Click( _ + ByVal sender As Object, _ + ByVal e As EventArgs) + + Me.lightShapeValue = MarqueeLightShape.Circle + Me.Invalidate(False) + Me.editorService.CloseDropDown() + + End Sub + ' + +#Region "Component Designer generated code" + + '/ + '/ Required method for Designer support - do not modify + '/ the contents of this method with the code editor. + '/ + Private Sub InitializeComponent() + Me.squarePanel = New System.Windows.Forms.Panel + Me.circlePanel = New System.Windows.Forms.Panel + Me.SuspendLayout() + ' + ' squarePanel + ' + Me.squarePanel.Location = New System.Drawing.Point(8, 10) + Me.squarePanel.Name = "squarePanel" + Me.squarePanel.Size = New System.Drawing.Size(60, 60) + Me.squarePanel.TabIndex = 2 + ' + ' circlePanel + ' + Me.circlePanel.Location = New System.Drawing.Point(80, 10) + Me.circlePanel.Name = "circlePanel" + Me.circlePanel.Size = New System.Drawing.Size(60, 60) + Me.circlePanel.TabIndex = 3 + ' + ' LightShapeSelectionControl + ' + Me.Controls.Add(squarePanel) + Me.Controls.Add(circlePanel) + Me.Name = "LightShapeSelectionControl" + Me.Size = New System.Drawing.Size(150, 80) + Me.ResumeLayout(False) + End Sub + +#End Region + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/makefile new file mode 100644 index 0000000000..5b3f75b0a5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/makefile @@ -0,0 +1,5 @@ +MarqueeControlLibrary.dll: IMarqueeWidget.vb LightShapeSelectionControl.vb MarqueeBorder.vb MarqueeControl.vb MarqueeText.vb MarqueeControlRootDesigner.vb MarqueeBorderDesigner.vb + vbc /t:library /out:MarqueeControlLibrary.dll IMarqueeWidget.vb LightShapeSelectionControl.vb MarqueeBorder.vb MarqueeControl.vb MarqueeText.vb MarqueeControlRootDesigner.vb MarqueeBorderDesigner.vb + +clean: + del *.dll *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb new file mode 100644 index 0000000000..a7493c0068 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborder.vb @@ -0,0 +1,577 @@ +' +' +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Diagnostics +Imports System.Drawing +Imports System.Drawing.Design +Imports System.Threading +Imports System.Windows.Forms +Imports System.Windows.Forms.Design +' + +' +' This defines the possible values for the MarqueeBorder +' control's SpinDirection property. +Public Enum MarqueeSpinDirection + CW + CCW +End Enum + +' +' This defines the possible values for the MarqueeBorder +' control's LightShape property. +Public Enum MarqueeLightShape + Square + Circle +End Enum +' +' + +' + _ +Partial Public Class MarqueeBorder + Inherits Panel + Implements IMarqueeWidget + ' + + ' + Public Shared MaxLightSize As Integer = 10 + + ' These fields back the public properties. + Private updatePeriodValue As Integer = 50 + Private lightSizeValue As Integer = 5 + Private lightPeriodValue As Integer = 3 + Private lightSpacingValue As Integer = 1 + Private lightColorValue As Color + Private darkColorValue As Color + Private spinDirectionValue As MarqueeSpinDirection = MarqueeSpinDirection.CW + Private lightShapeValue As MarqueeLightShape = MarqueeLightShape.Square + + ' These brushes are used to paint the light and dark + ' colors of the marquee lights. + Private lightBrush As Brush + Private darkBrush As Brush + + ' This field tracks the progress of the "first" light as it + ' "travels" around the marquee border. + Private currentOffset As Integer = 0 + + ' This component updates the control asynchronously. + Private WithEvents backgroundWorker1 As System.ComponentModel.BackgroundWorker + + + Public Sub New() + ' This call is required by the Windows.Forms Form Designer. + InitializeComponent() + + ' Initialize light and dark colors + ' to the control's default values. + Me.lightColorValue = Me.ForeColor + Me.darkColorValue = Me.BackColor + Me.lightBrush = New SolidBrush(Me.lightColorValue) + Me.darkBrush = New SolidBrush(Me.darkColorValue) + + ' The MarqueeBorder control manages its own padding, + ' because it requires that any contained controls do + ' not overlap any of the marquee lights. + Dim pad As Integer = 2 * (Me.lightSizeValue + Me.lightSpacingValue) + Me.Padding = New Padding(pad, pad, pad, pad) + + SetStyle(ControlStyles.OptimizedDoubleBuffer, True) + End Sub + ' + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "IMarqueeWidget implementation" + + ' + Public Overridable Sub StartMarquee() _ + Implements IMarqueeWidget.StartMarquee + ' The MarqueeBorder control may contain any number of + ' controls that implement IMarqueeWidget, so find + ' each IMarqueeWidget child and call its StartMarquee + ' method. + Dim cntrl As Control + For Each cntrl In Me.Controls + If TypeOf cntrl Is IMarqueeWidget Then + Dim widget As IMarqueeWidget = CType(cntrl, IMarqueeWidget) + + widget.StartMarquee() + End If + Next cntrl + + ' Start the updating thread and pass it the UpdatePeriod. + Me.backgroundWorker1.RunWorkerAsync(Me.UpdatePeriod) + End Sub + + + Public Overridable Sub StopMarquee() _ + Implements IMarqueeWidget.StopMarquee + ' The MarqueeBorder control may contain any number of + ' controls that implement IMarqueeWidget, so find + ' each IMarqueeWidget child and call its StopMarquee + ' method. + Dim cntrl As Control + For Each cntrl In Me.Controls + If TypeOf cntrl Is IMarqueeWidget Then + Dim widget As IMarqueeWidget = CType(cntrl, IMarqueeWidget) + + widget.StopMarquee() + End If + Next cntrl + + ' Stop the updating thread. + Me.backgroundWorker1.CancelAsync() + End Sub + + + _ + Public Overridable Property UpdatePeriod() As Integer _ + Implements IMarqueeWidget.UpdatePeriod + + Get + Return Me.updatePeriodValue + End Get + + Set(ByVal Value As Integer) + If Value > 0 Then + Me.updatePeriodValue = Value + Else + Throw New ArgumentOutOfRangeException("UpdatePeriod", _ + "must be > 0") + End If + End Set + + End Property + ' + +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Public Properties" + + ' + _ + Public Property LightSize() As Integer + Get + Return Me.lightSizeValue + End Get + + Set(ByVal Value As Integer) + If Value > 0 AndAlso Value <= MaxLightSize Then + Me.lightSizeValue = Value + Me.DockPadding.All = 2 * Value + Else + Throw New ArgumentOutOfRangeException("LightSize", _ + "must be > 0 and < MaxLightSize") + End If + End Set + End Property + + + _ + Public Property LightPeriod() As Integer + Get + Return Me.lightPeriodValue + End Get + + Set(ByVal Value As Integer) + If Value > 0 Then + Me.lightPeriodValue = Value + Else + Throw New ArgumentOutOfRangeException("LightPeriod", _ + "must be > 0 ") + End If + End Set + End Property + + + _ + Public Property LightColor() As Color + Get + Return Me.lightColorValue + End Get + + Set(ByVal Value As Color) + ' The LightColor property is only changed if the + ' client provides a different value. Comparing values + ' from the ToArgb method is the recommended test for + ' equality between Color structs. + If Me.lightColorValue.ToArgb() <> Value.ToArgb() Then + Me.lightColorValue = Value + Me.lightBrush = New SolidBrush(Value) + End If + End Set + End Property + + + _ + Public Property DarkColor() As Color + Get + Return Me.darkColorValue + End Get + + Set(ByVal Value As Color) + ' The DarkColor property is only changed if the + ' client provides a different value. Comparing values + ' from the ToArgb method is the recommended test for + ' equality between Color structs. + If Me.darkColorValue.ToArgb() <> Value.ToArgb() Then + Me.darkColorValue = Value + Me.darkBrush = New SolidBrush(Value) + End If + End Set + End Property + + + _ + Public Property LightSpacing() As Integer + Get + Return Me.lightSpacingValue + End Get + + Set(ByVal Value As Integer) + If Value >= 0 Then + Me.lightSpacingValue = Value + Else + Throw New ArgumentOutOfRangeException("LightSpacing", _ + "must be >= 0") + End If + End Set + End Property + + + _ + Public Property LightShape() As MarqueeLightShape + + Get + Return Me.lightShapeValue + End Get + + Set(ByVal Value As MarqueeLightShape) + Me.lightShapeValue = Value + End Set + + End Property + + + _ + Public Property SpinDirection() As MarqueeSpinDirection + + Get + Return Me.spinDirectionValue + End Get + + Set(ByVal Value As MarqueeSpinDirection) + Me.spinDirectionValue = Value + End Set + + End Property + ' + +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Implementation" + + ' + Protected Overrides Sub OnLayout(ByVal levent As LayoutEventArgs) + MyBase.OnLayout(levent) + + ' Repaint when the layout has changed. + Me.Refresh() + End Sub + + + ' This method paints the lights around the border of the + ' control. It paints the top row first, followed by the + ' right side, the bottom row, and the left side. The color + ' of each light is determined by the IsLit method and + ' depends on the light's position relative to the value + ' of currentOffset. + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + Dim g As Graphics = e.Graphics + g.Clear(Me.BackColor) + + MyBase.OnPaint(e) + + ' If the control is large enough, draw some lights. + If Me.Width > MaxLightSize AndAlso Me.Height > MaxLightSize Then + ' The position of the next light will be incremented + ' by this value, which is equal to the sum of the + ' light size and the space between two lights. + Dim increment As Integer = _ + Me.lightSizeValue + Me.lightSpacingValue + + ' Compute the number of lights to be drawn along the + ' horizontal edges of the control. + Dim horizontalLights As Integer = _ + (Me.Width - increment) / increment + + ' Compute the number of lights to be drawn along the + ' vertical edges of the control. + Dim verticalLights As Integer = _ + (Me.Height - increment) / increment + + ' These local variables will be used to position and + ' paint each light. + Dim xPos As Integer = 0 + Dim yPos As Integer = 0 + Dim lightCounter As Integer = 0 + Dim brush As Brush + + ' Draw the top row of lights. + Dim i As Integer + For i = 0 To horizontalLights - 1 + brush = IIf(IsLit(lightCounter), Me.lightBrush, Me.darkBrush) + + DrawLight(g, brush, xPos, yPos) + + xPos += increment + lightCounter += 1 + Next i + + ' Draw the lights flush with the right edge of the control. + xPos = Me.Width - Me.lightSizeValue + + ' Draw the right column of lights. + 'Dim i As Integer + For i = 0 To verticalLights - 1 + brush = IIf(IsLit(lightCounter), Me.lightBrush, Me.darkBrush) + + DrawLight(g, brush, xPos, yPos) + + yPos += increment + lightCounter += 1 + Next i + + ' Draw the lights flush with the bottom edge of the control. + yPos = Me.Height - Me.lightSizeValue + + ' Draw the bottom row of lights. + 'Dim i As Integer + For i = 0 To horizontalLights - 1 + brush = IIf(IsLit(lightCounter), Me.lightBrush, Me.darkBrush) + + DrawLight(g, brush, xPos, yPos) + + xPos -= increment + lightCounter += 1 + Next i + + ' Draw the lights flush with the left edge of the control. + xPos = 0 + + ' Draw the left column of lights. + 'Dim i As Integer + For i = 0 To verticalLights - 1 + brush = IIf(IsLit(lightCounter), Me.lightBrush, Me.darkBrush) + + DrawLight(g, brush, xPos, yPos) + + yPos -= increment + lightCounter += 1 + Next i + End If + End Sub + ' + + ' + ' This method determines if the marquee light at lightIndex + ' should be lit. The currentOffset field specifies where + ' the "first" light is located, and the "position" of the + ' light given by lightIndex is computed relative to this + ' offset. If this position modulo lightPeriodValue is zero, + ' the light is considered to be on, and it will be painted + ' with the control's lightBrush. + Protected Overridable Function IsLit(ByVal lightIndex As Integer) As Boolean + Dim directionFactor As Integer = _ + IIf(Me.spinDirectionValue = MarqueeSpinDirection.CW, -1, 1) + + Return (lightIndex + directionFactor * Me.currentOffset) Mod Me.lightPeriodValue = 0 + End Function + + + Protected Overridable Sub DrawLight( _ + ByVal g As Graphics, _ + ByVal brush As Brush, _ + ByVal xPos As Integer, _ + ByVal yPos As Integer) + + Select Case Me.lightShapeValue + Case MarqueeLightShape.Square + g.FillRectangle( _ + brush, _ + xPos, _ + yPos, _ + Me.lightSizeValue, _ + Me.lightSizeValue) + Exit Select + Case MarqueeLightShape.Circle + g.FillEllipse( _ + brush, _ + xPos, _ + yPos, _ + Me.lightSizeValue, _ + Me.lightSizeValue) + Exit Select + Case Else + Trace.Assert(False, "Unknown value for light shape.") + Exit Select + End Select + + End Sub + ' + + ' + ' This method is called in the worker thread's context, + ' so it must not make any calls into the MarqueeBorder + ' control. Instead, it communicates to the control using + ' the ProgressChanged event. + ' + ' The only work done in this event handler is + ' to sleep for the number of milliseconds specified + ' by UpdatePeriod, then raise the ProgressChanged event. + Private Sub backgroundWorker1_DoWork( _ + ByVal sender As Object, _ + ByVal e As System.ComponentModel.DoWorkEventArgs) _ + Handles backgroundWorker1.DoWork + Dim worker As BackgroundWorker = CType(sender, BackgroundWorker) + + ' This event handler will run until the client cancels + ' the background task by calling CancelAsync. + While Not worker.CancellationPending + ' The Argument property of the DoWorkEventArgs + ' object holds the value of UpdatePeriod, which + ' was passed as the argument to the RunWorkerAsync + ' method. + Thread.Sleep(Fix(e.Argument)) + + ' The DoWork eventhandler does not actually report + ' progress; the ReportProgress event is used to + ' periodically alert the control to update its state. + worker.ReportProgress(0) + End While + End Sub + + + ' The ProgressChanged event is raised by the DoWork method. + ' This event handler does work that is internal to the + ' control. In this case, the currentOffset is incremented, + ' and the control is told to repaint itself. + Private Sub backgroundWorker1_ProgressChanged( _ + ByVal sender As Object, _ + ByVal e As System.ComponentModel.ProgressChangedEventArgs) _ + Handles backgroundWorker1.ProgressChanged + Me.currentOffset += 1 + Me.Refresh() + End Sub + ' + + ' + ' + ' This class demonstrates the use of a custom UITypeEditor. + ' It allows the MarqueeBorder control's LightShape property + ' to be changed at design time using a customized UI element + ' that is invoked by the Properties window. The UI is provided + ' by the LightShapeSelectionControl class. + Friend Class LightShapeEditor + Inherits UITypeEditor + ' + + ' + Private editorService As IWindowsFormsEditorService = Nothing + ' + + ' + Public Overrides Function GetEditStyle( _ + ByVal context As System.ComponentModel.ITypeDescriptorContext) _ + As UITypeEditorEditStyle + Return UITypeEditorEditStyle.DropDown + End Function + + ' + + ' + Public Overrides Function EditValue( _ + ByVal context As ITypeDescriptorContext, _ + ByVal provider As IServiceProvider, _ + ByVal value As Object) As Object + If (provider IsNot Nothing) Then + editorService = _ + CType(provider.GetService(GetType(IWindowsFormsEditorService)), _ + IWindowsFormsEditorService) + End If + + If (editorService IsNot Nothing) Then + Dim selectionControl As _ + New LightShapeSelectionControl( _ + CType(value, MarqueeLightShape), _ + editorService) + + editorService.DropDownControl(selectionControl) + + value = selectionControl.LightShape + End If + + Return value + End Function + ' + + ' + ' This method indicates to the design environment that + ' the type editor will paint additional content in the + ' LightShape entry in the PropertyGrid. + Public Overrides Function GetPaintValueSupported( _ + ByVal context As ITypeDescriptorContext) As Boolean + + Return True + + End Function + + ' This method paints a graphical representation of the + ' selected value of the LightShpae property. + Public Overrides Sub PaintValue( _ + ByVal e As PaintValueEventArgs) + + Dim shape As MarqueeLightShape = _ + CType(e.Value, MarqueeLightShape) + Using p As Pen = Pens.Black + + If shape = MarqueeLightShape.Square Then + + e.Graphics.DrawRectangle(p, e.Bounds) + + Else + + e.Graphics.DrawEllipse(p, e.Bounds) + + End If + + End Using + + End Sub + ' + + End Class + ' + + Private Sub InitializeComponent() + Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker + + ' + ' backgroundWorker1 + ' + Me.backgroundWorker1.WorkerReportsProgress = True + Me.backgroundWorker1.WorkerSupportsCancellation = True + End Sub + +#End Region + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb new file mode 100644 index 0000000000..c9d0ebbe2a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueeborderdesigner.vb @@ -0,0 +1,91 @@ +' +' +Imports System.Collections +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Diagnostics +Imports System.Windows.Forms +Imports System.Windows.Forms.Design +' + +' +Namespace MarqueeControlLibrary.Design + + _ + Public Class MarqueeBorderDesigner + Inherits ParentControlDesigner + ' + + Public Sub New() + Trace.WriteLine("MarqueeBorderDesigner") + End Sub + + ' + Public Property Visible() As Boolean + Get + Return CBool(ShadowProperties("Visible")) + End Get + Set(ByVal Value As Boolean) + Me.ShadowProperties("Visible") = Value + End Set + End Property + + + Public Property Enabled() As Boolean + Get + Return CBool(ShadowProperties("Enabled")) + End Get + Set(ByVal Value As Boolean) + Me.ShadowProperties("Enabled") = Value + End Set + End Property + ' + + ' + Protected Overrides Sub PreFilterProperties( _ + ByVal properties As IDictionary) + + MyBase.PreFilterProperties(properties) + + If properties.Contains("Padding") Then + properties.Remove("Padding") + End If + + properties("Visible") = _ + TypeDescriptor.CreateProperty(GetType(MarqueeBorderDesigner), _ + CType(properties("Visible"), PropertyDescriptor), _ + New Attribute(-1) {}) + + properties("Enabled") = _ + TypeDescriptor.CreateProperty(GetType(MarqueeBorderDesigner), _ + CType(properties("Enabled"), _ + PropertyDescriptor), _ + New Attribute(-1) {}) + + End Sub + ' + + ' + Private Sub OnVerbRunTest( _ + ByVal sender As Object, _ + ByVal e As EventArgs) + + Dim widget As IMarqueeWidget = CType(Me.Control, IMarqueeWidget) + widget.StartMarquee() + + End Sub + + + Private Sub OnVerbStopTest( _ + ByVal sender As Object, _ + ByVal e As EventArgs) + + Dim widget As IMarqueeWidget = CType(Me.Control, IMarqueeWidget) + widget.StopMarquee() + + End Sub + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb new file mode 100644 index 0000000000..2844c1d965 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrol.vb @@ -0,0 +1,107 @@ +' +' +Imports System.Collections +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.Design +' + +' + _ +Public Class MarqueeControl + Inherits UserControl + ' + + ' Required designer variable. + Private components As System.ComponentModel.Container = Nothing + + ' + Public Sub New() + ' This call is required by the Windows.Forms Form Designer. + InitializeComponent() + + ' Minimize flickering during animation by enabling + ' double buffering. + SetStyle(ControlStyles.OptimizedDoubleBuffer, True) + End Sub + ' + + ' + ' Clean up any resources being used. + ' + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + End Sub + + + ' + Public Sub Start() + ' The MarqueeControl may contain any number of + ' controls that implement IMarqueeWidget, so + ' find each IMarqueeWidget child and call its + ' StartMarquee method. + Dim cntrl As Control + For Each cntrl In Me.Controls + If TypeOf cntrl Is IMarqueeWidget Then + Dim widget As IMarqueeWidget = CType(cntrl, IMarqueeWidget) + + widget.StartMarquee() + End If + Next cntrl + End Sub + + + Public Sub [Stop]() + ' The MarqueeControl may contain any number of + ' controls that implement IMarqueeWidget, so find + ' each IMarqueeWidget child and call its StopMarquee + ' method. + Dim cntrl As Control + For Each cntrl In Me.Controls + If TypeOf cntrl Is IMarqueeWidget Then + Dim widget As IMarqueeWidget = CType(cntrl, IMarqueeWidget) + + widget.StopMarquee() + End If + Next cntrl + End Sub + ' + + ' + Protected Overrides Sub OnLayout(ByVal levent As LayoutEventArgs) + MyBase.OnLayout(levent) + + ' Repaint all IMarqueeWidget children if the layout + ' has changed. + Dim cntrl As Control + For Each cntrl In Me.Controls + If TypeOf cntrl Is IMarqueeWidget Then + Dim widget As IMarqueeWidget = CType(cntrl, IMarqueeWidget) + + cntrl.PerformLayout() + End If + Next cntrl + End Sub + ' + +#Region "Component Designer generated code" + + ' + ' Required method for Designer support - do not modify + ' the contents of this method with the code editor. + ' + Private Sub InitializeComponent() + End Sub + +#End Region + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb new file mode 100644 index 0000000000..b3250f7e17 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueecontrolrootdesigner.vb @@ -0,0 +1,87 @@ +' +' +Imports System.Collections +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Diagnostics +Imports System.Drawing.Design +Imports System.Windows.Forms +Imports System.Windows.Forms.Design +' + +' +Namespace MarqueeControlLibrary.Design + + _ + _ + Public Class MarqueeControlRootDesigner + Inherits DocumentDesigner + ' + + ' + Public Sub New() + Trace.WriteLine("MarqueeControlRootDesigner ctor") + End Sub + ' + + ' + Public Overrides Sub Initialize(ByVal component As IComponent) + + ' + MyBase.Initialize(component) + + Dim cs As IComponentChangeService = _ + CType(GetService(GetType(IComponentChangeService)), _ + IComponentChangeService) + + If (cs IsNot Nothing) Then + AddHandler cs.ComponentChanged, AddressOf OnComponentChanged + End If + ' + + ' + Me.Verbs.Add(New DesignerVerb("Run Test", _ + New EventHandler(AddressOf OnVerbRunTest))) + + Me.Verbs.Add(New DesignerVerb("Stop Test", _ + New EventHandler(AddressOf OnVerbStopTest))) + ' + End Sub + ' + + ' + Private Sub OnComponentChanged( _ + ByVal sender As Object, _ + ByVal e As ComponentChangedEventArgs) + If TypeOf e.Component Is IMarqueeWidget Then + Me.Control.Refresh() + End If + End Sub + ' + + ' + Private Sub OnVerbRunTest( _ + ByVal sender As Object, _ + ByVal e As EventArgs) + + Dim c As MarqueeControl = CType(Me.Control, MarqueeControl) + c.Start() + + End Sub + + Private Sub OnVerbStopTest( _ + ByVal sender As Object, _ + ByVal e As EventArgs) + + Dim c As MarqueeControl = CType(Me.Control, MarqueeControl) + c.Stop() + + End Sub + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb new file mode 100644 index 0000000000..5faffc3a2a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Design.DocumentDesigner/VB/marqueetext.vb @@ -0,0 +1,212 @@ +' +' +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Diagnostics +Imports System.Drawing +Imports System.Threading +Imports System.Windows.Forms +Imports System.Windows.Forms.Design +' + +' + _ +Partial Public Class MarqueeText + Inherits Label + Implements IMarqueeWidget + ' + + ' + ' When isLit is true, the text is painted in the light color; + ' When isLit is false, the text is painted in the dark color. + ' This value changes whenever the BackgroundWorker component + ' raises the ProgressChanged event. + Private isLit As Boolean = True + + ' These fields back the public properties. + Private updatePeriodValue As Integer = 50 + Private lightColorValue As Color + Private darkColorValue As Color + + ' These brushes are used to paint the light and dark + ' colors of the text. + Private lightBrush As Brush + Private darkBrush As Brush + + ' This component updates the control asynchronously. + Private WithEvents backgroundWorker1 As BackgroundWorker + + + Public Sub New() + ' This call is required by the Windows.Forms Form Designer. + InitializeComponent() + + ' Initialize light and dark colors + ' to the control's default values. + Me.lightColorValue = Me.ForeColor + Me.darkColorValue = Me.BackColor + Me.lightBrush = New SolidBrush(Me.lightColorValue) + Me.darkBrush = New SolidBrush(Me.darkColorValue) + End Sub + ' + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "IMarqueeWidget implementation" + + + ' + Public Overridable Sub StartMarquee() _ + Implements IMarqueeWidget.StartMarquee + ' Start the updating thread and pass it the UpdatePeriod. + Me.backgroundWorker1.RunWorkerAsync(Me.UpdatePeriod) + End Sub + + Public Overridable Sub StopMarquee() _ + Implements IMarqueeWidget.StopMarquee + ' Stop the updating thread. + Me.backgroundWorker1.CancelAsync() + End Sub + + + _ + Public Property UpdatePeriod() As Integer _ + Implements IMarqueeWidget.UpdatePeriod + + Get + Return Me.updatePeriodValue + End Get + + Set(ByVal Value As Integer) + If Value > 0 Then + Me.updatePeriodValue = Value + Else + Throw New ArgumentOutOfRangeException("UpdatePeriod", "must be > 0") + End If + End Set + + End Property + ' + +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Public Properties" + + ' + _ + Public Property LightColor() As Color + + Get + Return Me.lightColorValue + End Get + + Set(ByVal Value As Color) + ' The LightColor property is only changed if the + ' client provides a different value. Comparing values + ' from the ToArgb method is the recommended test for + ' equality between Color structs. + If Me.lightColorValue.ToArgb() <> Value.ToArgb() Then + Me.lightColorValue = Value + Me.lightBrush = New SolidBrush(Value) + End If + End Set + + End Property + + + _ + Public Property DarkColor() As Color + + Get + Return Me.darkColorValue + End Get + + Set(ByVal Value As Color) + ' The DarkColor property is only changed if the + ' client provides a different value. Comparing values + ' from the ToArgb method is the recommended test for + ' equality between Color structs. + If Me.darkColorValue.ToArgb() <> Value.ToArgb() Then + Me.darkColorValue = Value + Me.darkBrush = New SolidBrush(Value) + End If + End Set + + End Property + ' +#End Region + + ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +#Region "Implementation" + + ' + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + ' The text is painted in the light or dark color, + ' depending on the current value of isLit. + Me.ForeColor = IIf(Me.isLit, Me.lightColorValue, Me.darkColorValue) + + MyBase.OnPaint(e) + End Sub + ' + + ' + ' This method is called in the worker thread's context, + ' so it must not make any calls into the MarqueeText control. + ' Instead, it communicates to the control using the + ' ProgressChanged event. + ' + ' The only work done in this event handler is + ' to sleep for the number of milliseconds specified + ' by UpdatePeriod, then raise the ProgressChanged event. + Private Sub backgroundWorker1_DoWork( _ + ByVal sender As Object, _ + ByVal e As System.ComponentModel.DoWorkEventArgs) _ + Handles backgroundWorker1.DoWork + Dim worker As BackgroundWorker = CType(sender, BackgroundWorker) + + ' This event handler will run until the client cancels + ' the background task by calling CancelAsync. + While Not worker.CancellationPending + ' The Argument property of the DoWorkEventArgs + ' object holds the value of UpdatePeriod, which + ' was passed as the argument to the RunWorkerAsync + ' method. + Thread.Sleep(Fix(e.Argument)) + + ' The DoWork eventhandler does not actually report + ' progress; the ReportProgress event is used to + ' periodically alert the control to update its state. + worker.ReportProgress(0) + End While + End Sub + + + ' The ProgressChanged event is raised by the DoWork method. + ' This event handler does work that is internal to the + ' control. In this case, the text is toggled between its + ' light and dark state, and the control is told to + ' repaint itself. + Private Sub backgroundWorker1_ProgressChanged( _ + ByVal sender As Object, _ + ByVal e As System.ComponentModel.ProgressChangedEventArgs) _ + Handles backgroundWorker1.ProgressChanged + Me.isLit = Not Me.isLit + Me.Refresh() + End Sub + ' + + Private Sub InitializeComponent() + Me.backgroundWorker1 = New System.ComponentModel.BackgroundWorker + + ' + ' backgroundWorker1 + ' + Me.backgroundWorker1.WorkerReportsProgress = True + Me.backgroundWorker1.WorkerSupportsCancellation = True + End Sub + +#End Region + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/VB/form1.vb new file mode 100644 index 0000000000..065d325f60 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.DetermineModifierKey/VB/form1.vb @@ -0,0 +1,34 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Namespace DetermineModifierKey + + Class Form1 + Inherits Form + + Private WithEvents TextBox1 As New TextBox() + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Me.Controls.Add(TextBox1) + End Sub + + ' + Public Sub TextBox1_KeyPress(ByVal sender As Object, _ + ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress + + If ((Control.ModifierKeys And Keys.Shift) = Keys.Shift) Then + MsgBox("Pressed " + Keys.Shift.ToString()) + End If + End Sub + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb new file mode 100644 index 0000000000..ee47b42878 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ExplorerStyleInterface/VB/Form1.vb @@ -0,0 +1,201 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms +' +Imports System.IO +' + + + +Public Class Form1 + Inherits Form + Private splitContainer1 As SplitContainer + Private WithEvents treeView1 As TreeView + Private imageList1 As ImageList + Private components As IContainer + Private nameColumn As ColumnHeader + Private typeColumn As ColumnHeader + Private modifiedColumn As ColumnHeader + Friend WithEvents ImageList2 As System.Windows.Forms.ImageList + Private listView1 As ListView + + + ' + Public Sub New() + InitializeComponent() + PopulateTreeView() + + End Sub + + ' + ' + Private Sub treeView1_NodeMouseClick(ByVal sender As Object, _ + ByVal e As TreeNodeMouseClickEventArgs) _ + Handles treeView1.NodeMouseClick + + Dim newSelected As TreeNode = e.Node + listView1.Items.Clear() + Dim nodeDirInfo As DirectoryInfo = _ + CType(newSelected.Tag, DirectoryInfo) + Dim subItems() As ListViewItem.ListViewSubItem + Dim item As ListViewItem = Nothing + + Dim dir As DirectoryInfo + For Each dir In nodeDirInfo.GetDirectories() + item = New ListViewItem(dir.Name, 0) + subItems = New ListViewItem.ListViewSubItem() _ + {New ListViewItem.ListViewSubItem(item, "Directory"), _ + New ListViewItem.ListViewSubItem(item, _ + dir.LastAccessTime.ToShortDateString())} + + item.SubItems.AddRange(subItems) + listView1.Items.Add(item) + Next dir + Dim file As FileInfo + For Each file In nodeDirInfo.GetFiles() + item = New ListViewItem(file.Name, 1) + subItems = New ListViewItem.ListViewSubItem() _ + {New ListViewItem.ListViewSubItem(item, "File"), _ + New ListViewItem.ListViewSubItem(item, _ + file.LastAccessTime.ToShortDateString())} + + item.SubItems.AddRange(subItems) + listView1.Items.Add(item) + Next file + + listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize) + + End Sub + + ' + ' + Private Sub PopulateTreeView() + Dim rootNode As TreeNode + + Dim info As New DirectoryInfo("../..") + If info.Exists Then + rootNode = New TreeNode(info.Name) + rootNode.Tag = info + GetDirectories(info.GetDirectories(), rootNode) + treeView1.Nodes.Add(rootNode) + End If + + End Sub + + Private Sub GetDirectories(ByVal subDirs() As DirectoryInfo, _ + ByVal nodeToAddTo As TreeNode) + + Dim aNode As TreeNode + Dim subSubDirs() As DirectoryInfo + Dim subDir As DirectoryInfo + For Each subDir In subDirs + aNode = New TreeNode(subDir.Name, 0, 0) + aNode.Tag = subDir + aNode.ImageKey = "folder" + subSubDirs = subDir.GetDirectories() + If subSubDirs.Length <> 0 Then + GetDirectories(subSubDirs, aNode) + End If + nodeToAddTo.Nodes.Add(aNode) + Next subDir + + End Sub + + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container + Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1)) + Me.splitContainer1 = New System.Windows.Forms.SplitContainer + Me.treeView1 = New System.Windows.Forms.TreeView + Me.imageList1 = New System.Windows.Forms.ImageList(Me.components) + Me.listView1 = New System.Windows.Forms.ListView + Me.nameColumn = New System.Windows.Forms.ColumnHeader("") + Me.typeColumn = New System.Windows.Forms.ColumnHeader("") + Me.modifiedColumn = New System.Windows.Forms.ColumnHeader("") + Me.ImageList2 = New System.Windows.Forms.ImageList(Me.components) + Me.splitContainer1.Panel1.SuspendLayout() + Me.splitContainer1.Panel2.SuspendLayout() + Me.splitContainer1.SuspendLayout() + Me.SuspendLayout() + ' + 'splitContainer1 + ' + Me.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill + Me.splitContainer1.Location = New System.Drawing.Point(0, 0) + Me.splitContainer1.Name = "splitContainer1" + ' + 'Panel1 + ' + Me.splitContainer1.Panel1.Controls.Add(Me.treeView1) + ' + 'Panel2 + ' + Me.splitContainer1.Panel2.Controls.Add(Me.listView1) + Me.splitContainer1.Size = New System.Drawing.Size(492, 466) + Me.splitContainer1.SplitterDistance = 166 + Me.splitContainer1.TabIndex = 0 + Me.splitContainer1.Text = "splitContainer1" + ' + 'treeView1 + ' + Me.treeView1.Dock = System.Windows.Forms.DockStyle.Fill + Me.treeView1.ImageList = Me.imageList1 + Me.treeView1.Location = New System.Drawing.Point(0, 0) + Me.treeView1.Name = "treeView1" + Me.treeView1.Size = New System.Drawing.Size(166, 466) + Me.treeView1.TabIndex = 0 + ' + 'imageList1 + ' + Me.imageList1.ImageStream = CType(resources.GetObject("imageList1.ImageStream"), System.Windows.Forms.ImageListStreamer) + Me.imageList1.Images.SetKeyName(0, "FOLDER.ICO") + Me.imageList1.Images.SetKeyName(1, "DOC.ICO") + ' + 'listView1 + ' + Me.listView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.nameColumn, Me.typeColumn, Me.modifiedColumn}) + Me.listView1.Dock = System.Windows.Forms.DockStyle.Fill + Me.listView1.Location = New System.Drawing.Point(0, 0) + Me.listView1.Name = "listView1" + Me.listView1.Size = New System.Drawing.Size(322, 466) + Me.listView1.SmallImageList = Me.imageList1 + Me.listView1.TabIndex = 0 + Me.listView1.View = System.Windows.Forms.View.Details + ' + 'nameColumn + ' + Me.nameColumn.Text = "Name" + Me.nameColumn.Width = 82 + ' + 'typeColumn + ' + Me.typeColumn.Text = "Type" + Me.typeColumn.Width = 78 + ' + 'modifiedColumn + ' + Me.modifiedColumn.Text = "Last Modified" + Me.modifiedColumn.Width = 109 + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(492, 466) + Me.Controls.Add(Me.splitContainer1) + Me.Name = "Form1" + Me.splitContainer1.Panel1.ResumeLayout(False) + Me.splitContainer1.Panel2.ResumeLayout(False) + Me.splitContainer1.ResumeLayout(False) + Me.ResumeLayout(False) + + End Sub +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb new file mode 100644 index 0000000000..96c8beabf8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/FirstControl.vb @@ -0,0 +1,71 @@ + ' +Imports System.Drawing +Imports System.Collections +Imports System.ComponentModel +Imports System.Windows.Forms + + +' +Public Class FirstControl + Inherits Control + ' + + Public Sub New() + End Sub + + + ' + ' ContentAlignment is an enumeration defined in the System.Drawing + ' namespace that specifies the alignment of content on a drawing + ' surface. + Private alignmentValue As ContentAlignment = ContentAlignment.MiddleLeft + + ' + _ + Public Property TextAlignment() As ContentAlignment + ' + + Get + Return alignmentValue + End Get + Set + alignmentValue = value + + ' The Invalidate method invokes the OnPaint method described + ' in step 3. + Invalidate() + End Set + End Property +' + + + ' + Protected Overrides Sub OnPaint(e As PaintEventArgs) + + MyBase.OnPaint(e) + Dim style As New StringFormat() + style.Alignment = StringAlignment.Near + Select Case alignmentValue + Case ContentAlignment.MiddleLeft + style.Alignment = StringAlignment.Near + Case ContentAlignment.MiddleRight + style.Alignment = StringAlignment.Far + Case ContentAlignment.MiddleCenter + style.Alignment = StringAlignment.Center + End Select + + ' Call the DrawString method of the System.Drawing class to write + ' text. Text and ClientRectangle are properties inherited from + ' Control. + e.Graphics.DrawString( _ + me.Text, _ + me.Font, _ + New SolidBrush(ForeColor), _ + RectangleF.op_Implicit(ClientRectangle), _ + style) + + End Sub + ' + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/SimpleForm.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/SimpleForm.vb new file mode 100644 index 0000000000..fad774e0b0 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/SimpleForm.vb @@ -0,0 +1,57 @@ + ' +Imports System.Drawing +Imports System.Collections +Imports System.ComponentModel +Imports System.Windows.Forms + + + + +Public Class SimpleForm + Inherits System.Windows.Forms.Form + + Private firstControl1 As FirstControl + + Private components As System.ComponentModel.Container = Nothing + + + Public Sub New() + InitializeComponent() + End Sub + + + + + + Private Sub InitializeComponent() + Me.firstControl1 = New FirstControl() + Me.SuspendLayout() + + ' + ' firstControl1 + ' + Me.firstControl1.BackColor = System.Drawing.SystemColors.ControlDark + Me.firstControl1.Location = New System.Drawing.Point(96, 104) + Me.firstControl1.Name = "firstControl1" + Me.firstControl1.Size = New System.Drawing.Size(75, 16) + Me.firstControl1.TabIndex = 0 + Me.firstControl1.Text = "Hello World" + Me.firstControl1.TextAlignment = System.Drawing.ContentAlignment.MiddleCenter + + ' + ' SimpleForm + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(firstControl1) + Me.Name = "SimpleForm" + Me.Text = "SimpleForm" + Me.ResumeLayout(False) + End Sub + + + _ + Shared Sub Main() + Application.Run(New SimpleForm()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/makefile new file mode 100644 index 0000000000..e257e06628 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FirstControl/VB/makefile @@ -0,0 +1,8 @@ +SimpleForm.exe: SimpleForm.vb FirstControl.dll + vbc /t:exe /r:FirstControl.dll,System.dll,System.Drawing.dll,System.Windows.Forms.dll /out:SimpleForm.exe SimpleForm.vb + +FirstControl.dll: FirstControl.vb + vbc /r:System.dll,System.Drawing.dll,System.Windows.Forms.dll /t:library /out:FirstControl.dll FirstControl.vb + +clean: + del *.exe *.dll *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb new file mode 100644 index 0000000000..d788e750e8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBar.vb @@ -0,0 +1,502 @@ +' +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Drawing.Design +Imports System.Windows.Forms +Imports System.Diagnostics + +Namespace Microsoft.Samples.WinForms.VB.FlashTrackBar + + _ + Public Class FlashTrackBar + Inherits System.Windows.Forms.Control + + Private LeftRightBorder As Integer = 10 + Private myValue As Integer = 0 + Private myMin As Integer = 0 + Private myMax As Integer = 100 + Private myShowPercentage As Boolean = False + Private myShowValue As Boolean = False + Private myAllowUserEdit As Boolean = True + Private myShowGradient As Boolean = True + Private dragValue As Integer = 0 + Private dragging As Boolean = False + Private myStartColor As Color = Color.Red + Private myEndColor As Color = Color.LimeGreen + ' + Private baseBackground As Brush + ' + Private backgroundDim As Brush + Private myDarkenBy As Byte = 200 + + Public Sub New() + + MyBase.New() + + 'This call is required by the Windows Forms Designer. + InitializeComponent() + + SetStyle(ControlStyles.Opaque, True) + SetStyle(ControlStyles.ResizeRedraw, True) + Debug.Assert(GetStyle(ControlStyles.ResizeRedraw), "Should be redraw!") + End Sub + + 'Form overrides dispose to clean up the component list. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + End Sub + + +#Region " Windows Form Designer generated code " + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.Container + + '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.components = New System.ComponentModel.Container() + Me.ForeColor = System.Drawing.Color.White + Me.BackColor = System.Drawing.Color.Black + Me.Size = New System.Drawing.Size(100, 23) + Me.Text = "FlashTrackBar" + End Sub + +#End Region + + + Public Property AllowUserEdit() As Boolean + Get + Return myAllowUserEdit + End Get + + Set(ByVal Value As Boolean) + If (Value <> myAllowUserEdit) Then + myAllowUserEdit = Value + If Not (myAllowUserEdit) Then + Capture = False + dragging = False + End If + End If + End Set + + End Property + + + Public Property EndColor() As Color + Get + Return myEndColor + End Get + + Set(ByVal Value As Color) + myEndColor = Value + If ((baseBackground IsNot Nothing) And myShowGradient) Then + baseBackground.Dispose() + baseBackground = Nothing + End If + Invalidate() + End Set + End Property + + + Public Function ShouldPersistEndColor() As Boolean + Return Not (myEndColor.Equals(Color.LimeGreen)) + End Function + + + _ + Public Property DarkenBy() As Byte + Get + Return myDarkenBy + End Get + Set(ByVal Value As Byte) + If (Value <> myDarkenBy) Then + myDarkenBy = Value + If (backgroundDim IsNot Nothing) Then + backgroundDim.Dispose() + backgroundDim = Nothing + End If + OptimizedInvalidate(Value, Max) + End If + End Set + End Property + + _ + Public Property Max() As Integer + Get + Return myMax + End Get + Set(ByVal Value As Integer) + If (myMax <> Value) Then + myMax = Value + Invalidate() + End If + End Set + End Property + + + _ + Public Property Min() As Integer + Get + Return myMin + End Get + Set(ByVal Value As Integer) + If (Min <> Value) Then + Min = Value + Invalidate() + End If + End Set + End Property + + + Public Property StartColor() As Color + Get + Return myStartColor + End Get + Set(ByVal Value As Color) + myStartColor = Value + If ((baseBackground IsNot Nothing) And myShowGradient) Then + baseBackground.Dispose() + baseBackground = Nothing + End If + Invalidate() + End Set + End Property + + Public Function ShouldPersistStartColor() As Boolean + Return Not (StartColor.Equals(Color.Red)) + End Function + + + _ + Public Property ShowPercentage() As Boolean + Get + Return myShowPercentage + End Get + Set(ByVal Value As Boolean) + If (Value <> myShowPercentage) Then + myShowPercentage = Value + If (myShowPercentage) Then + myShowValue = False + End If + Invalidate() + End If + End Set + End Property + + + _ + Public Property ShowValue() As Boolean + Get + Return myShowValue + End Get + Set(ByVal Value As Boolean) + If (Value <> myShowValue) Then + myShowValue = Value + If (myShowValue) Then + myShowPercentage = False + End If + Invalidate() + End If + End Set + End Property + + + + _ + Public Property ShowGradient() As Boolean + Get + Return myShowGradient + End Get + Set(ByVal Value As Boolean) + If (Value <> myShowGradient) Then + myShowGradient = Value + If (baseBackground IsNot Nothing) Then + baseBackground.Dispose() + baseBackground = Nothing + End If + Invalidate() + End If + End Set + End Property + + _ + Public Property Value() As Integer + Get + If (dragging) Then + Return dragValue + End If + Return myValue + End Get + Set(ByVal Value As Integer) + If (Value <> myValue) Then + Dim old As Integer = myValue + myValue = Value + OnValueChanged(EventArgs.Empty) + OptimizedInvalidate(old, myValue) + End If + End Set + End Property + + ' ValueChanged Event + + _ + Public Event ValueChanged(ByVal sender As Object, ByVal ev As EventArgs) 'As EventHandler + + + Private Sub OptimizedInvalidate(ByVal oldValue As Integer, ByVal newValue As Integer) + Dim client As Rectangle = ClientRectangle + + Dim oldPercentValue As Single = CSng(oldValue) / (CSng(Max) - CSng(Min)) + Dim oldNonDimLength As Integer = CInt(oldPercentValue * CSng(client.Width)) + + Dim newPercentValue As Single = (CSng(newValue) / (CSng(Max) - CSng(Min))) + Dim newNonDimLength As Integer = CInt(newPercentValue * CSng(client.Width)) + + Dim lmin As Integer = Math.Min(oldNonDimLength, newNonDimLength) + Dim lmax As Integer = Math.Max(oldNonDimLength, newNonDimLength) + + ' + Dim invalid As Rectangle = New Rectangle( _ + client.X + lmin, _ + client.Y, _ + lmax - lmin, _ + client.Height) + + Invalidate(invalid) + ' + + Dim oldToDisplay As String + Dim newToDisplay As String + + If (ShowPercentage) Then + oldToDisplay = Convert.ToString(CInt(oldPercentValue * 100F)) + "%" + newToDisplay = Convert.ToString(CInt(newPercentValue * 100F)) + "%" + ElseIf (ShowValue) Then + oldToDisplay = Convert.ToString(oldValue) + newToDisplay = Convert.ToString(newValue) + Else + oldToDisplay = Nothing + newToDisplay = Nothing + End If + + If (oldToDisplay <> Nothing And newToDisplay <> Nothing) Then + Dim g As Graphics = CreateGraphics() + Dim oldFontSize As SizeF = g.MeasureString(oldToDisplay, Font) + Dim newFontSize As SizeF = g.MeasureString(newToDisplay, Font) + Dim oldFontRectF As RectangleF = New RectangleF(New PointF(0, 0), oldFontSize) + Dim newFontRectF As RectangleF = New RectangleF(New PointF(0, 0), newFontSize) + oldFontRectF.X = (client.Width - oldFontRectF.Width) / 2 + oldFontRectF.Y = (client.Height - oldFontRectF.Height) / 2 + newFontRectF.X = (client.Width - newFontRectF.Width) / 2 + newFontRectF.Y = (client.Height - newFontRectF.Height) / 2 + + Dim oldFontRect As Rectangle = New Rectangle(CInt(oldFontRectF.X), CInt(oldFontRectF.Y), CInt(oldFontRectF.Width), CInt(oldFontRectF.Height)) + Dim newFontRect As Rectangle = New Rectangle(CInt(newFontRectF.X), CInt(newFontRectF.Y), CInt(newFontRectF.Width), CInt(newFontRectF.Height)) + + Invalidate(oldFontRect) + Invalidate(newFontRect) + End If + End Sub + + + ' + Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs) + MyBase.OnMouseDown(e) + If Not (myAllowUserEdit) Then + Return + End If + Capture = True + dragging = True + SetDragValue(New Point(e.X, e.Y)) + End Sub + ' + + ' + Protected Overrides Sub OnMouseMove(ByVal e As MouseEventArgs) + MyBase.OnMouseMove(e) + If (Not myAllowUserEdit Or Not dragging) Then + Return + End If + SetDragValue(New Point(e.X, e.Y)) + End Sub + ' + + ' + Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs) + MyBase.OnMouseUp(e) + If (Not myAllowUserEdit Or Not dragging) Then + Return + End If + Capture = False + dragging = False + Value = dragValue + OnValueChanged(EventArgs.Empty) + End Sub + ' + + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + + ' + MyBase.OnPaint(e) + + If (baseBackground Is Nothing) Then + + If (myShowGradient) Then + baseBackground = New LinearGradientBrush(New Point(0, 0), _ + New Point(ClientSize.Width, 0), _ + StartColor, _ + EndColor) + ElseIf (BackgroundImage IsNot Nothing) Then + baseBackground = New TextureBrush(BackgroundImage) + Else + baseBackground = New SolidBrush(BackColor) + End If + + End If + ' + + If (backgroundDim Is Nothing) Then + backgroundDim = New SolidBrush(Color.FromArgb(DarkenBy, Color.Black)) + End If + + Dim toDim As Rectangle = ClientRectangle + Dim percentValue As Single = (CSng(Value) / (CSng(Max) - CSng(Min))) + Dim nonDimLength As Integer = CInt(percentValue * CSng(toDim.Width)) + toDim.X = toDim.X + nonDimLength + toDim.Width = toDim.Width - nonDimLength + + Dim ltext As String = Me.Text + Dim toDisplay As String + Dim textRect As RectangleF = New RectangleF(0, 0, 0, 0) + + If (ShowPercentage Or ShowValue Or ltext.Length > 0) Then + + If (ShowPercentage) Then + toDisplay = Convert.ToString(CInt(percentValue * 100F)) + "%" + ElseIf (ShowValue) Then + toDisplay = Convert.ToString(Value) + Else + toDisplay = ltext + End If + + Dim textSize As SizeF = e.Graphics.MeasureString(toDisplay, Font) + textRect.Width = textSize.Width + textRect.Height = textSize.Height + textRect.X = (ClientRectangle.Width - textRect.Width) / 2 + textRect.Y = (ClientRectangle.Height - textRect.Height) / 2 + End If + + e.Graphics.FillRectangle(baseBackground, ClientRectangle) + e.Graphics.FillRectangle(backgroundDim, toDim) + e.Graphics.Flush() + If (toDisplay <> Nothing And toDisplay.Length > 0) Then + e.Graphics.DrawString(toDisplay, Font, New SolidBrush(ForeColor), textRect) + End If + End Sub + + ' + Protected Overrides Sub OnTextChanged(ByVal E As EventArgs) + MyBase.OnTextChanged(E) + Invalidate() + End Sub + + Protected Overrides Sub OnBackColorChanged(ByVal E As EventArgs) + MyBase.OnBackColorChanged(E) + If (baseBackground IsNot Nothing) And Not ShowGradient Then + baseBackground.Dispose() + baseBackground = Nothing + End If + End Sub + ' + + Protected Overrides Sub OnBackgroundImageChanged(ByVal E As EventArgs) + MyBase.OnTextChanged(E) + If (baseBackground IsNot Nothing) And Not ShowGradient Then + baseBackground.Dispose() + baseBackground = Nothing + End If + End Sub + + ' + Protected Overrides Sub OnResize(ByVal e As EventArgs) + MyBase.OnResize(e) + If (baseBackground IsNot Nothing) Then + baseBackground.Dispose() + baseBackground = Nothing + End If + End Sub + ' + + Protected Overridable Sub OnValueChanged(ByVal e As EventArgs) + RaiseEvent ValueChanged(Me, e) + End Sub + + Private Sub SetDragValue(ByVal mouseLocation As Point) + + Dim client As Rectangle = ClientRectangle + + If (client.Contains(mouseLocation)) Then + + Dim percentage As Single = CSng(mouseLocation.X) / CSng(ClientRectangle.Width) + Dim newDragValue As Integer = CInt(percentage * CSng(Max - Min)) + + If (newDragValue <> dragValue) Then + Dim old As Integer = dragValue + dragValue = newDragValue + OptimizedInvalidate(old, dragValue) + End If + + Else + + If (client.Y <= mouseLocation.Y And mouseLocation.Y <= client.Y + client.Height) Then + If (mouseLocation.X <= client.X And mouseLocation.X > client.X - LeftRightBorder) Then + Dim newDragValue As Integer = Min + If (newDragValue <> dragValue) Then + Dim old As Integer = dragValue + dragValue = newDragValue + OptimizedInvalidate(old, dragValue) + End If + + ElseIf (mouseLocation.X >= client.X + client.Width And mouseLocation.X < client.X + client.Width + LeftRightBorder) Then + Dim newDragValue As Integer = Max + If (newDragValue <> dragValue) Then + Dim old As Integer = dragValue + dragValue = newDragValue + OptimizedInvalidate(old, dragValue) + End If + End If + + Else + If (dragValue <> Value) Then + Dim old As Integer = dragValue + dragValue = Value + OptimizedInvalidate(old, dragValue) + End If + + End If + + End If + + End Sub + + End Class + +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarDarkenByEditor.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarDarkenByEditor.vb new file mode 100644 index 0000000000..9ec40e28a1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarDarkenByEditor.vb @@ -0,0 +1,24 @@ +' +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Drawing.Design +Imports System.Windows.Forms +Imports System.Diagnostics + +Namespace Microsoft.Samples.WinForms.VB.FlashTrackBar + + Public Class FlashTrackBarDarkenByEditor + Inherits FlashTrackBarValueEditor + + Overrides Protected Sub SetEditorProps(editingInstance As FlashTrackBar, editor As FlashTrackBar) + MyBase.SetEditorProps(editingInstance, editor) + editor.Min = 0 + editor.Max = System.Byte.MaxValue + End Sub + + End Class + +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarValueEditor.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarValueEditor.vb new file mode 100644 index 0000000000..ceb1cb1ffc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/FlashTrackBarValueEditor.vb @@ -0,0 +1,83 @@ +' +Imports System.ComponentModel +Imports System.ComponentModel.Design +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Drawing.Design +Imports System.Windows.Forms +Imports System.Diagnostics +Imports System.Windows.Forms.ComponentModel +Imports System.Windows.Forms.Design + +Namespace Microsoft.Samples.WinForms.VB.FlashTrackBar + + _ + Public Class FlashTrackBarValueEditor + Inherits UITypeEditor + + Private edSvc As IWindowsFormsEditorService + + + Overridable Protected Sub SetEditorProps(editingInstance As FlashTrackBar, editor As FlashTrackBar) + editor.ShowValue = true + editor.StartColor = Color.Navy + editor.EndColor = Color.White + editor.ForeColor = Color.White + editor.Min = editingInstance.Min + editor.Max = editingInstance.Max + End Sub + + Overrides OverLoads Public Function EditValue(context As ITypeDescriptorContext, provider As IServiceProvider, value As object) As Object + + If ((context IsNot Nothing) And (context.Instance IsNot Nothing) And (provider IsNot Nothing)) Then + + edSvc = CType(provider.GetService(GetType(IWindowsFormsEditorService)), IWindowsFormsEditorService) + + If (edSvc IsNot Nothing) Then + + Dim trackBar As FlashTrackBar = New FlashTrackBar() + AddHandler trackBar.ValueChanged, AddressOf Me.ValueChanged + SetEditorProps(CType(context.Instance, FlashTrackBar), TrackBar) + + Dim asInt As Boolean = True + + If (TypeOf value Is Integer) Then + trackBar.Value = CInt(value) + ElseIf (TypeOf value Is System.Byte) Then + asInt = False + trackBar.Value = CType(value, Byte) + End If + + edSvc.DropDownControl(trackBar) + + If (asInt) Then + value = trackBar.Value + Else + value = CType(trackBar.Value, Byte) + End If + + End If + + End If + + Return value + + End Function + + Overrides OverLoads Public Function GetEditStyle(context As ITypeDescriptorContext) As UITypeEditorEditStyle + If ((context IsNot Nothing) And (context.Instance IsNot Nothing)) Then + Return UITypeEditorEditStyle.DropDown + End If + Return MyBase.GetEditStyle(context) + End Function + + private Sub ValueChanged(sender As object, e As EventArgs) + If (edSvc IsNot Nothing) Then + edSvc.CloseDropDown() + End If + End Sub + + End Class + +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/HostApp.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/HostApp.vb new file mode 100644 index 0000000000..7fe8b82b9a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/HostApp.vb @@ -0,0 +1,77 @@ +' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms +Imports Microsoft.Samples.WinForms.VB.FlashTrackBar + + +Namespace Microsoft.Samples.WinForms.VB.HostApp + + Public Class HostApp + Inherits System.Windows.Forms.Form + + Public Sub New() + + MyBase.New() + + HostApp = Me + + 'This call is required by the Windows Forms Designer. + InitializeComponent() + + End Sub + + 'Form overrides dispose to clean up the component list. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + End Sub + + + +#Region " Windows Form Designer generated code " + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.Container + Private WithEvents flashTrackBar1 As Microsoft.Samples.WinForms.VB.FlashTrackBar.FlashTrackBar + + Private WithEvents HostApp As System.Windows.Forms.Form + + '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.components = New System.ComponentModel.Container() + Me.flashTrackBar1 = New Microsoft.Samples.WinForms.VB.FlashTrackBar.FlashTrackBar() + + flashTrackBar1.Dock = System.Windows.Forms.DockStyle.Fill + flashTrackBar1.ForeColor = System.Drawing.Color.White + flashTrackBar1.BackColor = System.Drawing.Color.Black + flashTrackBar1.Size = New System.Drawing.Size(600, 450) + flashTrackBar1.TabIndex = 0 + flashTrackBar1.Value = 73 + flashTrackBar1.Text = "Drag the Mouse and say Wow!" + + Me.Text = "Control Example" + Me.ClientSize = New System.Drawing.Size(528, 325) + + Me.Controls.Add(flashTrackBar1) + + End Sub + +#End Region + + 'The main entry point for the application + Shared Sub Main() + System.Windows.Forms.Application.Run(New HostApp()) + End Sub + + End Class + +End Namespace + +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/makefile b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/makefile new file mode 100644 index 0000000000..6db7243d90 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlashTrackBar/VB/makefile @@ -0,0 +1,5 @@ +FlashTrackBarTest.exe: FlashTrackBar.vb FlashTrackBarDarkenByEditor.vb FlashTrackBarValueEditor.vb HostApp.vb + vbc /t:exe /r:System.Design.dll,System.dll,System.Drawing.dll,System.Windows.Forms.dll /out:FlashTrackBarTest.exe FlashTrackBar.vb FlashTrackBarDarkenByEditor.vb FlashTrackBarValueEditor.vb HostApp.vb + +clean: + del *.exe *.bin \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/VB/FlpAnchorExampleForm.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/VB/FlpAnchorExampleForm.vb new file mode 100644 index 0000000000..0550e50aaf --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel.AnchorExampleForm/VB/FlpAnchorExampleForm.vb @@ -0,0 +1,220 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + + + + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeComponent() + End Sub + Private flowLayoutPanel3 As FlowLayoutPanel + Private label2 As Label + Private button11 As Button + Private button12 As Button + Private button13 As Button + Private button14 As Button + Private button15 As Button + Private flowLayoutPanel1 As FlowLayoutPanel + Private label1 As Label + Private button1 As Button + Private button2 As Button + Private button3 As Button + Private button4 As Button + Private button5 As Button + + Private components As System.ComponentModel.IContainer = Nothing + + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + + Private Sub InitializeComponent() + Me.flowLayoutPanel3 = New System.Windows.Forms.FlowLayoutPanel() + Me.label2 = New System.Windows.Forms.Label() + Me.button11 = New System.Windows.Forms.Button() + Me.button12 = New System.Windows.Forms.Button() + Me.button13 = New System.Windows.Forms.Button() + Me.button14 = New System.Windows.Forms.Button() + Me.button15 = New System.Windows.Forms.Button() + Me.flowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel() + Me.label1 = New System.Windows.Forms.Label() + Me.button1 = New System.Windows.Forms.Button() + Me.button2 = New System.Windows.Forms.Button() + Me.button3 = New System.Windows.Forms.Button() + Me.button4 = New System.Windows.Forms.Button() + Me.button5 = New System.Windows.Forms.Button() + Me.flowLayoutPanel3.SuspendLayout() + Me.flowLayoutPanel1.SuspendLayout() + Me.SuspendLayout() + ' + ' flowLayoutPanel3 + ' + Me.flowLayoutPanel3.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.flowLayoutPanel3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle + Me.flowLayoutPanel3.Controls.Add(Me.label2) + Me.flowLayoutPanel3.Controls.Add(Me.button11) + Me.flowLayoutPanel3.Controls.Add(Me.button12) + Me.flowLayoutPanel3.Controls.Add(Me.button13) + Me.flowLayoutPanel3.Controls.Add(Me.button14) + Me.flowLayoutPanel3.Controls.Add(Me.button15) + Me.flowLayoutPanel3.Location = New System.Drawing.Point(12, 12) + Me.flowLayoutPanel3.Name = "flowLayoutPanel3" + Me.flowLayoutPanel3.Size = New System.Drawing.Size(631, 100) + Me.flowLayoutPanel3.TabIndex = 2 + ' + ' label2 + ' + Me.label2.Anchor = System.Windows.Forms.AnchorStyles.None + Me.label2.AutoSize = True + Me.label2.Location = New System.Drawing.Point(3, 28) + Me.label2.Name = "label2" + Me.label2.Size = New System.Drawing.Size(138, 14) + Me.label2.TabIndex = 10 + Me.label2.Text = "FlowDirection=LeftToRight" + ' + ' button11 + ' + Me.button11.Anchor = System.Windows.Forms.AnchorStyles.Bottom + Me.button11.AutoSize = True + Me.button11.Location = New System.Drawing.Point(147, 44) + Me.button11.Name = "button11" + Me.button11.Size = New System.Drawing.Size(86, 23) + Me.button11.TabIndex = 5 + Me.button11.Text = "Anchor=Bottom" + ' + ' button12 + ' + Me.button12.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom, System.Windows.Forms.AnchorStyles) + Me.button12.AutoSize = True + Me.button12.Location = New System.Drawing.Point(239, 3) + Me.button12.Name = "button12" + Me.button12.Size = New System.Drawing.Size(111, 64) + Me.button12.TabIndex = 6 + Me.button12.Text = "Anchor=Top, Bottom" + ' + ' button13 + ' + Me.button13.Anchor = System.Windows.Forms.AnchorStyles.None + Me.button13.BackColor = System.Drawing.SystemColors.GradientActiveCaption + Me.button13.Location = New System.Drawing.Point(356, 3) + Me.button13.Name = "button13" + Me.button13.Size = New System.Drawing.Size(75, 64) + Me.button13.TabIndex = 7 + ' + ' button14 + ' + Me.button14.Dock = System.Windows.Forms.DockStyle.Bottom + Me.button14.Location = New System.Drawing.Point(437, 44) + Me.button14.Name = "button14" + Me.button14.TabIndex = 8 + Me.button14.Text = "Dock=Bottom" + ' + ' button15 + ' + Me.button15.Dock = System.Windows.Forms.DockStyle.Fill + Me.button15.Location = New System.Drawing.Point(518, 3) + Me.button15.Name = "button15" + Me.button15.Size = New System.Drawing.Size(75, 64) + Me.button15.TabIndex = 9 + Me.button15.Text = "Dock=Fill" + ' + ' flowLayoutPanel1 + ' + Me.flowLayoutPanel1.Anchor = CType(System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.flowLayoutPanel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle + Me.flowLayoutPanel1.Controls.Add(Me.label1) + Me.flowLayoutPanel1.Controls.Add(Me.button1) + Me.flowLayoutPanel1.Controls.Add(Me.button2) + Me.flowLayoutPanel1.Controls.Add(Me.button3) + Me.flowLayoutPanel1.Controls.Add(Me.button4) + Me.flowLayoutPanel1.Controls.Add(Me.button5) + Me.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown + Me.flowLayoutPanel1.Location = New System.Drawing.Point(12, 118) + Me.flowLayoutPanel1.Name = "flowLayoutPanel1" + Me.flowLayoutPanel1.Size = New System.Drawing.Size(200, 209) + Me.flowLayoutPanel1.TabIndex = 3 + ' + ' label1 + ' + Me.label1.AutoSize = True + Me.label1.Location = New System.Drawing.Point(3, 3) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(128, 14) + Me.label1.TabIndex = 11 + Me.label1.Text = "FlowDirection=TopDown" + ' + ' button1 + ' + Me.button1.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.button1.Location = New System.Drawing.Point(74, 23) + Me.button1.Name = "button1" + Me.button1.TabIndex = 5 + Me.button1.Text = "Anchor=Right" + ' + ' button2 + ' + Me.button2.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button2.Location = New System.Drawing.Point(3, 52) + Me.button2.Name = "button2" + Me.button2.Size = New System.Drawing.Size(146, 23) + Me.button2.TabIndex = 6 + Me.button2.Text = "Anchor=Left, Right" + ' + ' button3 + ' + Me.button3.BackColor = System.Drawing.SystemColors.GradientActiveCaption + Me.button3.Location = New System.Drawing.Point(3, 81) + Me.button3.Name = "button3" + Me.button3.Size = New System.Drawing.Size(146, 23) + Me.button3.TabIndex = 7 + ' + ' button4 + ' + Me.button4.Dock = System.Windows.Forms.DockStyle.Right + Me.button4.Location = New System.Drawing.Point(74, 110) + Me.button4.Name = "button4" + Me.button4.TabIndex = 8 + Me.button4.Text = "Dock=Right" + ' + ' button5 + ' + Me.button5.Dock = System.Windows.Forms.DockStyle.Fill + Me.button5.Location = New System.Drawing.Point(3, 139) + Me.button5.Name = "button5" + Me.button5.Size = New System.Drawing.Size(146, 23) + Me.button5.TabIndex = 9 + Me.button5.Text = "Dock=Fill" + ' + ' Form1 + ' + Me.ClientSize = New System.Drawing.Size(658, 341) + Me.Controls.Add(flowLayoutPanel1) + Me.Controls.Add(flowLayoutPanel3) + Me.Name = "Form1" + Me.Text = "Form1" + Me.flowLayoutPanel3.ResumeLayout(False) + Me.flowLayoutPanel3.PerformLayout() + Me.flowLayoutPanel1.ResumeLayout(False) + Me.flowLayoutPanel1.PerformLayout() + Me.ResumeLayout(False) + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel/VB/form1.vb new file mode 100644 index 0000000000..da8cbdaca8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FlowLayoutPanel/VB/form1.vb @@ -0,0 +1,219 @@ +' + +' +Imports System.Windows.Forms +' + +Public Class Form1 + Inherits System.Windows.Forms.Form + + ' + Private Sub wrapContentsCheckBox_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles wrapContentsCheckBox.CheckedChanged + + Me.FlowLayoutPanel1.WrapContents = Me.wrapContentsCheckBox.Checked + + End Sub + ' + + ' + Private Sub flowTopDownBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles flowTopDownBtn.CheckedChanged + + Me.FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown + + End Sub + + Private Sub flowBottomUpBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles flowBottomUpBtn.CheckedChanged + + Me.FlowLayoutPanel1.FlowDirection = FlowDirection.BottomUp + + End Sub + + Private Sub flowLeftToRight_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles flowLeftToRight.CheckedChanged + + Me.FlowLayoutPanel1.FlowDirection = FlowDirection.LeftToRight + + End Sub + + Private Sub flowRightToLeftBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles flowRightToLeftBtn.CheckedChanged + + Me.FlowLayoutPanel1.FlowDirection = FlowDirection.RightToLeft + + End Sub + ' + +#Region " Windows Form Designer generated code " + + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + 'Add any initialization after the InitializeComponent() call + + End Sub + + 'Form overrides dispose to clean up the component list. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + End Sub + Friend WithEvents FlowLayoutPanel1 As System.Windows.Forms.FlowLayoutPanel + Friend WithEvents wrapContentsCheckBox As System.Windows.Forms.CheckBox + Friend WithEvents flowTopDownBtn As System.Windows.Forms.RadioButton + Friend WithEvents flowBottomUpBtn As System.Windows.Forms.RadioButton + Friend WithEvents flowLeftToRight As System.Windows.Forms.RadioButton + Friend WithEvents flowRightToLeftBtn As System.Windows.Forms.RadioButton + Friend WithEvents Button1 As System.Windows.Forms.Button + Friend WithEvents Button2 As System.Windows.Forms.Button + Friend WithEvents Button3 As System.Windows.Forms.Button + Friend WithEvents Button4 As System.Windows.Forms.Button + + '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.FlowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel + Me.wrapContentsCheckBox = New System.Windows.Forms.CheckBox + Me.flowTopDownBtn = New System.Windows.Forms.RadioButton + Me.flowBottomUpBtn = New System.Windows.Forms.RadioButton + Me.flowLeftToRight = New System.Windows.Forms.RadioButton + Me.flowRightToLeftBtn = New System.Windows.Forms.RadioButton + Me.Button1 = New System.Windows.Forms.Button + Me.Button2 = New System.Windows.Forms.Button + Me.Button3 = New System.Windows.Forms.Button + Me.Button4 = New System.Windows.Forms.Button + Me.FlowLayoutPanel1.SuspendLayout() + Me.SuspendLayout() + ' + 'FlowLayoutPanel1 + ' + Me.FlowLayoutPanel1.Controls.Add(Me.Button1) + Me.FlowLayoutPanel1.Controls.Add(Me.Button2) + Me.FlowLayoutPanel1.Controls.Add(Me.Button3) + Me.FlowLayoutPanel1.Controls.Add(Me.Button4) + Me.FlowLayoutPanel1.Location = New System.Drawing.Point(47, 55) + Me.FlowLayoutPanel1.Name = "FlowLayoutPanel1" + Me.FlowLayoutPanel1.TabIndex = 0 + ' + 'wrapContentsCheckBox + ' + Me.wrapContentsCheckBox.Location = New System.Drawing.Point(46, 162) + Me.wrapContentsCheckBox.Name = "wrapContentsCheckBox" + Me.wrapContentsCheckBox.TabIndex = 1 + Me.wrapContentsCheckBox.Text = "Wrap Contents" + ' + 'flowTopDownBtn + ' + Me.flowTopDownBtn.Location = New System.Drawing.Point(45, 193) + Me.flowTopDownBtn.Name = "flowTopDownBtn" + Me.flowTopDownBtn.TabIndex = 2 + Me.flowTopDownBtn.Text = "Flow TopDown" + ' + 'flowBottomUpBtn + ' + Me.flowBottomUpBtn.Location = New System.Drawing.Point(44, 224) + Me.flowBottomUpBtn.Name = "flowBottomUpBtn" + Me.flowBottomUpBtn.TabIndex = 3 + Me.flowBottomUpBtn.Text = "Flow BottomUp" + ' + 'flowLeftToRight + ' + Me.flowLeftToRight.Location = New System.Drawing.Point(156, 193) + Me.flowLeftToRight.Name = "flowLeftToRight" + Me.flowLeftToRight.TabIndex = 4 + Me.flowLeftToRight.Text = "Flow LeftToRight" + ' + 'flowRightToLeftBtn + ' + Me.flowRightToLeftBtn.Location = New System.Drawing.Point(155, 224) + Me.flowRightToLeftBtn.Name = "flowRightToLeftBtn" + Me.flowRightToLeftBtn.TabIndex = 5 + Me.flowRightToLeftBtn.Text = "Flow RightToLeft" + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(3, 3) + Me.Button1.Name = "Button1" + Me.Button1.TabIndex = 0 + Me.Button1.Text = "Button1" + ' + 'Button2 + ' + Me.Button2.Location = New System.Drawing.Point(84, 3) + Me.Button2.Name = "Button2" + Me.Button2.TabIndex = 1 + Me.Button2.Text = "Button2" + ' + 'Button3 + ' + Me.Button3.Location = New System.Drawing.Point(3, 32) + Me.Button3.Name = "Button3" + Me.Button3.TabIndex = 2 + Me.Button3.Text = "Button3" + ' + 'Button4 + ' + Me.Button4.Location = New System.Drawing.Point(84, 32) + Me.Button4.Name = "Button4" + Me.Button4.TabIndex = 3 + Me.Button4.Text = "Button4" + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(Me.flowRightToLeftBtn) + Me.Controls.Add(Me.flowLeftToRight) + Me.Controls.Add(Me.flowBottomUpBtn) + Me.Controls.Add(Me.flowTopDownBtn) + Me.Controls.Add(Me.wrapContentsCheckBox) + Me.Controls.Add(Me.FlowLayoutPanel1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.FlowLayoutPanel1.ResumeLayout(False) + Me.ResumeLayout(False) + + End Sub + + Friend Shared ReadOnly Property GetInstance() As Form1 + Get + If m_DefaultInstance Is Nothing OrElse m_DefaultInstance.IsDisposed() Then + SyncLock m_SyncObject + If m_DefaultInstance Is Nothing OrElse m_DefaultInstance.IsDisposed() Then + m_DefaultInstance = New Form1 + End If + End SyncLock + End If + Return m_DefaultInstance + End Get + End Property + + Private Shared m_DefaultInstance As Form1 + Private Shared m_SyncObject As New Object +#End Region + + +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb new file mode 100644 index 0000000000..b52ba68423 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.FormWithButton/VB/Form1.vb @@ -0,0 +1,37 @@ +' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + ' + Public WithEvents button1 As Button + + Public Sub New() + button1 = New Button() + button1.Size = New Size(40, 40) + button1.Location = New Point(30, 30) + button1.Text = "Click me" + Me.Controls.Add(button1) + + End Sub + ' + + ' + ' + Private Sub button1_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles button1.Click + ' + MessageBox.Show("Hello World") + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/VB/Form1.vb new file mode 100644 index 0000000000..6d6674ee07 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.GenerateMember/VB/Form1.vb @@ -0,0 +1,109 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeComponent() + End Sub + + ' + ' The Modifiers property for button1 is "Private". + Private button1 As Button + + ' The Modifiers property for button2 is "Protected". + Protected button2 As Button + + ' button3 is not a member, because + ' its GenerateMember property is false. + ' + + ' + ' Required designer variable. + ' + Private components As System.ComponentModel.IContainer = Nothing + + + ' + ' Clean up any resources being used. + ' + ' true if managed resources should be disposed; otherwise, false. + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + +#Region "Windows Form Designer generated code" + + ' + Private Sub InitializeComponent() + + ' button3 is declared in a local scope, because + ' its GenerateMember property is false. + Dim button3 As System.Windows.Forms.Button + Me.button1 = New System.Windows.Forms.Button() + Me.button2 = New System.Windows.Forms.Button() + button3 = New System.Windows.Forms.Button() + ' + Me.SuspendLayout() + ' + ' button1 + ' + Me.button1.Location = New System.Drawing.Point(12, 12) + Me.button1.Name = "button1" + Me.button1.Size = New System.Drawing.Size(75, 23) + Me.button1.TabIndex = 0 + Me.button1.Text = "button1" + ' + ' button2 + ' + Me.button2.Location = New System.Drawing.Point(12, 41) + Me.button2.Name = "button2" + Me.button2.Size = New System.Drawing.Size(75, 23) + Me.button2.TabIndex = 1 + Me.button2.Text = "button2" + ' + ' button3 + ' + button3.Location = New System.Drawing.Point(12, 70) + button3.Name = "button3" + button3.Size = New System.Drawing.Size(75, 23) + button3.TabIndex = 2 + button3.Text = "button3" + ' + ' Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(104, 109) + Me.Controls.Add(button3) + Me.Controls.Add(button2) + Me.Controls.Add(button1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + End Sub + +#End Region + +End Class + + +Class Program + + ' + ' The main entry point for the application. + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.Designer.vb new file mode 100644 index 0000000000..3dd2dfd9dc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.Designer.vb @@ -0,0 +1,254 @@ +Partial Public Class Form1 + Inherits System.Windows.Forms.Form + + _ + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + End Sub + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.FlowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel + Me.PrintDOMButton = New System.Windows.Forms.Button + Me.EnableElementMoveButton = New System.Windows.Forms.Button + Me.EnableEditingButton = New System.Windows.Forms.Button + Me.CreateHTMLMenuButton = New System.Windows.Forms.Button + Me.GetOffsetsButton = New System.Windows.Forms.Button + Me.AddURLToTooltipButton = New System.Windows.Forms.Button + Me.AddlinkToPageButton = New System.Windows.Forms.Button + Me.AddDIVMessageButton = New System.Windows.Forms.Button + Me.HandleFormSubmitButton = New System.Windows.Forms.Button + Me.ShiftRowsButton = New System.Windows.Forms.Button + Me.ScrollToElementButton = New System.Windows.Forms.Button + Me.InsertImageFooterButton = New System.Windows.Forms.Button + Me.HandleBodyErrorButton = New System.Windows.Forms.Button + Me.HandleFormFocusButton = New System.Windows.Forms.Button + Me.Button1 = New System.Windows.Forms.Button + Me.WebBrowser1 = New System.Windows.Forms.WebBrowser + Me.StatusStrip1 = New System.Windows.Forms.StatusStrip + Me.BrowserStatus = New System.Windows.Forms.ToolStripStatusLabel + Me.FlowLayoutPanel1.SuspendLayout() + Me.StatusStrip1.SuspendLayout() + Me.SuspendLayout() + ' + 'FlowLayoutPanel1 + ' + Me.FlowLayoutPanel1.Controls.Add(Me.PrintDOMButton) + Me.FlowLayoutPanel1.Controls.Add(Me.EnableElementMoveButton) + Me.FlowLayoutPanel1.Controls.Add(Me.EnableEditingButton) + Me.FlowLayoutPanel1.Controls.Add(Me.CreateHTMLMenuButton) + Me.FlowLayoutPanel1.Controls.Add(Me.GetOffsetsButton) + Me.FlowLayoutPanel1.Controls.Add(Me.AddURLToTooltipButton) + Me.FlowLayoutPanel1.Controls.Add(Me.AddlinkToPageButton) + Me.FlowLayoutPanel1.Controls.Add(Me.AddDIVMessageButton) + Me.FlowLayoutPanel1.Controls.Add(Me.HandleFormSubmitButton) + Me.FlowLayoutPanel1.Controls.Add(Me.ShiftRowsButton) + Me.FlowLayoutPanel1.Controls.Add(Me.ScrollToElementButton) + Me.FlowLayoutPanel1.Controls.Add(Me.InsertImageFooterButton) + Me.FlowLayoutPanel1.Controls.Add(Me.HandleBodyErrorButton) + Me.FlowLayoutPanel1.Controls.Add(Me.HandleFormFocusButton) + Me.FlowLayoutPanel1.Controls.Add(Me.Button1) + Me.FlowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top + Me.FlowLayoutPanel1.Location = New System.Drawing.Point(0, 0) + Me.FlowLayoutPanel1.Name = "FlowLayoutPanel1" + Me.FlowLayoutPanel1.Size = New System.Drawing.Size(656, 152) + Me.FlowLayoutPanel1.TabIndex = 0 + ' + 'PrintDOMButton + ' + Me.PrintDOMButton.Location = New System.Drawing.Point(3, 3) + Me.PrintDOMButton.Name = "PrintDOMButton" + Me.PrintDOMButton.Size = New System.Drawing.Size(155, 23) + Me.PrintDOMButton.TabIndex = 0 + Me.PrintDOMButton.Text = "Print DOM" + ' + 'EnableElementMoveButton + ' + Me.EnableElementMoveButton.Location = New System.Drawing.Point(164, 3) + Me.EnableElementMoveButton.Name = "EnableElementMoveButton" + Me.EnableElementMoveButton.Size = New System.Drawing.Size(206, 23) + Me.EnableElementMoveButton.TabIndex = 1 + Me.EnableElementMoveButton.Text = "Enable Element Move" + ' + 'EnableEditingButton + ' + Me.EnableEditingButton.Location = New System.Drawing.Point(376, 3) + Me.EnableEditingButton.Name = "EnableEditingButton" + Me.EnableEditingButton.Size = New System.Drawing.Size(159, 23) + Me.EnableEditingButton.TabIndex = 2 + Me.EnableEditingButton.Text = "Enable Editing" + ' + 'CreateHTMLMenuButton + ' + Me.CreateHTMLMenuButton.Location = New System.Drawing.Point(3, 32) + Me.CreateHTMLMenuButton.Name = "CreateHTMLMenuButton" + Me.CreateHTMLMenuButton.Size = New System.Drawing.Size(170, 23) + Me.CreateHTMLMenuButton.TabIndex = 3 + Me.CreateHTMLMenuButton.Text = "Create HTML Menu" + ' + 'GetOffsetsButton + ' + Me.GetOffsetsButton.Location = New System.Drawing.Point(179, 32) + Me.GetOffsetsButton.Name = "GetOffsetsButton" + Me.GetOffsetsButton.Size = New System.Drawing.Size(138, 23) + Me.GetOffsetsButton.TabIndex = 4 + Me.GetOffsetsButton.Text = "Get Offsets" + ' + 'AddURLToTooltipButton + ' + Me.AddURLToTooltipButton.Location = New System.Drawing.Point(323, 32) + Me.AddURLToTooltipButton.Name = "AddURLToTooltipButton" + Me.AddURLToTooltipButton.Size = New System.Drawing.Size(181, 23) + Me.AddURLToTooltipButton.TabIndex = 5 + Me.AddURLToTooltipButton.Text = "Add URL to Tooltip" + ' + 'AddlinkToPageButton + ' + Me.AddlinkToPageButton.Location = New System.Drawing.Point(3, 61) + Me.AddlinkToPageButton.Name = "AddlinkToPageButton" + Me.AddlinkToPageButton.Size = New System.Drawing.Size(146, 23) + Me.AddlinkToPageButton.TabIndex = 6 + Me.AddlinkToPageButton.Text = "Add Link to Page" + ' + 'AddDIVMessageButton + ' + Me.AddDIVMessageButton.Location = New System.Drawing.Point(155, 61) + Me.AddDIVMessageButton.Name = "AddDIVMessageButton" + Me.AddDIVMessageButton.Size = New System.Drawing.Size(162, 23) + Me.AddDIVMessageButton.TabIndex = 7 + Me.AddDIVMessageButton.Text = "Add DIV Message" + ' + 'HandleFormSubmitButton + ' + Me.HandleFormSubmitButton.Location = New System.Drawing.Point(323, 61) + Me.HandleFormSubmitButton.Name = "HandleFormSubmitButton" + Me.HandleFormSubmitButton.Size = New System.Drawing.Size(181, 23) + Me.HandleFormSubmitButton.TabIndex = 8 + Me.HandleFormSubmitButton.Text = "Handle Form Submit" + ' + 'ShiftRowsButton + ' + Me.ShiftRowsButton.Location = New System.Drawing.Point(3, 90) + Me.ShiftRowsButton.Name = "ShiftRowsButton" + Me.ShiftRowsButton.Size = New System.Drawing.Size(146, 23) + Me.ShiftRowsButton.TabIndex = 9 + Me.ShiftRowsButton.Text = "Shift Rows" + ' + 'ScrollToElementButton + ' + Me.ScrollToElementButton.Location = New System.Drawing.Point(155, 90) + Me.ScrollToElementButton.Name = "ScrollToElementButton" + Me.ScrollToElementButton.Size = New System.Drawing.Size(162, 23) + Me.ScrollToElementButton.TabIndex = 10 + Me.ScrollToElementButton.Text = "Scroll to Element" + ' + 'InsertImageFooterButton + ' + Me.InsertImageFooterButton.Location = New System.Drawing.Point(323, 90) + Me.InsertImageFooterButton.Name = "InsertImageFooterButton" + Me.InsertImageFooterButton.Size = New System.Drawing.Size(181, 23) + Me.InsertImageFooterButton.TabIndex = 11 + Me.InsertImageFooterButton.Text = "Insert Image Footer" + ' + 'HandleBodyErrorButton + ' + Me.HandleBodyErrorButton.Location = New System.Drawing.Point(510, 90) + Me.HandleBodyErrorButton.Name = "HandleBodyErrorButton" + Me.HandleBodyErrorButton.Size = New System.Drawing.Size(134, 23) + Me.HandleBodyErrorButton.TabIndex = 12 + Me.HandleBodyErrorButton.Text = "Handle Body Error" + ' + 'HandleFormFocusButton + ' + Me.HandleFormFocusButton.Location = New System.Drawing.Point(3, 119) + Me.HandleFormFocusButton.Name = "HandleFormFocusButton" + Me.HandleFormFocusButton.Size = New System.Drawing.Size(155, 23) + Me.HandleFormFocusButton.TabIndex = 13 + Me.HandleFormFocusButton.Text = "Handle Form Focus" + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(164, 119) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(206, 23) + Me.Button1.TabIndex = 14 + Me.Button1.Text = "Attach Event Handler" + ' + 'WebBrowser1 + ' + Me.WebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill + Me.WebBrowser1.Location = New System.Drawing.Point(0, 152) + Me.WebBrowser1.Name = "WebBrowser1" + Me.WebBrowser1.Size = New System.Drawing.Size(656, 273) + Me.WebBrowser1.TabIndex = 0 + Me.WebBrowser1.Url = New System.Uri("c:\userfiles\jayallen\HtmlElementProject\TestAEH.htm", System.UriKind.Absolute) + ' + 'StatusStrip1 + ' + Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.BrowserStatus}) + Me.StatusStrip1.Location = New System.Drawing.Point(0, 425) + Me.StatusStrip1.Name = "StatusStrip1" + Me.StatusStrip1.Size = New System.Drawing.Size(656, 22) + Me.StatusStrip1.TabIndex = 1 + Me.StatusStrip1.Text = "StatusStrip1" + ' + 'BrowserStatus + ' + Me.BrowserStatus.Name = "BrowserStatus" + Me.BrowserStatus.Size = New System.Drawing.Size(0, 17) + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(656, 447) + Me.Controls.Add(Me.WebBrowser1) + Me.Controls.Add(Me.FlowLayoutPanel1) + Me.Controls.Add(Me.StatusStrip1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.FlowLayoutPanel1.ResumeLayout(False) + Me.StatusStrip1.ResumeLayout(False) + Me.StatusStrip1.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + Friend WithEvents FlowLayoutPanel1 As System.Windows.Forms.FlowLayoutPanel + Friend WithEvents PrintDOMButton As System.Windows.Forms.Button + Friend WithEvents WebBrowser1 As System.Windows.Forms.WebBrowser + Friend WithEvents EnableElementMoveButton As System.Windows.Forms.Button + Friend WithEvents EnableEditingButton As System.Windows.Forms.Button + Friend WithEvents CreateHTMLMenuButton As System.Windows.Forms.Button + Friend WithEvents GetOffsetsButton As System.Windows.Forms.Button + Friend WithEvents AddURLToTooltipButton As System.Windows.Forms.Button + Friend WithEvents AddlinkToPageButton As System.Windows.Forms.Button + Friend WithEvents AddDIVMessageButton As System.Windows.Forms.Button + Friend WithEvents HandleFormSubmitButton As System.Windows.Forms.Button + Friend WithEvents ShiftRowsButton As System.Windows.Forms.Button + Friend WithEvents ScrollToElementButton As System.Windows.Forms.Button + Friend WithEvents InsertImageFooterButton As System.Windows.Forms.Button + Friend WithEvents HandleBodyErrorButton As System.Windows.Forms.Button + Friend WithEvents HandleFormFocusButton As System.Windows.Forms.Button + Friend WithEvents Button1 As System.Windows.Forms.Button + Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip + Friend WithEvents BrowserStatus As System.Windows.Forms.ToolStripStatusLabel + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.resx new file mode 100644 index 0000000000..faac01d4a5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.vb new file mode 100644 index 0000000000..3b466396ef --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/Form1.vb @@ -0,0 +1,429 @@ +Imports System.Net + +Public Class Form1 + + Private Sub PrintDOMButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintDOMButton.Click + PrintDomBegin() + End Sub + + ' + Private Sub PrintDomBegin() + If (WebBrowser1.Document IsNot Nothing) Then + Dim ElemColl As HtmlElementCollection + + Dim Doc As HtmlDocument = WebBrowser1.Document + If (Not (Doc Is Nothing)) Then + ElemColl = Doc.GetElementsByTagName("HTML") + Dim Str As String = PrintDom(ElemColl, New System.Text.StringBuilder(), 0) + + WebBrowser1.DocumentText = Str + End If + End If + End Sub + + Private Function PrintDom(ByVal ElemColl As HtmlElementCollection, ByRef ReturnStr As System.Text.StringBuilder, ByVal Depth As Integer) As String + Dim Str As New System.Text.StringBuilder() + + For Each Elem As HtmlElement In ElemColl + Dim ElemName As String + + ElemName = Elem.GetAttribute("ID") + If (ElemName Is Nothing Or ElemName.Length = 0) Then + ElemName = Elem.GetAttribute("name") + If (ElemName Is Nothing Or ElemName.Length = 0) Then + ElemName = "" + End If + End If + + Str.Append(CChar(" "), Depth * 4) + Str.Append(ElemName & ": " & Elem.TagName & "(Level " & Depth & ")") + ReturnStr.AppendLine(Str.ToString()) + + If (Elem.CanHaveChildren) Then + PrintDom(Elem.Children, ReturnStr, Depth + 1) + End If + + Str.Remove(0, Str.Length) + Next + + PrintDom = ReturnStr.ToString() + End Function + ' + + Private Sub EnableElementMoveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnableElementMoveButton.Click + + End Sub + + ' + Dim WithEvents Doc As HtmlDocument + Dim MoveElement As HtmlElement + + Private Sub EnableElementMove() + If (WebBrowser1 IsNot Nothing) Then + Doc = WebBrowser1.Document + End If + End Sub + + Private Sub Document_Click(ByVal sender As Object, ByVal args As HtmlElementEventArgs) Handles Doc.Click + If (MoveElement Is Nothing) Then + MoveElement = WebBrowser1.Document.GetElementFromPoint(args.ClientMousePosition) + Else + With WebBrowser1.Document + Dim TargetElement As HtmlElement = .GetElementFromPoint(args.ClientMousePosition) + If (TargetElement.CanHaveChildren) Then + + TargetElement.AppendChild(MoveElement) + MoveElement = Nothing + End If + End With + End If + End Sub + ' + + Private Sub EnableEditingButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnableEditingButton.Click + EnableEditing() + End Sub + + ' + Private Sub EnableEditing() + Dim Elem As HtmlElement = WebBrowser1.Document.GetElementById("div1") + If (Not Elem Is Nothing) Then + If (Elem.ClientRectangle.Width < 200) Then + Elem.SetAttribute("width", "200px") + End If + + If (Elem.ClientRectangle.Height < 50) Then + Elem.SetAttribute("height", "50px") + End If + + Elem.SetAttribute("contentEditable", "true") + Elem.Focus() + End If + End Sub + ' + + ' + Private Sub CreateHyperlinkFromSelection() + If (WebBrowser1.Document IsNot Nothing) Then + Dim IDoc As mshtml.IHTMLDocument2 = WebBrowser1.Document.DomDocument + + If (Not (IDoc Is Nothing)) Then + Dim ISelect As mshtml.IHTMLSelectionObject = IDoc.selection + If (ISelect Is Nothing) Then + MsgBox("Please select some text before using this command.") + Exit Sub + End If + + Dim TxtRange As mshtml.IHTMLTxtRange = ISelect.createRange() + + ' Create the link. + If (TxtRange.queryCommandEnabled("CreateLink")) Then + TxtRange.execCommand("CreateLink", True) + End If + End If + End If + End Sub + ' + + + Private Sub CreateHTMLMenuButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateHTMLMenuButton.Click + CreateHTMLMenu() + End Sub + + ' + Private Sub CreateHtmlMenu() + Dim Elem As HtmlElement = WebBrowser1.Document.GetElementById("div1") + + Dim HtmlMenu As String = "
" + HtmlMenu &= "
" + HtmlMenu &= "+First Level
" + HtmlMenu &= "
" + HtmlMenu &= "
First Sub-Level
" & vbCrLf + HtmlMenu &= "
Second Sub-Level
" & vbCrLf + HtmlMenu &= "
" + + HtmlMenu &= "
" + + Elem.InnerHtml = HtmlMenu + + ' Retrieve the menu cues and hook up an event handler for expanding and collapsing display of the + ' child elements. + For Each MenuCueElem As HtmlElement In Elem.GetElementsByTagName("SPAN") + If MenuCueElem.Id.EndsWith("cue") Then + AddHandler MenuCueElem.Click, New HtmlElementEventHandler(AddressOf Me.Element_Click) + End If + Next + End Sub + + Private Sub Element_Click(ByVal sender As Object, ByVal e As HtmlElementEventArgs) + ' !TODO: Need SetStyle() implemented per DCR. + End Sub + '
+ + Private Sub GetOffsetsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetOffsetsButton.Click + GetOffsets() + End Sub + + ' + Private Sub GetOffsets() + Dim Str As String = "" + Dim Doc As HtmlDocument = WebBrowser1.Document + + For Each Elem As HtmlElement In Doc.GetElementsByTagName("SPAN") + Str &= "OffsetParent for " & Elem.Id & " is " & Elem.OffsetParent.Id + Str &= "; OffsetRectangle is " & Elem.OffsetRectangle.ToString() & vbCrLf + Next + + MessageBox.Show(Str) + End Sub + ' + + Private Sub AddURLToTooltipButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddURLToTooltipButton.Click + AddUrlToTooltip() + End Sub + + ' + Private Sub AddUrlToTooltip() + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + For Each Elem As HtmlElement In .GetElementsByTagName("IMG") + If (Elem.Parent.TagName.Equals("A")) Then + Dim AltStr As String = Elem.GetAttribute("ALT") + If (Not (AltStr Is Nothing) And (AltStr.Length <> 0)) Then + Elem.SetAttribute("ALT", AltStr & " - points to " & Elem.Parent.GetAttribute("HREF")) + Else + Elem.SetAttribute("ALT", "Points to " & Elem.Parent.GetAttribute("HREF")) + End If + End If + Next + End With + End If + End Sub + ' + + Private Sub AddlinkToPageButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddlinkToPageButton.Click + AddLinkToPage("http://www.adatum.com/") + End Sub + + ' + Private Sub AddLinkToPage(ByVal url As String) + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + Dim Elem As HtmlElement = .CreateElement("A") + Elem.SetAttribute("HREF", url) + Elem.InnerText = "Visit our web site for more details." + + .Body.AppendChild(Elem) + End With + End If + End Sub + ' + + Private Sub AddDIVMessageButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddDIVMessageButton.Click + AddDivMessage() + End Sub + + ' + Private Sub AddDivMessage() + Dim CurrentUri As New Uri(WebBrowser1.Url.ToString()) + Dim HostName As String + + ' Ensure we have a host name, and not just an IP, against which to test. + If (Not CurrentUri.HostNameType = UriHostNameType.Dns) Then + Dim Permit As New DnsPermission(System.Security.Permissions.PermissionState.Unrestricted) + Permit.Assert() + + Dim HostEntry As IPHostEntry = System.Net.Dns.GetHostEntry(CurrentUri.Host) + HostName = HostEntry.HostName + Else + HostName = CurrentUri.Host + End If + + If (Not HostName.Contains("adatum.com")) Then + AddTopPageMessage("You are viewing a web site other than ADatum.com. " & _ + "Please exercise caution, and ensure your web surfing complies with all " & _ + "corporate regulations as laid out in the company handbook.") + End If + End Sub + + Private Sub AddTopPageMessage(ByVal Message As String) + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + ' Do not insert the warning again if it already exists. + Dim ReturnedElems As HtmlElementCollection = .All.GetElementsByName("ADatumWarningDiv") + If (Not (ReturnedElems Is Nothing) And (ReturnedElems.Count > 0)) Then + Exit Sub + End If + + Dim DivElem As HtmlElement = .CreateElement("DIV") + DivElem.Name = "ADatumWarningDiv" + DivElem.Style = "background-color:black;color:white;font-weight:bold;width:100%;" + DivElem.InnerText = Message + + DivElem = .Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, DivElem) + End With + End If + End Sub + ' + + Private Sub HandleFormSubmitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HandleFormSubmitButton.Click + SubmitForm("form1") + End Sub + + ' + Private Sub SubmitForm(ByVal FormName As String) + Dim Elems As HtmlElementCollection + Dim Elem As HtmlElement + + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + Elems = .All.GetElementsByName(FormName) + If (Not Elems Is Nothing And Elems.Count > 0) Then + Elem = Elems(0) + If (Elem.TagName.Equals("FORM")) Then + Elem.InvokeMember("Submit") + End If + End If + End With + End If + End Sub + ' + + + Private Sub ShiftRowsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShiftRowsButton.Click + ShiftRows("dataTable") + End Sub + + ' + Private Sub ShiftRows(ByVal TableName As String) + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + Dim Elems As HtmlElementCollection = .All.GetElementsByName(TableName) + If (Not Elems Is Nothing And Elems.Count > 0) Then + Dim Elem As HtmlElement = Elems(0) + + ' Prepare the arguments. + Dim Args(2) As Object + Args(0) = CObj("-1") + Args(1) = CObj("0") + + Elem.InvokeMember("moveRow", Args) + End If + End With + End If + End Sub + ' + + + Private Sub ScrollToElementButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScrollToElementButton.Click + ScrollToElement("orderDetails") + End Sub + + ' + Private Sub ScrollToElement(ByVal ElemName As String) + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + Dim Elems As HtmlElementCollection = .All.GetElementsByName(ElemName) + If (Not Elems Is Nothing And Elems.Count > 0) Then + Dim Elem As HtmlElement = Elems(0) + + Elem.ScrollIntoView(True) + End If + End With + End If + End Sub + ' + + Private Sub InsertImageFooterButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsertImageFooterButton.Click + InsertImageFooter() + End Sub + + ' + Private Sub InsertImageFooter() + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + Dim Elem As HtmlElement = .CreateElement("IMG") + Elem.SetAttribute("SRC", "http://www.adatum.com/images/footer-banner.jpg") + + .Body.AppendChild(Elem) + End With + End If + End Sub + ' + + + Private Sub HandleBodyErrorButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HandleBodyErrorButton.Click + SetBody() + End Sub + + ' + Dim WithEvents BodyElement As HtmlElement + + Private Sub SetBody() + If (WebBrowser1.Document IsNot Nothing) Then + BodyElement = WebBrowser1.Document.Body + End If + End Sub + + 'Private Sub HandleError(ByVal sender As Object, ByVal e As HtmlElementEventArgs) Handles BodyElement.Error + ' System.Diagnostics.EventLog.WriteEntry("Custom Application", "Scripting error occurred: " & _ + ' e. + 'End Sub + ' + + + Private Sub HandleFormFocusButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HandleFormFocusButton.Click + HandleFormFocus() + End Sub + + ' + Dim WithEvents TargetFormElement As HtmlElement + + Private Sub HandleFormFocus() + If (WebBrowser1.Document IsNot Nothing) Then + With WebBrowser1.Document + If (.Forms.Count > 0) Then + Dim TargetForm As HtmlElement = .Forms(0) + Dim SearchCollection As HtmlElementCollection = TargetForm.All.GetElementsByName("text1") + If (SearchCollection.Count = 1) Then + TargetFormElement = SearchCollection(0) + End If + End If + End With + End If + End Sub + + Private Sub TargetFormElement_Focus(ByVal sender As Object, ByVal e As HtmlElementEventArgs) + Dim TextElement As HtmlElement = e.FromElement + Dim ElementText As String = TextElement.GetAttribute("value") + + ' Check that this value is at least five characters long. + If (ElementText.Length < 5) Then + e.ReturnValue = True + MessageBox.Show("The entry in the current field must be at least five characters long.") + End If + End Sub + ' + + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + AttachCopyHandler() + End Sub + + + ' + Private Sub AttachCopyHandler() + If (WebBrowser1.Document IsNot Nothing) Then + Dim Div As HtmlElement = WebBrowser1.Document.GetElementById("Div1") + Div.AttachEventHandler("oncopy", New EventHandler(AddressOf HtmlElement_OnCopy)) + End If + End Sub + + Private Sub HtmlElement_OnCopy(ByVal sender As Object, ByVal e As EventArgs) + BrowserStatus.Text = "Selection copied. Selection is: " & Clipboard.GetText() + End Sub + ' + + Private Sub FlowLayoutPanel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles FlowLayoutPanel1.Paint + + End Sub +End Class \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/HtmlElementProject.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/HtmlElementProject.vbproj new file mode 100644 index 0000000000..8f097245af --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/HtmlElementProject.vbproj @@ -0,0 +1,96 @@ + + + Debug + AnyCPU + 8.0.41123 + 2.0 + {0032B27F-DFAF-4DD5-BB1F-8B3A3E7C7DE2} + WinExe + HtmlElementProject.My.MyApplication + HtmlElementProject + HtmlElementProject + WindowsForms + + + true + full + true + true + bin\ + HtmlElementProject.xml + 42016,42017,42018,42019,42032 + + + pdbonly + false + true + true + bin\ + HtmlElementProject.xml + 42016,42017,42018,42019,42032 + + + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + MyApplication.myapp + + + True + True + MyResources.resx + + + True + MySettings.settings + True + + + + + + Form1.vb + Designer + + + VbMyResourcesResXFileCodeGenerator + MyResources.vb + My.Resources + Designer + + + + + + MyApplicationCodeGenerator + MyApplication.vb + + + SettingsSingleFileGenerator + MySettings.vb + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..65c5feb0b9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,34 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyApplication.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyApplication.myapp new file mode 100644 index 0000000000..e84073258a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyApplication.myapp @@ -0,0 +1,10 @@ + + + true + HtmlElementProject.Form1 + false + 0 + true + 0 + 0 + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyApplication.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyApplication.vb new file mode 100644 index 0000000000..00227d3dcc --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyApplication.vb @@ -0,0 +1,29 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + Partial Class MyApplication + + Public Sub New() + MyBase.New(ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.ShutDownStyle = ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = My.Forms.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyEvents.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyEvents.vb new file mode 100644 index 0000000000..b6dfb0a6eb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyEvents.vb @@ -0,0 +1,15 @@ +Namespace My + + 'Use the editor window dropdowns in the Application pane of the Project Designer to handle MyApplication Events + ' + 'Startup: Raised when the application starts, before the startup form is created. + 'Shutdown: Raised after all application forms are closed. This event is not raised if the application is terminating abnormally. + 'UnhandledException: Raised if the application encounters an unhandled exception. + 'StartupNextInstance: Raised when launching a single-instance application and the application is already active. + 'NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. + + Partial Friend Class MyApplication + + End Class + +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyResources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyResources.resx new file mode 100644 index 0000000000..3e18af958a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyResources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyResources.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyResources.vb new file mode 100644 index 0000000000..b082861e3e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MyResources.vb @@ -0,0 +1,61 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict Off +Option Explicit On + +Imports System.IO +Imports System.Resources + +Namespace My.Resources + + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + 'This class was auto-generated by the Strongly Typed Resource Builder + 'class via a tool like ResGen or Visual Studio.NET. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + _ + Module MyResources + + Private _resMgr As System.Resources.ResourceManager + + Private _resCulture As System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Public ReadOnly Property ResourceManager() As System.Resources.ResourceManager + Get + If (_resMgr Is Nothing) Then + Dim temp As System.Resources.ResourceManager = New System.Resources.ResourceManager("HtmlElementProject.MyResources", GetType(MyResources).Assembly) + System.Threading.Thread.MemoryBarrier + _resMgr = temp + End If + Return _resMgr + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Public Property Culture() As System.Globalization.CultureInfo + Get + Return _resCulture + End Get + Set + _resCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MySettings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MySettings.settings new file mode 100644 index 0000000000..0bcb11da33 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MySettings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MySettings.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MySettings.vb new file mode 100644 index 0000000000..3d12c6fb5f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/My Project/MySettings.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict Off +Option Explicit On + + + +Partial Friend NotInheritable Class MySettings + Inherits System.Configuration.ApplicationSettingsBase + + Private Shared m_Value As MySettings + + Private Shared m_SyncObject As Object = New Object + + _ + Public Shared ReadOnly Property Value() As MySettings + Get + If (MySettings.m_Value Is Nothing) Then + System.Threading.Monitor.Enter(MySettings.m_SyncObject) + If (MySettings.m_Value Is Nothing) Then + Try + MySettings.m_Value = New MySettings + Finally + System.Threading.Monitor.Exit(MySettings.m_SyncObject) + End Try + End If + End If + Return MySettings.m_Value + End Get + End Property +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/app.config b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/app.config new file mode 100644 index 0000000000..f636923451 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.HtmlElement/VB/app.config @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb new file mode 100644 index 0000000000..555129a086 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInput/VB/form1.vb @@ -0,0 +1,134 @@ +' This sample compiles a set of miscellaneous code snippets that demonstrate +' different levels of user input control. + +' +Imports System.Drawing +Imports System.Security +Imports System.Security.Permissions +Imports System.Windows.Forms + + +Namespace KeyboardInput + _ + Class Form1 + Inherits Form + + ' The following Windows message value is defined in Winuser.h. + Private WM_KEYDOWN As Integer = &H100 + Private WithEvents CustomTextBox1 As New CustomTextBox() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Me.AutoSize = True + Me.Controls.Add(CustomTextBox1) + End Sub + + ' + ' Consume and modify several character keys. + Sub CustomTextBox1_KeyPress(ByVal sender As Object, _ + ByVal e As KeyPressEventArgs) Handles CustomTextBox1.KeyPress + + Select Case e.KeyChar + + ' + ' Consume 'A' and 'a'. + Case ChrW(65), ChrW(97) + MessageBox.Show(("Control.KeyPress: '" + _ + e.KeyChar.ToString() + "' consumed.")) + e.Handled = True + ' + + ' + ' Modify 'B' to 'A' and forward the key. + Case ChrW(66) + MessageBox.Show(("Control.KeyPress: '" + _ + e.KeyChar.ToString() + "' replaced by 'A'.")) + e.KeyChar = ChrW(65) + e.Handled = False + + ' Modify 'b' to 'a' and forward the key. + Case ChrW(98) + MessageBox.Show(("Control.KeyPress: '" + _ + e.KeyChar.ToString() + "' replaced by 'a'.")) + e.KeyChar = ChrW(97) + e.Handled = False + ' + End Select + End Sub + ' + End Class + + _ + Public Class CustomTextBox + Inherits TextBox + + ' The following Windows message value is defined in Winuser.h. + Private WM_KEYDOWN As Integer = &H100 + + Public Sub New() + Me.Size = New Size(100, 100) + Me.AutoSize = False + End Sub + + ' + ' + ' Detect F1 through F9 during preprocessing and modify F3. + Public Overrides Function PreProcessMessage(ByRef m As Message) _ + As Boolean + + If m.Msg = WM_KEYDOWN Then + Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode + + ' Detect F1 through F9. + Select Case keyCode + Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _ + Keys.F6, Keys.F7, Keys.F8, Keys.F9 + + MessageBox.Show(("Control.PreProcessMessage: '" + _ + keyCode.ToString() + "' pressed.")) + + ' Replace F3 with F1, so that ProcessKeyMessage will + ' receive F1 instead of F3. + If keyCode = Keys.F3 Then + m.WParam = CType(Keys.F1, IntPtr) + MessageBox.Show(("Control.PreProcessMessage: '" + _ + keyCode.ToString() + "' replaced by F1.")) + End If + End Select + End If + + ' Send all other messages to the base method. + Return MyBase.PreProcessMessage(m) + End Function + ' + + ' Detect F1 through F9 during processing. + Protected Overrides Function ProcessKeyMessage(ByRef m As Message) _ + As Boolean + + If m.Msg = WM_KEYDOWN Then + Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode + + ' Detect F1 through F9. + Select Case keyCode + Case Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5, _ + Keys.F6, Keys.F7, Keys.F8, Keys.F9 + + MessageBox.Show(("Control.ProcessKeyMessage: '" + _ + keyCode.ToString() + "' pressed.")) + End Select + End If + + ' Send all messages to the base method. + Return MyBase.ProcessKeyMessage(m) + End Function + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/VB/form1.vb new file mode 100644 index 0000000000..0f9288d121 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyboardInputForm/VB/form1.vb @@ -0,0 +1,76 @@ +' This sample compiles a set of miscellaneous code snippets that demonstrate +' different levels of user input control. + +' +Imports System.Drawing +Imports System.Windows.Forms + +Namespace KeyboardInputForm + + Class Form1 + Inherits Form + + Private WithEvents TextBox1 As New TextBox() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + Me.AutoSize = True + + Dim panel As New FlowLayoutPanel() + panel.AutoSize = True + panel.FlowDirection = FlowDirection.TopDown + panel.Controls.Add(TextBox1) + Me.Controls.Add(panel) + + Me.KeyPreview = True + End Sub + + ' + ' Detect all numeric characters at the form level and consume 1, + ' 4, and 7. Note that Form.KeyPreview must be set to true for this + ' event handler to be called. + Sub Form1_KeyPress(ByVal sender As Object, _ + ByVal e As KeyPressEventArgs) Handles Me.KeyPress + + If e.KeyChar >= ChrW(48) And e.KeyChar <= ChrW(57) Then + MessageBox.Show(("Form.KeyPress: '" + _ + e.KeyChar.ToString() + "' pressed.")) + + Select Case e.KeyChar + Case ChrW(49), ChrW(52), ChrW(55) + MessageBox.Show(("Form.KeyPress: '" + _ + e.KeyChar.ToString() + "' consumed.")) + e.Handled = True + End Select + End If + End Sub + ' + + ' + ' Detect all numeric characters at the TextBox level and consume + ' 2, 5, and 8. + Sub TextBox1_KeyPress(ByVal sender As Object, _ + ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress + + If e.KeyChar >= ChrW(48) And e.KeyChar <= ChrW(57) Then + MessageBox.Show(("Control.KeyPress: '" + _ + e.KeyChar.ToString() + "' pressed.")) + + Select Case e.KeyChar + Case ChrW(50), ChrW(53), ChrW(56) + MessageBox.Show(("Control.KeyPress: '" + _ + e.KeyChar.ToString() + "' consumed.")) + e.Handled = True + End Select + End If + End Sub + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/VB/Form1.vb new file mode 100644 index 0000000000..3742773252 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.KeyedCollectionsEx/VB/Form1.vb @@ -0,0 +1,317 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Class Form1 + Inherits Form + + Public Sub New() + + InitializeComponent() + ShowShippingOptions() + + ' + Me.BackgroundImage = imageList1.Images("logo.gif") + ' + End Sub + + + Private Sub ShowShippingOptions() + + ' + tabControl1.SelectedTab = tabControl1.TabPages("shippingOptions") + ' + + End Sub + + + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click + + ' + Dim OrderForm1 As New OrderForm() + OrderForm1.Show() + OrderForm1.Controls.Find("textBox1", True)(0).Focus() + ' + + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + + End Sub + + Private WithEvents button1 As System.Windows.Forms.Button + Private imageList1 As System.Windows.Forms.ImageList + Private tabControl1 As System.Windows.Forms.TabControl + Private products As System.Windows.Forms.TabPage + Private components As System.ComponentModel.IContainer + Private shippingOptions As System.Windows.Forms.TabPage + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container + Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1)) + Me.button1 = New System.Windows.Forms.Button + Me.imageList1 = New System.Windows.Forms.ImageList(Me.components) + Me.tabControl1 = New System.Windows.Forms.TabControl + Me.products = New System.Windows.Forms.TabPage + Me.shippingOptions = New System.Windows.Forms.TabPage + Me.tabControl1.SuspendLayout() + Me.SuspendLayout() + ' + 'button1 + ' + Me.button1.Location = New System.Drawing.Point(66, 218) + Me.button1.Name = "button1" + Me.button1.Size = New System.Drawing.Size(75, 23) + Me.button1.TabIndex = 0 + Me.button1.Text = "Show Order Form" + Me.button1.UseVisualStyleBackColor = True + ' + 'imageList1 + ' + Me.imageList1.ImageStream = CType(resources.GetObject("imageList1.ImageStream"), System.Windows.Forms.ImageListStreamer) + Me.imageList1.TransparentColor = System.Drawing.Color.Transparent + Me.imageList1.Images.SetKeyName(0, "order.GIF") + Me.imageList1.Images.SetKeyName(1, "logo.gif") + ' + 'tabControl1 + ' + Me.tabControl1.Controls.Add(Me.products) + Me.tabControl1.Controls.Add(Me.shippingOptions) + Me.tabControl1.Location = New System.Drawing.Point(12, 12) + Me.tabControl1.Name = "tabControl1" + Me.tabControl1.SelectedIndex = 0 + Me.tabControl1.Size = New System.Drawing.Size(264, 175) + Me.tabControl1.TabIndex = 1 + ' + 'products + ' + Me.products.Location = New System.Drawing.Point(4, 22) + Me.products.Name = "products" + Me.products.Padding = New System.Windows.Forms.Padding(3) + Me.products.Size = New System.Drawing.Size(256, 149) + Me.products.TabIndex = 0 + Me.products.Text = "Products" + Me.products.UseVisualStyleBackColor = True + ' + 'shippingOptions + ' + Me.shippingOptions.Location = New System.Drawing.Point(4, 22) + Me.shippingOptions.Name = "shippingOptions" + Me.shippingOptions.Padding = New System.Windows.Forms.Padding(3) + Me.shippingOptions.Size = New System.Drawing.Size(256, 149) + Me.shippingOptions.TabIndex = 1 + Me.shippingOptions.Text = "Shipping Options" + Me.shippingOptions.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(Me.tabControl1) + Me.Controls.Add(Me.button1) + Me.Name = "Form1" + Me.tabControl1.ResumeLayout(False) + Me.ResumeLayout(False) + + End Sub +End Class + + +Public Class OrderForm + Inherits Form + + Public Sub New() + InitializeComponent() + End Sub + + Private panel1 As System.Windows.Forms.Panel + Private label4 As System.Windows.Forms.Label + Private textBox4 As System.Windows.Forms.TextBox + Private label3 As System.Windows.Forms.Label + Private textBox3 As System.Windows.Forms.TextBox + Private label2 As System.Windows.Forms.Label + Private label1 As System.Windows.Forms.Label + Private textBox2 As System.Windows.Forms.TextBox + Private textBox1 As System.Windows.Forms.TextBox + Private label5 As System.Windows.Forms.Label + Private checkBox1 As System.Windows.Forms.CheckBox + Private panel2 As System.Windows.Forms.Panel + Private label6 As System.Windows.Forms.Label + Private listView1 As System.Windows.Forms.ListView + Private imageList1 As System.Windows.Forms.ImageList + + + Private Sub InitializeComponent() + + Me.panel1 = New System.Windows.Forms.Panel() + Me.label5 = New System.Windows.Forms.Label() + Me.checkBox1 = New System.Windows.Forms.CheckBox() + Me.label4 = New System.Windows.Forms.Label() + Me.textBox4 = New System.Windows.Forms.TextBox() + Me.label3 = New System.Windows.Forms.Label() + Me.textBox3 = New System.Windows.Forms.TextBox() + Me.label2 = New System.Windows.Forms.Label() + Me.label1 = New System.Windows.Forms.Label() + Me.textBox2 = New System.Windows.Forms.TextBox() + Me.textBox1 = New System.Windows.Forms.TextBox() + imageList1 = New ImageList() + Me.panel2 = New System.Windows.Forms.Panel() + Me.listView1 = New System.Windows.Forms.ListView() + Me.label6 = New System.Windows.Forms.Label() + Me.panel1.SuspendLayout() + Me.panel2.SuspendLayout() + Me.SuspendLayout() + ' + ' panel1 + ' + Me.panel1.Controls.Add(Me.label5) + Me.panel1.Controls.Add(Me.checkBox1) + Me.panel1.Controls.Add(Me.label4) + Me.panel1.Controls.Add(Me.textBox4) + Me.panel1.Controls.Add(Me.label3) + Me.panel1.Controls.Add(Me.textBox3) + Me.panel1.Controls.Add(Me.label2) + Me.panel1.Controls.Add(Me.label1) + Me.panel1.Controls.Add(Me.textBox2) + Me.panel1.Controls.Add(Me.textBox1) + Me.panel1.Location = New System.Drawing.Point(3, 69) + Me.panel1.Name = "panel1" + Me.panel1.Size = New System.Drawing.Size(287, 198) + Me.panel1.TabIndex = 1 + ' + ' label5 + ' + Me.label5.AutoSize = True + Me.label5.Location = New System.Drawing.Point(6, 4) + Me.label5.Name = "label5" + Me.label5.Size = New System.Drawing.Size(89, 13) + Me.label5.TabIndex = 9 + Me.label5.Text = "Billing Information" + ' + ' checkBox1 + ' + Me.checkBox1.AutoSize = True + Me.checkBox1.Location = New System.Drawing.Point(150, 4) + Me.checkBox1.Name = "checkBox1" + Me.checkBox1.Size = New System.Drawing.Size(127, 17) + Me.checkBox1.TabIndex = 8 + Me.checkBox1.Text = "Ship to same address" + Me.checkBox1.UseVisualStyleBackColor = True + ' + ' label4 + ' + Me.label4.AutoSize = True + Me.label4.Location = New System.Drawing.Point(6, 167) + Me.label4.Name = "label4" + Me.label4.Size = New System.Drawing.Size(76, 13) + Me.label4.TabIndex = 7 + Me.label4.Text = "City, State, Zip" + ' + ' textBox4 + ' + Me.textBox4.Location = New System.Drawing.Point(6, 105) + Me.textBox4.Name = "textBox4" + Me.textBox4.Size = New System.Drawing.Size(187, 20) + Me.textBox4.TabIndex = 6 + ' + ' label3 + ' + Me.label3.AutoSize = True + Me.label3.Location = New System.Drawing.Point(3, 128) + Me.label3.Name = "label3" + Me.label3.Size = New System.Drawing.Size(76, 13) + Me.label3.TabIndex = 5 + Me.label3.Text = "Address, line 2" + ' + ' textBox3 + ' + Me.textBox3.Location = New System.Drawing.Point(6, 144) + Me.textBox3.Name = "textBox3" + Me.textBox3.Size = New System.Drawing.Size(187, 20) + Me.textBox3.TabIndex = 4 + ' + ' label2 + ' + Me.label2.AutoSize = True + Me.label2.Location = New System.Drawing.Point(3, 89) + Me.label2.Name = "label2" + Me.label2.Size = New System.Drawing.Size(76, 13) + Me.label2.TabIndex = 3 + Me.label2.Text = "Address, line 1" + ' + ' label1 + ' + Me.label1.AutoSize = True + Me.label1.Location = New System.Drawing.Point(6, 50) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(35, 13) + Me.label1.TabIndex = 2 + Me.label1.Text = "Name" + ' + ' textBox2 + ' + Me.textBox2.Location = New System.Drawing.Point(6, 66) + Me.textBox2.Name = "textBox2" + Me.textBox2.Size = New System.Drawing.Size(187, 20) + Me.textBox2.TabIndex = 1 + ' + ' textBox1 + ' + Me.textBox1.Location = New System.Drawing.Point(3, 27) + Me.textBox1.Name = "textBox1" + Me.textBox1.Size = New System.Drawing.Size(190, 20) + Me.textBox1.TabIndex = 0 + ' + ' panel2 + ' + Me.panel2.Controls.Add(Me.label6) + Me.panel2.Controls.Add(Me.listView1) + Me.panel2.Location = New System.Drawing.Point(3, 2) + Me.panel2.Name = "panel2" + Me.panel2.Size = New System.Drawing.Size(287, 61) + Me.panel2.TabIndex = 0 + ' + ' listView1 + ' + Me.listView1.Location = New System.Drawing.Point(3, 23) + Me.listView1.Name = "listView1" + Me.listView1.Size = New System.Drawing.Size(274, 35) + Me.listView1.TabIndex = 0 + ' + ' label6 + ' + Me.label6.AutoSize = True + Me.label6.Location = New System.Drawing.Point(3, 7) + Me.label6.Name = "label6" + Me.label6.Size = New System.Drawing.Size(46, 13) + Me.label6.TabIndex = 1 + Me.label6.Text = "Item List" + ' + + ' + ' OrderForm + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(panel2) + Me.Controls.Add(panel1) + Me.Name = "OrderForm" + Me.Text = "Order Form" + Me.panel1.ResumeLayout(False) + Me.panel1.PerformLayout() + Me.panel2.ResumeLayout(False) + Me.panel2.PerformLayout() + Me.ResumeLayout(False) + + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/VB/DemoFlowLayout.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/VB/DemoFlowLayout.vb new file mode 100644 index 0000000000..37a3c9fc01 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Layout.LayoutEngine/VB/DemoFlowLayout.vb @@ -0,0 +1,87 @@ +' +Imports System.Collections.Generic +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms +Imports System.Windows.Forms.Layout + +' +' This class demonstrates a simple custom layout panel. +' It overrides the LayoutEngine property of the Panel +' control to provide a custom layout engine. +Public Class DemoFlowPanel + Inherits Panel + + Private layoutEng As DemoFlowLayout + + Public Sub New() + End Sub + + Public Overrides ReadOnly Property LayoutEngine() As LayoutEngine + Get + If layoutEng Is Nothing Then + layoutEng = New DemoFlowLayout() + End If + + Return layoutEng + End Get + End Property +End Class +' + +' +' This class demonstrates a simple custom layout engine. +Public Class DemoFlowLayout + Inherits LayoutEngine + + ' + Public Overrides Function Layout( _ + ByVal container As Object, _ + ByVal layoutEventArgs As LayoutEventArgs) As Boolean + + Dim parent As Control = container + + ' Use DisplayRectangle so that parent.Padding is honored. + Dim parentDisplayRectangle As Rectangle = parent.DisplayRectangle + Dim nextControlLocation As Point = parentDisplayRectangle.Location + + Dim c As Control + For Each c In parent.Controls + + ' Only apply layout to visible controls. + If c.Visible <> True Then + Continue For + End If + + ' Respect the margin of the control: + ' shift over the left and the top. + nextControlLocation.Offset(c.Margin.Left, c.Margin.Top) + + ' Set the location of the control. + c.Location = nextControlLocation + + ' Set the autosized controls to their + ' autosized heights. + If c.AutoSize Then + c.Size = c.GetPreferredSize(parentDisplayRectangle.Size) + End If + + ' Move X back to the display rectangle origin. + nextControlLocation.X = parentDisplayRectangle.X + + ' Increment Y by the height of the control + ' and the bottom margin. + nextControlLocation.Y += c.Height + c.Margin.Bottom + Next c + + ' Optional: Return whether or not the container's + ' parent should perform layout as a result of this + ' layout. Some layout engines return the value of + ' the container's AutoSize property. + Return False + + End Function + ' +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb new file mode 100644 index 0000000000..5a01af27a4 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.LegacyBufferedGraphics/VB/Class1.vb @@ -0,0 +1,87 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml + +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + ' 4c2a90ee-bbbe-4ff6-9170-1b06c195c918 + ' How to: Manually Manage Buffered Graphics + Public Sub Method11() + ' + Dim myContext As BufferedGraphicsContext + myContext = BufferedGraphicsManager.Current + + ' + End Sub + Public Sub Method12() + ' + Dim myContext As BufferedGraphicsContext + myContext = New BufferedGraphicsContext + ' Insert code to create graphics here. + ' On a nondefault BufferedGraphicsContext instance, you should always + ' call Dispose when finished. + myContext.Dispose() + + ' + End Sub + ' 5192295e-bd8e-45f7-8bd6-5c4f6bd21e61 + ' How to: Manually Render Buffered Graphics + Public Sub Method21() + ' + ' This example assumes the existence of a form called Form1. + Dim currentContext As BufferedGraphicsContext + Dim myBuffer As BufferedGraphics + ' Gets a reference to the current BufferedGraphicsContext. + currentContext = BufferedGraphicsManager.Current + ' Creates a BufferedGraphics instance associated with Form1, and with + ' dimensions the same size as the drawing surface of Form1. + myBuffer = currentContext.Allocate(Me.CreateGraphics, _ + Me.DisplayRectangle) + + ' + + ' + ' Draws an ellipse to the graphics buffer. + myBuffer.Graphics.DrawEllipse(Pens.Blue, Me.DisplayRectangle) + ' + + ' + ' Renders the contents of the buffer to the drawing surface associated + ' with the buffer. + myBuffer.Render() + ' Renders the contents of the buffer to the specified drawing surface. + myBuffer.Render(Me.CreateGraphics) + ' + + ' + myBuffer.Dispose() + ' + End Sub + + ' 91083d3a-653f-4f15-a467-0f37b2aa39d6 + ' How to: Reduce Graphics Flicker with Double Buffering for Forms and Controls + Public Sub Method31() + ' + DoubleBuffered = True + + ' + End Sub + Public Sub Method32() + ' + SetStyle(ControlStyles.OptimizedDoubleBuffer, True) + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/VB/listviewinsertionmarkexample.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/VB/listviewinsertionmarkexample.vb new file mode 100644 index 0000000000..88ac6d46fb --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/VB/listviewinsertionmarkexample.vb @@ -0,0 +1,141 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class ListViewInsertionMarkExample + Inherits Form + + Private myListView As ListView + + ' + Public Sub New() + ' Initialize myListView. + myListView = New ListView() + myListView.Dock = DockStyle.Fill + myListView.View = View.LargeIcon + myListView.MultiSelect = False + myListView.ListViewItemSorter = New ListViewIndexComparer() + + ' Initialize the insertion mark. + myListView.InsertionMark.Color = Color.Green + + ' Add items to myListView. + myListView.Items.Add("zero") + myListView.Items.Add("one") + myListView.Items.Add("two") + myListView.Items.Add("three") + myListView.Items.Add("four") + myListView.Items.Add("five") + + ' Initialize the drag-and-drop operation when running + ' under Windows XP or a later operating system. + If OSFeature.Feature.IsPresent(OSFeature.Themes) + myListView.AllowDrop = True + AddHandler myListView.ItemDrag, AddressOf myListView_ItemDrag + AddHandler myListView.DragEnter, AddressOf myListView_DragEnter + AddHandler myListView.DragOver, AddressOf myListView_DragOver + AddHandler myListView.DragLeave, AddressOf myListView_DragLeave + AddHandler myListView.DragDrop, AddressOf myListView_DragDrop + End If + + ' Initialize the form. + Me.Text = "ListView Insertion Mark Example" + Me.Controls.Add(myListView) + End Sub + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New ListViewInsertionMarkExample()) + End Sub + + ' Starts the drag-and-drop operation when an item is dragged. + Private Sub myListView_ItemDrag(sender As Object, e As ItemDragEventArgs) + myListView.DoDragDrop(e.Item, DragDropEffects.Move) + End Sub + + ' Sets the target drop effect. + Private Sub myListView_DragEnter(sender As Object, e As DragEventArgs) + e.Effect = e.AllowedEffect + End Sub + + ' + ' Moves the insertion mark as the item is dragged. + Private Sub myListView_DragOver(sender As Object, e As DragEventArgs) + ' Retrieve the client coordinates of the mouse pointer. + Dim targetPoint As Point = myListView.PointToClient(New Point(e.X, e.Y)) + + ' Retrieve the index of the item closest to the mouse pointer. + Dim targetIndex As Integer = _ + myListView.InsertionMark.NearestIndex(targetPoint) + + ' Confirm that the mouse pointer is not over the dragged item. + If targetIndex > -1 Then + ' Determine whether the mouse pointer is to the left or + ' the right of the midpoint of the closest item and set + ' the InsertionMark.AppearsAfterItem property accordingly. + Dim itemBounds As Rectangle = myListView.GetItemRect(targetIndex) + If targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) Then + myListView.InsertionMark.AppearsAfterItem = True + Else + myListView.InsertionMark.AppearsAfterItem = False + End If + End If + + ' Set the location of the insertion mark. If the mouse is + ' over the dragged item, the targetIndex value is -1 and + ' the insertion mark disappears. + myListView.InsertionMark.Index = targetIndex + End Sub + ' + + ' Removes the insertion mark when the mouse leaves the control. + Private Sub myListView_DragLeave(sender As Object, e As EventArgs) + myListView.InsertionMark.Index = -1 + End Sub + + ' Moves the item to the location of the insertion mark. + Private Sub myListView_DragDrop(sender As Object, e As DragEventArgs) + ' Retrieve the index of the insertion mark; + Dim targetIndex As Integer = myListView.InsertionMark.Index + + ' If the insertion mark is not visible, exit the method. + If targetIndex = -1 Then + Return + End If + + ' If the insertion mark is to the right of the item with + ' the corresponding index, increment the target index. + If myListView.InsertionMark.AppearsAfterItem Then + targetIndex += 1 + End If + + ' Retrieve the dragged item. + Dim draggedItem As ListViewItem = _ + CType(e.Data.GetData(GetType(ListViewItem)), ListViewItem) + + ' Insert a copy of the dragged item at the target index. + ' A copy must be inserted before the original item is removed + ' to preserve item index values. + myListView.Items.Insert(targetIndex, _ + CType(draggedItem.Clone(), ListViewItem)) + + ' Remove the original copy of the dragged item. + myListView.Items.Remove(draggedItem) + + End Sub + + ' Sorts ListViewItem objects by index. + Private Class ListViewIndexComparer + Implements System.Collections.IComparer + + Public Function Compare(x As Object, y As Object) As Integer _ + Implements System.Collections.IComparer.Compare + Return CType(x, ListViewItem).Index - CType(y, ListViewItem).Index + End Function 'Compare + + End Class + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/VB/form1.vb new file mode 100644 index 0000000000..ffbd5bb668 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Misc/VB/form1.vb @@ -0,0 +1,104 @@ +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + +#Region " Windows Form Designer generated code " + + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + 'Add any initialization after the InitializeComponent() call + + End Sub + + 'Form overrides dispose to clean up the component list. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + End Sub +Friend WithEvents ListView1 As System.Windows.Forms.ListView +Friend WithEvents Button1 As System.Windows.Forms.Button + + '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() + Dim ListViewItem11 As System.Windows.Forms.ListViewItem = New System.Windows.Forms.ListViewItem("one") + Dim ListViewItem12 As System.Windows.Forms.ListViewItem = New System.Windows.Forms.ListViewItem("two") + Dim ListViewItem13 As System.Windows.Forms.ListViewItem = New System.Windows.Forms.ListViewItem("three") + Me.ListView1 = New System.Windows.Forms.ListView + Me.Button1 = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + 'ListView1 + ' + Me.ListView1.Items.AddRange(New System.Windows.Forms.ListViewItem() {ListViewItem11, ListViewItem12, ListViewItem13}) + Me.ListView1.Location = New System.Drawing.Point(15, 41) + Me.ListView1.Name = "ListView1" + Me.ListView1.Size = New System.Drawing.Size(256, 208) + Me.ListView1.TabIndex = 0 + ' + 'Button1 + ' + Me.Button1.Location = New System.Drawing.Point(173, 11) + Me.Button1.Name = "Button1" + Me.Button1.Size = New System.Drawing.Size(73, 22) + Me.Button1.TabIndex = 1 + Me.Button1.Text = "Button1" + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.Button1) + Me.Controls.Add(Me.ListView1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + + Friend Shared Readonly Property GetInstance as Form1 + Get + if m_DefaultInstance is nothing OrElse m_DefaultInstance.IsDisposed() Then + SyncLock m_SyncObject + if m_DefaultInstance is nothing OrElse m_DefaultInstance.IsDisposed() Then + m_DefaultInstance = new Form1 + end if + End SyncLock + End If + return m_DefaultInstance + End Get + End Property + + Private Shared m_DefaultInstance as Form1 + Private Shared m_SyncObject as new Object + + Public Shared Sub Main() + Application.Run(New Form1()) + End Sub + + Public Sub DemonstrateSelection + ' + me.ListView1.Items(0).Focused = True + me.ListView1.Items(0).Selected = True + ' + End Sub + + Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click + DemonstrateSelection() + End Sub + +#End Region + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/VB/listviewtilingexample.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/VB/listviewtilingexample.vb new file mode 100644 index 0000000000..f8c95adc4b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListView.Tiling/VB/listviewtilingexample.vb @@ -0,0 +1,85 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class ListViewTilingExample + Inherits Form + + Private myImageList As ImageList + + Public Sub New() + ' Initialize myListView. + Dim myListView As New ListView() + myListView.Dock = DockStyle.Fill + myListView.View = View.Tile + + ' Initialize the tile size. + myListView.TileSize = new Size(400, 45) + + ' Initialize the item icons. + myImageList = New ImageList() + Dim myIcon as Icon = new Icon("book.ico") + Try + myImageList.Images.Add(myIcon) + Finally + myIcon.Dispose() + End Try + myIcon.Dispose() + myImageList.ImageSize = New Size(32, 32) + myListView.LargeImageList = myImageList + + ' Add column headers so the subitems will appear. + myListView.Columns.AddRange(New ColumnHeader() _ + {New ColumnHeader(), New ColumnHeader(), New ColumnHeader()}) + + ' Create items and add them to myListView. + Dim item0 As New ListViewItem( New String() _ + {"Programming Windows", _ + "Petzold, Charles", _ + "1998"}, 0 ) + Dim item1 As New ListViewItem( New String() _ + {"Code: The Hidden Language of Computer Hardware and Software", _ + "Petzold, Charles", _ + "2000"}, 0 ) + Dim item2 As New ListViewItem( New String() _ + {"Programming Windows with C#", _ + "Petzold, Charles", _ + "2001"}, 0 ) + Dim item3 As New ListViewItem( New String() _ + {"Coding Techniques for Microsoft Visual Basic .NET", _ + "Connell, John", _ + "2001"}, 0 ) + Dim item4 As New ListViewItem( New String() _ + {"C# for Java Developers", _ + "Jones, Allen / Freeman, Adam", _ + "2002"}, 0 ) + Dim item5 As New ListViewItem( New String() _ + {"Microsoft .NET XML Web Services Step by Step", _ + "Jones, Allen / Freeman, Adam", _ + "2002"}, 0 ) + myListView.Items.AddRange( _ + New ListViewItem() {item0, item1, item2, item3, item4, item5}) + + ' Initialize the form. + Me.Controls.Add(myListView) + Me.Size = new System.Drawing.Size(430, 330) + Me.Text = "ListView Tiling Example" + End Sub + + ' Clean up any resources being used. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If (disposing) Then + myImageList.Dispose() + End If + + MyBase.Dispose(disposing) + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New ListViewTilingExample()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/VB/form1.vb new file mode 100644 index 0000000000..070c0d4c89 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewFindItems/VB/form1.vb @@ -0,0 +1,168 @@ + +#Region "Using directives" + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + + +#End Region + + +Class Form1 + Inherits Form + + Public Sub New() + InitializeComponent() + + 'InitializeTextSearchListView(); + InitializeLocationSearchListView() + + End Sub + + '/ + '/ Required designer variable. + '/ + Private components As System.ComponentModel.IContainer = Nothing + + + '/ + '/ Clean up any resources being used. + '/ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + + End Sub + + #Region "Windows Form Designer generated code" + + + '/ + '/ Required method for Designer support - do not modify + '/ the contents of this method with the code editor. + '/ + Private Sub InitializeComponent() + ' + ' Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Name = "Form1" + Me.Text = "Form1" + + End Sub + + #End Region + + ' + Private textListView As New ListView() + Private WithEvents searchBox As New TextBox() + + Private Sub InitializeTextSearchListView() + searchBox.Location = New Point(150, 20) + textListView.Scrollable = True + textListView.Width = 80 + textListView.Height = 50 + + ' Set the View to list to use the FindItemWithText method. + textListView.View = View.List + + ' Populate the ListView with items. + textListView.Items.AddRange(New ListViewItem() { _ + New ListViewItem("Amy Alberts"), _ + New ListViewItem("Amy Recker"), _ + New ListViewItem("Erin Hagens"), _ + New ListViewItem("Barry Johnson"), _ + New ListViewItem("Jay Hamlin"), _ + New ListViewItem("Brian Valentine"), _ + New ListViewItem("Brian Welker"), _ + New ListViewItem("Daniel Weisman")}) + + ' Add the controls to the form. + Me.Controls.Add(textListView) + Me.Controls.Add(searchBox) + + End Sub + + ' + Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _ + Handles searchBox.TextChanged + + ' Call FindItemWithText with the contents of the textbox. + Dim foundItem As ListViewItem = _ + textListView.FindItemWithText(searchBox.Text, False, 0, True) + + If (foundItem IsNot Nothing) Then + textListView.TopItem = foundItem + End If + + End Sub + ' + ' + + ' + Private WithEvents iconListView As New ListView() + Private previousItemBox As New TextBox() + + + Private Sub InitializeLocationSearchListView() + previousItemBox.Location = New Point(150, 20) + + ' Create an image list for the icon ListView. + iconListView.LargeImageList = New ImageList() + + ' Add an image to the ListView large icon list. + iconListView.LargeImageList.Images.Add(New Bitmap(GetType(Control), "Edit.bmp")) + + ' Set the view to large icon and add some items with the image + ' in the image list. + iconListView.View = View.SmallIcon + iconListView.Items.AddRange(New ListViewItem() { _ + New ListViewItem("Amy Alberts", 0), _ + New ListViewItem("Amy Recker", 0), _ + New ListViewItem("Erin Hagens", 0), _ + New ListViewItem("Barry Johnson", 0), _ + New ListViewItem("Jay Hamlin", 0), _ + New ListViewItem("Brian Valentine", 0), _ + New ListViewItem("Brian Welker", 0), _ + New ListViewItem("Daniel Weisman", 0)}) + + Me.Controls.Add(iconListView) + Me.Controls.Add(previousItemBox) + End Sub + + ' + Sub iconListView_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _ + Handles iconListView.MouseDown + + ' Find the next item up from where the user clicked. + Dim foundItem As ListViewItem = _ + iconListView.FindNearestItem(SearchDirectionHint.Up, e.X, e.Y) + + ' Display the results in a textbox. + If (foundItem IsNot Nothing) Then + previousItemBox.Text = foundItem.Text + Else + previousItemBox.Text = "No item found" + End If + + + End Sub + ' + ' + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub +End Class + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb new file mode 100644 index 0000000000..d141050a09 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ListViewLegacyTopics/VB/Class1.vb @@ -0,0 +1,108 @@ +Option Explicit On +Option Strict On + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections +Imports System.Xml + + +Public Class Form1 + Inherits Form + + Dim ListView1 As New ListView() + Dim ImageList1 As New ImageList() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + + ' 1b35a80a-edd8-495f-a807-a28c4aae52c6 + ' How to: Add and Remove Items with the Windows Forms ListView Control + Public Sub Method11() + ' + ' Adds a new item with ImageIndex 3 + ListView1.Items.Add("List item text", 3) + + ' + End Sub + Public Sub Method12() + ' + ' Removes the first item in the list. + ListView1.Items.RemoveAt(0) + ' Clears all items: + ListView1.Items.Clear() + + ' + End Sub + ' 610416a1-8da4-436c-af19-5f19e654769b + ' How to: Group Items in a Windows Forms ListView Control + Public Sub Method21() + ' + ' Adds a new group that has a left-aligned header + ListView1.Groups.Add(New ListViewGroup("Group 1", _ + HorizontalAlignment.Left)) + ' + End Sub + Public Sub Method22() + ' + ' Removes the first group in the collection. + ListView1.Groups.RemoveAt(0) + ' Clears all groups: + ListView1.Groups.Clear() + ' + End Sub + Public Sub Method23() + ' + ' Adds the first item to the first group + ListView1.Items.Item(0).Group = ListView1.Groups(0) + ' + End Sub + ' 79174274-12ee-4a5d-80db-6ec02976d010 + ' How to: Add Columns to the Windows Forms ListView Control + Public Sub Method31() + ' + ' Set to details view + ListView1.View = View.Details + ' Add a column with width 20 and left alignment + ListView1.Columns.Add("File type", 20, HorizontalAlignment.Left) + + ' + End Sub + ' 9d577542-8595-429b-99e5-078770ec9d35 + ' How to: Display Icons for the Windows Forms ListView Control + Public Sub Method41() + ' + ListView1.SmallImageList = ImageList1 + + ' + End Sub + Public Sub Method42() + ' + ' Sets the first list item to display the 4th image. + ListView1.Items(0).ImageIndex = 3 + + ' + End Sub + ' c20e67a3-2d94-413d-9fcf-ecbd0fe251da + ' How to: Enable Tile View in a Windows Forms ListView Control + Public Sub Method51() + ' + ListView1.View = View.Tile + ' + End Sub + ' e465f044-cde7-4fd9-a687-788a73a0f554 + ' How to: Display Subitems in Columns with the Windows Forms ListView Control + Public Sub Method61() + ' + ' Adds two subitems to the first list item + ListView1.Items(0).SubItems.Add("John Smith") + ListView1.Items(0).SubItems.Add("Accounting") + + ' + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/VB/Form1.vb new file mode 100644 index 0000000000..5d9d4eabf6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.NavigatingData/VB/Form1.vb @@ -0,0 +1,97 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Data.SqlClient +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Class Form1 + Inherits Form + + Private WithEvents nextButton As Button + Private WithEvents findButton As Button + Private WithEvents customersBindingSource As BindingSource + Private customersDataGridView As DataGridView + + Public Sub New() + Me.customersDataGridView = New DataGridView() + Me.nextButton = New Button() + Me.findButton = New Button() + Me.customersBindingSource = New BindingSource() + + Me.customersDataGridView.Location = New Point(23, 62) + Me.customersDataGridView.Size = New Size(240, 150) + Me.nextButton.Location = New Point(23, 22) + Me.nextButton.Size = New Size(75, 23) + Me.nextButton.Text = "Next" + Me.findButton.Location = New Point(122, 22) + Me.findButton.Size = New Size(75, 23) + Me.findButton.Text = "Find ANTON" + Me.ClientSize = New Size(292, 266) + Me.Controls.Add(Me.findButton) + Me.Controls.Add(Me.nextButton) + Me.Controls.Add(Me.customersDataGridView) + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + ' + Sub findButton_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles findButton.Click + Dim foundIndex As Integer = customersBindingSource.Find("CustomerID", _ + "ANTON") + customersBindingSource.Position = foundIndex + End Sub + ' + + ' + Sub customersBindingSource_PositionChanged(ByVal sender As Object, _ + ByVal e As EventArgs) + + If customersBindingSource.Position = _ + customersBindingSource.Count - 1 Then + nextButton.Enabled = False + Else + nextButton.Enabled = True + End If + End Sub + ' + + ' + Private Sub nextButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles nextButton.Click + Me.customersBindingSource.MoveNext() + End Sub + ' + + ' + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + ' Create the connection string, data adapter, data table and data view. + Dim connectionString As _ + New SqlConnection("Initial Catalog=Northwind;" & _ + "Data Source=localhost;Integrated Security=SSPI;") + Dim customersDataAdapter As New SqlDataAdapter("Select * from Customers", _ + connectionString) + + Dim customerTable As New DataTable() + + ' Fill the table with the contents of the customer table. + customersDataAdapter.Fill(customerTable) + Dim customerView As New DataView(customerTable) + + ' Set data source for customersBindingSource. + customersBindingSource.DataSource = customerView + customersDataGridView.DataSource = customersBindingSource + End Sub + ' +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Padding/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Padding/VB/Form1.vb new file mode 100644 index 0000000000..8231ef6dcd --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Padding/VB/Form1.vb @@ -0,0 +1,100 @@ + ' +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + Private panel1 As Panel + Private richTextBox1 As RichTextBox + + '/ + '/ Required designer variable. + '/ + Private components As System.ComponentModel.IContainer = Nothing + + ' + ' This code example demonstrates using the Padding property to + ' create a border around a RichTextBox control. + Public Sub New() + InitializeComponent() + + Me.panel1.BackColor = System.Drawing.Color.Blue + Me.panel1.Padding = New System.Windows.Forms.Padding(5) + Me.panel1.Dock = System.Windows.Forms.DockStyle.Fill + + Me.richTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None + Me.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill + End Sub + ' + + '/ + '/ Clean up any resources being used. + '/ + '/ true if managed resources should be disposed; otherwise, false. + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + +#Region "Windows Form Designer generated code" + + '/ + '/ Required method for Designer support - do not modify + '/ the contents of this method with the code editor. + '/ + Private Sub InitializeComponent() + Me.panel1 = New System.Windows.Forms.Panel() + Me.richTextBox1 = New System.Windows.Forms.RichTextBox() + Me.panel1.SuspendLayout() + Me.SuspendLayout() + ' + ' panel1 + ' + Me.panel1.Controls.Add(Me.richTextBox1) + Me.panel1.Location = New System.Drawing.Point(20, 20) + Me.panel1.Name = "panel1" + Me.panel1.Size = New System.Drawing.Size(491, 313) + Me.panel1.TabIndex = 0 + ' + ' richTextBox1 + ' + Me.richTextBox1.Location = New System.Drawing.Point(5, 5) + Me.richTextBox1.Name = "richTextBox1" + Me.richTextBox1.Size = New System.Drawing.Size(481, 303) + Me.richTextBox1.TabIndex = 0 + Me.richTextBox1.Text = "" + ' + ' Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0F, 13.0F) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(531, 353) + Me.Controls.Add(panel1) + Me.Name = "Form1" + Me.Padding = New System.Windows.Forms.Padding(20) + Me.Text = "Form1" + Me.panel1.ResumeLayout(False) + Me.ResumeLayout(False) + End Sub + +#End Region + +End Class + + + +Public Class Program + + '/ + '/ The main entry point for the application. + '/ + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.PictureBox.LoadAsync/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.PictureBox.LoadAsync/VB/Form1.vb new file mode 100644 index 0000000000..462aa9b18c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.PictureBox.LoadAsync/VB/Form1.vb @@ -0,0 +1,131 @@ +' +Imports System.Windows.Forms + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Sub New() + + InitializeComponent() + + End Sub + + ' + Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox + ' + Friend WithEvents loadButton As System.Windows.Forms.Button + Friend WithEvents cancelLoadButton As System.Windows.Forms.Button + + ' + Private Sub loadButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles loadButton.Click + + ' Replace with a real url. + PictureBox1.LoadAsync("http://www.tailspintoys.com/image.jpg") + + End Sub + ' + + ' + Private Sub cancelLoadButton_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles cancelLoadButton.Click + + PictureBox1.CancelAsync() + + End Sub + ' + + ' + Private Sub PictureBox1_LoadCompleted( _ + ByVal sender As System.Object, _ + ByVal e As System.ComponentModel.AsyncCompletedEventArgs) _ + Handles PictureBox1.LoadCompleted + + If (e.Error IsNot Nothing) Then + MessageBox.Show(e.Error.Message, "Load Error") + ElseIf e.Cancelled Then + MessageBox.Show("Load cancelled", "Canceled") + Else + MessageBox.Show("Load completed", "Completed") + End If + + End Sub + ' + + 'Form overrides dispose to clean up the component list. + _ + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.PictureBox1 = New System.Windows.Forms.PictureBox + Me.loadButton = New System.Windows.Forms.Button + Me.cancelLoadButton = New System.Windows.Forms.Button + CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() + Me.SuspendLayout() + ' + 'PictureBox1 + ' + Me.PictureBox1.Dock = System.Windows.Forms.DockStyle.Top + Me.PictureBox1.Location = New System.Drawing.Point(10, 10) + Me.PictureBox1.Name = "PictureBox1" + Me.PictureBox1.Size = New System.Drawing.Size(311, 300) + Me.PictureBox1.TabIndex = 0 + Me.PictureBox1.TabStop = False + ' + 'loadButton + ' + Me.loadButton.Location = New System.Drawing.Point(87, 330) + Me.loadButton.Name = "loadButton" + Me.loadButton.Size = New System.Drawing.Size(75, 23) + Me.loadButton.TabIndex = 1 + Me.loadButton.Text = "Load" + ' + 'cancelLoadButton + ' + Me.cancelLoadButton.Location = New System.Drawing.Point(168, 330) + Me.cancelLoadButton.Name = "cancelLoadButton" + Me.cancelLoadButton.Size = New System.Drawing.Size(75, 23) + Me.cancelLoadButton.TabIndex = 2 + Me.cancelLoadButton.Text = "Cancel" + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(331, 385) + Me.Controls.Add(Me.cancelLoadButton) + Me.Controls.Add(Me.loadButton) + Me.Controls.Add(Me.PictureBox1) + Me.Name = "Form1" + Me.Padding = New System.Windows.Forms.Padding(10) + Me.Text = "Form1" + CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() + Me.ResumeLayout(False) + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/VB/form1.vb new file mode 100644 index 0000000000..b35c6019e3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SimulateKeyPress/VB/form1.vb @@ -0,0 +1,75 @@ +' +Imports System.Runtime.InteropServices +Imports System.Drawing +Imports System.Windows.Forms + +Namespace SimulateKeyPress + + Class Form1 + Inherits Form + Private WithEvents button1 As New Button() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + button1.Location = New Point(10, 10) + button1.TabIndex = 0 + button1.Text = "Click to automate Calculator" + button1.AutoSize = True + Me.Controls.Add(button1) + End Sub + + ' + ' Get a handle to an application window. + Declare Auto Function FindWindow Lib "USER32.DLL" ( _ + ByVal lpClassName As String, _ + ByVal lpWindowName As String) As IntPtr + + ' Activate an application window. + Declare Auto Function SetForegroundWindow Lib "USER32.DLL" _ + (ByVal hWnd As IntPtr) As Boolean + + ' Send a series of key presses to the Calculator application. + Private Sub button1_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles button1.Click + + ' Get a handle to the Calculator application. The window class + ' and window name were obtained using the Spy++ tool. + Dim calculatorHandle As IntPtr = FindWindow("CalcFrame", "Calculator") + + ' Verify that Calculator is a running process. + If calculatorHandle = IntPtr.Zero Then + MsgBox("Calculator is not running.") + Return + End If + + ' Make Calculator the foreground application and send it + ' a set of calculations. + SetForegroundWindow(calculatorHandle) + SendKeys.SendWait("111") + SendKeys.SendWait("*") + SendKeys.SendWait("11") + SendKeys.SendWait("=") + End Sub + ' + + ' + ' Send a key to the button when the user double-clicks anywhere + ' on the form. + Private Sub Form1_DoubleClick(ByVal sender As Object, _ + ByVal e As EventArgs) Handles Me.DoubleClick + + ' Send the enter key to the button, which raises the click + ' event for the button. This works because the tab stop of + ' the button is 0. + SendKeys.Send("{ENTER}") + End Sub + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/VB/form1.vb new file mode 100644 index 0000000000..89c78de9e7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.SingleVersusDoubleClick/VB/form1.vb @@ -0,0 +1,132 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Namespace SingleVersusDoubleClick + + Class Form1 + Inherits Form + Private hitTestRectangle As New Rectangle() + Private doubleClickRectangle As New Rectangle() + Private textBox1 As New TextBox() + Private WithEvents doubleClickTimer As New Timer() + Private doubleClickBar As New ProgressBar() + Private label1 As New Label() + Private label2 As New Label() + Private isFirstClick As Boolean = True + Private isDoubleClick As Boolean = False + Private milliseconds As Integer = 0 + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + label1.Location = New Point(30, 5) + label1.Size = New Size(100, 15) + label1.Text = "Hit test rectangle:" + + label2.Location = New Point(30, 70) + label2.Size = New Size(100, 15) + label2.Text = "Double click timer:" + + hitTestRectangle.Location = New Point(30, 20) + hitTestRectangle.Size = New Size(100, 40) + doubleClickTimer.Interval = 100 + + doubleClickBar.Location = New Point(30, 85) + doubleClickBar.Minimum = 0 + doubleClickBar.Maximum = SystemInformation.DoubleClickTime + + textBox1.Location = New Point(30, 120) + textBox1.Size = New Size(200, 100) + textBox1.AutoSize = False + textBox1.Multiline = True + + Me.Controls.Add(doubleClickBar) + Me.Controls.Add(textBox1) + Me.Controls.Add(label1) + Me.Controls.Add(label2) + End Sub + + ' + ' Detect a valid single click or double click. + Sub Form1_MouseDown(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles Me.MouseDown + + ' Verify that the mouse click is in the main hit + ' test rectangle. + If Not hitTestRectangle.Contains(e.Location) Then + Return + End If + + ' This is the first mouse click. + If isFirstClick = True Then + isFirstClick = False + + ' Determine the location and size of the double click + ' rectangle to draw around the cursor point. + doubleClickRectangle = New Rectangle( _ + e.X - (SystemInformation.DoubleClickSize.Width / 2), _ + e.Y - (SystemInformation.DoubleClickSize.Height / 2), _ + SystemInformation.DoubleClickSize.Width, _ + SystemInformation.DoubleClickSize.Height) + Invalidate() + + ' Start the double click timer. + doubleClickTimer.Start() + + ' This is the second mouse click. + Else + ' Verify that the mouse click is within the double click + ' rectangle and is within the system-defined double + ' click period. + If doubleClickRectangle.Contains(e.Location) And _ + milliseconds < SystemInformation.DoubleClickTime Then + isDoubleClick = True + End If + End If + End Sub + ' + + Sub doubleClickTimer_Tick(ByVal sender As Object, _ + ByVal e As EventArgs) Handles doubleClickTimer.Tick + + milliseconds += 100 + doubleClickBar.Increment(100) + + ' The timer has reached the double click time limit. + If milliseconds >= SystemInformation.DoubleClickTime Then + doubleClickTimer.Stop() + + If isDoubleClick Then + textBox1.AppendText("Perform double click action") + textBox1.AppendText(Environment.NewLine) + Else + textBox1.AppendText("Perform single click action") + textBox1.AppendText(Environment.NewLine) + End If + + ' Allow the MouseDown event handler to process clicks again. + isFirstClick = True + isDoubleClick = False + milliseconds = 0 + doubleClickBar.Value = 0 + End If + End Sub + + ' Paint the hit test and double click rectangles. + Sub Form1_Paint(ByVal sender As Object, _ + ByVal e As PaintEventArgs) Handles Me.Paint + + ' Draw the border of the main hit test rectangle. + e.Graphics.DrawRectangle(Pens.Black, hitTestRectangle) + + ' Fill in the double click rectangle. + e.Graphics.FillRectangle(Brushes.Blue, doubleClickRectangle) + End Sub + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Sound/VB/soundtestform.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Sound/VB/soundtestform.vb new file mode 100644 index 0000000000..795bdb590f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.Sound/VB/soundtestform.vb @@ -0,0 +1,381 @@ +' +Imports System.Collections +Imports System.ComponentModel +Imports System.Diagnostics +Imports System.Drawing +Imports System.Media +Imports System.Windows.Forms + +Public Class SoundTestForm + Inherits System.Windows.Forms.Form + Private label1 As System.Windows.Forms.Label + Private WithEvents filepathTextbox As System.Windows.Forms.TextBox + Private WithEvents playOnceSyncButton As System.Windows.Forms.Button + Private WithEvents playOnceAsyncButton As System.Windows.Forms.Button + Private WithEvents playLoopAsyncButton As System.Windows.Forms.Button + Private WithEvents selectFileButton As System.Windows.Forms.Button + + Private WithEvents stopButton As System.Windows.Forms.Button + Private statusBar As System.Windows.Forms.StatusBar + Private WithEvents loadSyncButton As System.Windows.Forms.Button + Private WithEvents loadAsyncButton As System.Windows.Forms.Button + Private player As SoundPlayer + + + Public Sub New() + + ' Initialize Forms Designer generated code. + InitializeComponent() + + ' Disable playback controls until a valid .wav file + ' is selected. + EnablePlaybackControls(False) + + ' Set up the status bar and other controls. + InitializeControls() + + ' Set up the SoundPlayer object. + InitializeSound() + + End Sub + + + ' Sets up the status bar and other controls. + Private Sub InitializeControls() + + ' Set up the status bar. + Dim panel As New StatusBarPanel + panel.BorderStyle = StatusBarPanelBorderStyle.Sunken + panel.Text = "Ready." + panel.AutoSize = StatusBarPanelAutoSize.Spring + Me.statusBar.ShowPanels = True + Me.statusBar.Panels.Add(panel) + + End Sub + + + ' Sets up the SoundPlayer object. + Private Sub InitializeSound() + + ' Create an instance of the SoundPlayer class. + player = New SoundPlayer + + ' Listen for the LoadCompleted event. + AddHandler player.LoadCompleted, AddressOf player_LoadCompleted + + ' Listen for the SoundLocationChanged event. + AddHandler player.SoundLocationChanged, AddressOf player_LocationChanged + + End Sub + + + Private Sub selectFileButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles selectFileButton.Click + + ' Create a new OpenFileDialog. + Dim dlg As New OpenFileDialog + + ' Make sure the dialog checks for existence of the + ' selected file. + dlg.CheckFileExists = True + + ' Allow selection of .wav files only. + dlg.Filter = "WAV files (*.wav)|*.wav" + dlg.DefaultExt = ".wav" + + ' Activate the file selection dialog. + If dlg.ShowDialog() = System.Windows.Forms.DialogResult.OK Then + ' Get the selected file's path from the dialog. + Me.filepathTextbox.Text = dlg.FileName + + ' Assign the selected file's path to the SoundPlayer object. + player.SoundLocation = filepathTextbox.Text + End If + + End Sub + + + ' Convenience method for setting message text in + ' the status bar. + Private Sub ReportStatus(ByVal statusMessage As String) + + ' If the caller passed in a message... + If (statusMessage IsNot Nothing) AndAlso _ + statusMessage <> [String].Empty Then + ' ...post the caller's message to the status bar. + Me.statusBar.Panels(0).Text = statusMessage + End If + + End Sub + + + ' Enables and disables play controls. + Private Sub EnablePlaybackControls(ByVal enabled As Boolean) + + Me.playOnceSyncButton.Enabled = enabled + Me.playOnceAsyncButton.Enabled = enabled + Me.playLoopAsyncButton.Enabled = enabled + Me.stopButton.Enabled = enabled + + End Sub + + + Private Sub filepathTextbox_TextChanged(ByVal sender As Object, _ + ByVal e As EventArgs) Handles filepathTextbox.TextChanged + + ' Disable playback controls until the new .wav is loaded. + EnablePlaybackControls(False) + + End Sub + + + Private Sub loadSyncButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles loadSyncButton.Click + + ' Disable playback controls until the .wav is successfully + ' loaded. The LoadCompleted event handler will enable them. + EnablePlaybackControls(False) + + ' + Try + ' Assign the selected file's path to the SoundPlayer object. + player.SoundLocation = filepathTextbox.Text + + ' Load the .wav file. + player.Load() + Catch ex As Exception + ReportStatus(ex.Message) + End Try + ' + + End Sub + + + Private Sub loadAsyncButton_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles loadAsyncButton.Click + + ' Disable playback controls until the .wav is successfully + ' loaded. The LoadCompleted event handler will enable them. + EnablePlaybackControls(False) + + ' + Try + ' Assign the selected file's path to the SoundPlayer object. + player.SoundLocation = Me.filepathTextbox.Text + + ' Load the .wav file. + player.LoadAsync() + Catch ex As Exception + ReportStatus(ex.Message) + End Try + ' + + End Sub + + + ' Synchronously plays the selected .wav file once. + ' If the file is large, UI response will be visibly + ' affected. + Private Sub playOnceSyncButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles playOnceSyncButton.Click + + ' + ReportStatus("Playing .wav file synchronously.") + player.PlaySync() + ReportStatus("Finished playing .wav file synchronously.") + ' + End Sub + + + ' Asynchronously plays the selected .wav file once. + Private Sub playOnceAsyncButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles playOnceAsyncButton.Click + + ' + ReportStatus("Playing .wav file asynchronously.") + player.Play() + ' + + End Sub + + + ' Asynchronously plays the selected .wav file until the user + ' clicks the Stop button. + Private Sub playLoopAsyncButton_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles playLoopAsyncButton.Click + + ' + ReportStatus("Looping .wav file asynchronously.") + player.PlayLooping() + ' + + End Sub + + + ' Stops the currently playing .wav file, if any. + Private Sub stopButton_Click(ByVal sender As System.Object, _ + ByVal e As System.EventArgs) Handles stopButton.Click + + ' + player.Stop() + ReportStatus("Stopped by user.") + ' + + End Sub + + + ' + ' Handler for the LoadCompleted event. + Private Sub player_LoadCompleted(ByVal sender As Object, _ + ByVal e As AsyncCompletedEventArgs) + + Dim message As String = [String].Format("LoadCompleted: {0}", _ + Me.filepathTextbox.Text) + ReportStatus(message) + EnablePlaybackControls(True) + + End Sub + ' + + ' + ' Handler for the SoundLocationChanged event. + Private Sub player_LocationChanged(ByVal sender As Object, _ + ByVal e As EventArgs) + Dim message As String = [String].Format("SoundLocationChanged: {0}", _ + player.SoundLocation) + ReportStatus(message) + End Sub + ' + + ' + Private Sub playSoundFromResource(ByVal sender As Object, _ + ByVal e As EventArgs) + Dim a As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly() + Dim s As System.IO.Stream = a.GetManifestResourceStream(".chimes.wav") + Dim player As SoundPlayer = New SoundPlayer(s) + player.Play() + End Sub + ' + + Private Sub InitializeComponent() + Me.filepathTextbox = New System.Windows.Forms.TextBox + Me.selectFileButton = New System.Windows.Forms.Button + Me.label1 = New System.Windows.Forms.Label + Me.loadSyncButton = New System.Windows.Forms.Button + Me.playOnceSyncButton = New System.Windows.Forms.Button + Me.playOnceAsyncButton = New System.Windows.Forms.Button + Me.stopButton = New System.Windows.Forms.Button + Me.playLoopAsyncButton = New System.Windows.Forms.Button + Me.statusBar = New System.Windows.Forms.StatusBar + Me.loadAsyncButton = New System.Windows.Forms.Button + Me.SuspendLayout() + ' + ' filepathTextbox + ' + Me.filepathTextbox.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.filepathTextbox.Location = New System.Drawing.Point(7, 25) + Me.filepathTextbox.Name = "filepathTextbox" + Me.filepathTextbox.Size = New System.Drawing.Size(263, 20) + Me.filepathTextbox.TabIndex = 1 + Me.filepathTextbox.Text = "" + ' + ' selectFileButton + ' + Me.selectFileButton.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.selectFileButton.Location = New System.Drawing.Point(276, 25) + Me.selectFileButton.Name = "selectFileButton" + Me.selectFileButton.Size = New System.Drawing.Size(23, 21) + Me.selectFileButton.TabIndex = 2 + Me.selectFileButton.Text = "..." + ' + ' label1 + ' + Me.label1.Location = New System.Drawing.Point(7, 7) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(145, 17) + Me.label1.TabIndex = 3 + Me.label1.Text = ".wav path or URL:" + ' + ' loadSyncButton + ' + Me.loadSyncButton.Location = New System.Drawing.Point(7, 53) + Me.loadSyncButton.Name = "loadSyncButton" + Me.loadSyncButton.Size = New System.Drawing.Size(142, 23) + Me.loadSyncButton.TabIndex = 4 + Me.loadSyncButton.Text = "Load Synchronously" + ' + ' playOnceSyncButton + ' + Me.playOnceSyncButton.Location = New System.Drawing.Point(7, 86) + Me.playOnceSyncButton.Name = "playOnceSyncButton" + Me.playOnceSyncButton.Size = New System.Drawing.Size(142, 23) + Me.playOnceSyncButton.TabIndex = 5 + Me.playOnceSyncButton.Text = "Play Once Synchronously" + ' + ' playOnceAsyncButton + ' + Me.playOnceAsyncButton.Location = New System.Drawing.Point(149, 86) + Me.playOnceAsyncButton.Name = "playOnceAsyncButton" + Me.playOnceAsyncButton.Size = New System.Drawing.Size(147, 23) + Me.playOnceAsyncButton.TabIndex = 6 + Me.playOnceAsyncButton.Text = "Play Once Asynchronously" + ' + ' stopButton + ' + Me.stopButton.Location = New System.Drawing.Point(149, 109) + Me.stopButton.Name = "stopButton" + Me.stopButton.Size = New System.Drawing.Size(147, 23) + Me.stopButton.TabIndex = 7 + Me.stopButton.Text = "Stop" + ' + ' playLoopAsyncButton + ' + Me.playLoopAsyncButton.Location = New System.Drawing.Point(7, 109) + Me.playLoopAsyncButton.Name = "playLoopAsyncButton" + Me.playLoopAsyncButton.Size = New System.Drawing.Size(142, 23) + Me.playLoopAsyncButton.TabIndex = 8 + Me.playLoopAsyncButton.Text = "Loop Asynchronously" + ' + ' statusBar + ' + Me.statusBar.Location = New System.Drawing.Point(0, 146) + Me.statusBar.Name = "statusBar" + Me.statusBar.Size = New System.Drawing.Size(306, 22) + Me.statusBar.SizingGrip = False + Me.statusBar.TabIndex = 9 + Me.statusBar.Text = "(no status)" + ' + ' loadAsyncButton + ' + Me.loadAsyncButton.Location = New System.Drawing.Point(149, 53) + Me.loadAsyncButton.Name = "loadAsyncButton" + Me.loadAsyncButton.Size = New System.Drawing.Size(147, 23) + Me.loadAsyncButton.TabIndex = 10 + Me.loadAsyncButton.Text = "Load Asynchronously" + ' + ' SoundTestForm + ' + Me.ClientSize = New System.Drawing.Size(306, 168) + Me.Controls.Add(loadAsyncButton) + Me.Controls.Add(statusBar) + Me.Controls.Add(playLoopAsyncButton) + Me.Controls.Add(stopButton) + Me.Controls.Add(playOnceAsyncButton) + Me.Controls.Add(playOnceSyncButton) + Me.Controls.Add(loadSyncButton) + Me.Controls.Add(label1) + Me.Controls.Add(selectFileButton) + Me.Controls.Add(filepathTextbox) + Me.MinimumSize = New System.Drawing.Size(310, 165) + Me.Name = "SoundTestForm" + Me.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show + Me.Text = "Sound API Test Form" + Me.ResumeLayout(False) + End Sub + + _ + Shared Sub Main() + Application.Run(New SoundTestForm) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/VB/TlpAnchorExampleForm.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/VB/TlpAnchorExampleForm.vb new file mode 100644 index 0000000000..cc63b53977 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.AnchorExampleForm/VB/TlpAnchorExampleForm.vb @@ -0,0 +1,258 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeComponent() + End Sub + + Private components As System.ComponentModel.IContainer = Nothing + + Private tableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel + Private button1 As System.Windows.Forms.Button + Private button2 As System.Windows.Forms.Button + Private button3 As System.Windows.Forms.Button + Private button4 As System.Windows.Forms.Button + Private button5 As System.Windows.Forms.Button + Private tableLayoutPanel2 As System.Windows.Forms.TableLayoutPanel + Private button6 As System.Windows.Forms.Button + Private button7 As System.Windows.Forms.Button + Private button8 As System.Windows.Forms.Button + Private button9 As System.Windows.Forms.Button + Private tableLayoutPanel3 As System.Windows.Forms.TableLayoutPanel + Private button10 As System.Windows.Forms.Button + Private button11 As System.Windows.Forms.Button + Private button12 As System.Windows.Forms.Button + + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + + Private Sub InitializeComponent() + Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel() + Me.button1 = New System.Windows.Forms.Button() + Me.button2 = New System.Windows.Forms.Button() + Me.button3 = New System.Windows.Forms.Button() + Me.button4 = New System.Windows.Forms.Button() + Me.button5 = New System.Windows.Forms.Button() + Me.tableLayoutPanel2 = New System.Windows.Forms.TableLayoutPanel() + Me.button6 = New System.Windows.Forms.Button() + Me.button7 = New System.Windows.Forms.Button() + Me.button8 = New System.Windows.Forms.Button() + Me.button9 = New System.Windows.Forms.Button() + Me.tableLayoutPanel3 = New System.Windows.Forms.TableLayoutPanel() + Me.button10 = New System.Windows.Forms.Button() + Me.button11 = New System.Windows.Forms.Button() + Me.button12 = New System.Windows.Forms.Button() + Me.tableLayoutPanel1.SuspendLayout() + Me.tableLayoutPanel2.SuspendLayout() + Me.tableLayoutPanel3.SuspendLayout() + Me.SuspendLayout() + ' + ' tableLayoutPanel1 + ' + Me.tableLayoutPanel1.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel1.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single + Me.tableLayoutPanel1.ColumnCount = 5 + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)) + Me.tableLayoutPanel1.Controls.Add(Me.button1, 0, 0) + Me.tableLayoutPanel1.Controls.Add(Me.button2, 1, 0) + Me.tableLayoutPanel1.Controls.Add(Me.button3, 2, 0) + Me.tableLayoutPanel1.Controls.Add(Me.button4, 3, 0) + Me.tableLayoutPanel1.Controls.Add(Me.button5, 4, 0) + Me.tableLayoutPanel1.Location = New System.Drawing.Point(12, 12) + Me.tableLayoutPanel1.Name = "tableLayoutPanel1" + Me.tableLayoutPanel1.RowCount = 1 + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)) + Me.tableLayoutPanel1.Size = New System.Drawing.Size(731, 100) + Me.tableLayoutPanel1.TabIndex = 0 + ' + ' button1 + ' + Me.button1.Anchor = System.Windows.Forms.AnchorStyles.None + Me.button1.AutoSize = True + Me.button1.Location = New System.Drawing.Point(34, 38) + Me.button1.Name = "button1" + Me.button1.Size = New System.Drawing.Size(79, 23) + Me.button1.TabIndex = 0 + Me.button1.Text = "Anchor=None" + ' + ' button2 + ' + Me.button2.Anchor = System.Windows.Forms.AnchorStyles.Left + Me.button2.AutoSize = True + Me.button2.Location = New System.Drawing.Point(150, 38) + Me.button2.Name = "button2" + Me.button2.TabIndex = 1 + Me.button2.Text = "Anchor=Left" + ' + ' button3 + ' + Me.button3.Anchor = System.Windows.Forms.AnchorStyles.Top + Me.button3.AutoSize = True + Me.button3.Location = New System.Drawing.Point(328, 4) + Me.button3.Name = "button3" + Me.button3.TabIndex = 2 + Me.button3.Text = "Anchor=Top" + ' + ' button4 + ' + Me.button4.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.button4.AutoSize = True + Me.button4.Location = New System.Drawing.Point(503, 38) + Me.button4.Name = "button4" + Me.button4.Size = New System.Drawing.Size(78, 23) + Me.button4.TabIndex = 3 + Me.button4.Text = "Anchor=Right" + ' + ' button5 + ' + Me.button5.Anchor = System.Windows.Forms.AnchorStyles.Bottom + Me.button5.AutoSize = True + Me.button5.Location = New System.Drawing.Point(614, 73) + Me.button5.Name = "button5" + Me.button5.Size = New System.Drawing.Size(86, 23) + Me.button5.TabIndex = 4 + Me.button5.Text = "Anchor=Bottom" + ' + ' tableLayoutPanel2 + ' + Me.tableLayoutPanel2.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel2.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single + Me.tableLayoutPanel2.ColumnCount = 4 + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)) + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)) + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)) + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)) + Me.tableLayoutPanel2.Controls.Add(Me.button6, 0, 0) + Me.tableLayoutPanel2.Controls.Add(Me.button7, 1, 0) + Me.tableLayoutPanel2.Controls.Add(Me.button8, 2, 0) + Me.tableLayoutPanel2.Controls.Add(Me.button9, 3, 0) + Me.tableLayoutPanel2.Location = New System.Drawing.Point(12, 118) + Me.tableLayoutPanel2.Name = "tableLayoutPanel2" + Me.tableLayoutPanel2.RowCount = 1 + Me.tableLayoutPanel2.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)) + Me.tableLayoutPanel2.Size = New System.Drawing.Size(731, 100) + Me.tableLayoutPanel2.TabIndex = 1 + ' + ' button6 + ' + Me.button6.AutoSize = True + Me.button6.Location = New System.Drawing.Point(4, 4) + Me.button6.Name = "button6" + Me.button6.TabIndex = 0 + Me.button6.Text = "Top, Left" + ' + ' button7 + ' + Me.button7.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button7.AutoSize = True + Me.button7.Location = New System.Drawing.Point(286, 4) + Me.button7.Name = "button7" + Me.button7.TabIndex = 1 + Me.button7.Text = "Top, Right" + ' + ' button8 + ' + Me.button8.Anchor = CType(System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button8.AutoSize = True + Me.button8.Location = New System.Drawing.Point(466, 73) + Me.button8.Name = "button8" + Me.button8.Size = New System.Drawing.Size(77, 23) + Me.button8.TabIndex = 2 + Me.button8.Text = "Bottom, Right" + ' + ' button9 + ' + Me.button9.Anchor = CType(System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left, System.Windows.Forms.AnchorStyles) + Me.button9.AutoSize = True + Me.button9.Location = New System.Drawing.Point(550, 73) + Me.button9.Name = "button9" + Me.button9.TabIndex = 3 + Me.button9.Text = "Bottom, Left" + ' + ' tableLayoutPanel3 + ' + Me.tableLayoutPanel3.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel3.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single + Me.tableLayoutPanel3.ColumnCount = 3 + Me.tableLayoutPanel3.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)) + Me.tableLayoutPanel3.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)) + Me.tableLayoutPanel3.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)) + Me.tableLayoutPanel3.Controls.Add(Me.button10, 0, 0) + Me.tableLayoutPanel3.Controls.Add(Me.button11, 1, 0) + Me.tableLayoutPanel3.Controls.Add(Me.button12, 2, 0) + Me.tableLayoutPanel3.Location = New System.Drawing.Point(12, 225) + Me.tableLayoutPanel3.Name = "tableLayoutPanel3" + Me.tableLayoutPanel3.RowCount = 1 + Me.tableLayoutPanel3.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)) + Me.tableLayoutPanel3.Size = New System.Drawing.Size(731, 100) + Me.tableLayoutPanel3.TabIndex = 2 + ' + ' button10 + ' + Me.button10.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button10.Location = New System.Drawing.Point(4, 39) + Me.button10.Name = "button10" + Me.button10.Size = New System.Drawing.Size(236, 23) + Me.button10.TabIndex = 0 + Me.button10.Text = "Left, Right" + ' + ' button11 + ' + Me.button11.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom, System.Windows.Forms.AnchorStyles) + Me.button11.Location = New System.Drawing.Point(327, 4) + Me.button11.Name = "button11" + Me.button11.Size = New System.Drawing.Size(75, 93) + Me.button11.TabIndex = 1 + Me.button11.Text = "Top, Bottom" + ' + ' button12 + ' + Me.button12.Anchor = CType(System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button12.Location = New System.Drawing.Point(490, 4) + Me.button12.Name = "button12" + Me.button12.Size = New System.Drawing.Size(237, 93) + Me.button12.TabIndex = 2 + Me.button12.Text = "Top, Bottom, Left, Right" + ' + ' Form1 + ' + Me.AutoSize = True + Me.ClientSize = New System.Drawing.Size(755, 338) + Me.Controls.Add(tableLayoutPanel3) + Me.Controls.Add(tableLayoutPanel2) + Me.Controls.Add(tableLayoutPanel1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.tableLayoutPanel1.ResumeLayout(False) + Me.tableLayoutPanel1.PerformLayout() + Me.tableLayoutPanel2.ResumeLayout(False) + Me.tableLayoutPanel2.PerformLayout() + Me.tableLayoutPanel3.ResumeLayout(False) + Me.ResumeLayout(False) + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class + +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/VB/basicdataentryform.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/VB/basicdataentryform.vb new file mode 100644 index 0000000000..8c19cb3e97 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.DataEntryForm/VB/basicdataentryform.vb @@ -0,0 +1,338 @@ + +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +' This form demonstrates how to build a form layout that adjusts well +' when the user resizes the form. It also demonstrates a layout that +' responds well to localization. +Class BasicDataEntryForm + Inherits System.Windows.Forms.Form + + Public Sub New() + InitializeComponent() + End Sub + + Private components As System.ComponentModel.IContainer = Nothing + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + Public Overrides Function ToString() As String + Return "Basic Data Entry Form" + End Function + + Private Sub okBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles okBtn.Click + Me.Close() + End Sub + + + Private Sub cancelBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cancelBtn.Click + Me.Close() + End Sub + + + Private Sub InitializeComponent() + Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel + Me.label1 = New System.Windows.Forms.Label + Me.label2 = New System.Windows.Forms.Label + Me.label3 = New System.Windows.Forms.Label + Me.label4 = New System.Windows.Forms.Label + Me.label5 = New System.Windows.Forms.Label + Me.label6 = New System.Windows.Forms.Label + Me.label9 = New System.Windows.Forms.Label + Me.textBox2 = New System.Windows.Forms.TextBox + Me.textBox3 = New System.Windows.Forms.TextBox + Me.textBox4 = New System.Windows.Forms.TextBox + Me.textBox5 = New System.Windows.Forms.TextBox + Me.maskedTextBox1 = New System.Windows.Forms.MaskedTextBox + Me.maskedTextBox2 = New System.Windows.Forms.MaskedTextBox + Me.comboBox1 = New System.Windows.Forms.ComboBox + Me.textBox1 = New System.Windows.Forms.TextBox + Me.label7 = New System.Windows.Forms.Label + Me.label8 = New System.Windows.Forms.Label + Me.richTextBox1 = New System.Windows.Forms.RichTextBox + Me.cancelBtn = New System.Windows.Forms.Button + Me.okBtn = New System.Windows.Forms.Button + Me.tableLayoutPanel1.SuspendLayout() + Me.SuspendLayout() + ' + 'tableLayoutPanel1 + ' + Me.tableLayoutPanel1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ + Or System.Windows.Forms.AnchorStyles.Left) _ + Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel1.ColumnCount = 4 + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) + Me.tableLayoutPanel1.Controls.Add(Me.label1, 0, 0) + Me.tableLayoutPanel1.Controls.Add(Me.label2, 2, 0) + Me.tableLayoutPanel1.Controls.Add(Me.label3, 0, 1) + Me.tableLayoutPanel1.Controls.Add(Me.label4, 0, 2) + Me.tableLayoutPanel1.Controls.Add(Me.label5, 0, 3) + Me.tableLayoutPanel1.Controls.Add(Me.label6, 2, 3) + Me.tableLayoutPanel1.Controls.Add(Me.label9, 2, 4) + Me.tableLayoutPanel1.Controls.Add(Me.textBox2, 1, 1) + Me.tableLayoutPanel1.Controls.Add(Me.textBox3, 1, 2) + Me.tableLayoutPanel1.Controls.Add(Me.textBox4, 1, 3) + Me.tableLayoutPanel1.Controls.Add(Me.textBox5, 3, 0) + Me.tableLayoutPanel1.Controls.Add(Me.maskedTextBox1, 1, 4) + Me.tableLayoutPanel1.Controls.Add(Me.maskedTextBox2, 3, 4) + Me.tableLayoutPanel1.Controls.Add(Me.comboBox1, 3, 3) + Me.tableLayoutPanel1.Controls.Add(Me.textBox1, 1, 0) + Me.tableLayoutPanel1.Controls.Add(Me.label7, 0, 5) + Me.tableLayoutPanel1.Controls.Add(Me.label8, 0, 4) + Me.tableLayoutPanel1.Controls.Add(Me.richTextBox1, 1, 5) + Me.tableLayoutPanel1.Location = New System.Drawing.Point(13, 13) + Me.tableLayoutPanel1.Name = "tableLayoutPanel1" + Me.tableLayoutPanel1.RowCount = 6 + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80.0!)) + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!)) + Me.tableLayoutPanel1.Size = New System.Drawing.Size(623, 286) + Me.tableLayoutPanel1.TabIndex = 0 + ' + 'label1 + ' + Me.label1.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label1.AutoSize = True + Me.label1.Location = New System.Drawing.Point(3, 7) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(59, 14) + Me.label1.TabIndex = 20 + Me.label1.Text = "First Name" + ' + 'label2 + ' + Me.label2.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label2.AutoSize = True + Me.label2.Location = New System.Drawing.Point(323, 7) + Me.label2.Name = "label2" + Me.label2.Size = New System.Drawing.Size(59, 14) + Me.label2.TabIndex = 21 + Me.label2.Text = "Last Name" + ' + 'label3 + ' + Me.label3.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label3.AutoSize = True + Me.label3.Location = New System.Drawing.Point(10, 35) + Me.label3.Name = "label3" + Me.label3.Size = New System.Drawing.Size(52, 14) + Me.label3.TabIndex = 22 + Me.label3.Text = "Address1" + ' + 'label4 + ' + Me.label4.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label4.AutoSize = True + Me.label4.Location = New System.Drawing.Point(7, 63) + Me.label4.Name = "label4" + Me.label4.Size = New System.Drawing.Size(55, 14) + Me.label4.TabIndex = 23 + Me.label4.Text = "Address 2" + ' + 'label5 + ' + Me.label5.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label5.AutoSize = True + Me.label5.Location = New System.Drawing.Point(38, 91) + Me.label5.Name = "label5" + Me.label5.Size = New System.Drawing.Size(24, 14) + Me.label5.TabIndex = 24 + Me.label5.Text = "City" + ' + 'label6 + ' + Me.label6.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label6.AutoSize = True + Me.label6.Location = New System.Drawing.Point(351, 91) + Me.label6.Name = "label6" + Me.label6.Size = New System.Drawing.Size(31, 14) + Me.label6.TabIndex = 25 + Me.label6.Text = "State" + ' + 'label9 + ' + Me.label9.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label9.AutoSize = True + Me.label9.Location = New System.Drawing.Point(326, 119) + Me.label9.Name = "label9" + Me.label9.Size = New System.Drawing.Size(56, 14) + Me.label9.TabIndex = 33 + Me.label9.Text = "Phone (H)" + ' + 'textBox2 + ' + Me.textBox2.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel1.SetColumnSpan(Me.textBox2, 3) + Me.textBox2.Location = New System.Drawing.Point(68, 32) + Me.textBox2.Name = "textBox2" + Me.textBox2.Size = New System.Drawing.Size(552, 20) + Me.textBox2.TabIndex = 2 + ' + 'textBox3 + ' + Me.textBox3.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel1.SetColumnSpan(Me.textBox3, 3) + Me.textBox3.Location = New System.Drawing.Point(68, 60) + Me.textBox3.Name = "textBox3" + Me.textBox3.Size = New System.Drawing.Size(552, 20) + Me.textBox3.TabIndex = 3 + ' + 'textBox4 + ' + Me.textBox4.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.textBox4.Location = New System.Drawing.Point(68, 88) + Me.textBox4.Name = "textBox4" + Me.textBox4.Size = New System.Drawing.Size(249, 20) + Me.textBox4.TabIndex = 4 + ' + 'textBox5 + ' + Me.textBox5.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.textBox5.Location = New System.Drawing.Point(388, 4) + Me.textBox5.Name = "textBox5" + Me.textBox5.Size = New System.Drawing.Size(232, 20) + Me.textBox5.TabIndex = 1 + ' + 'maskedTextBox1 + ' + Me.maskedTextBox1.Anchor = System.Windows.Forms.AnchorStyles.Left + Me.maskedTextBox1.Location = New System.Drawing.Point(68, 116) + Me.maskedTextBox1.Mask = "(999)000-0000" + Me.maskedTextBox1.Name = "maskedTextBox1" + Me.maskedTextBox1.TabIndex = 6 + ' + 'maskedTextBox2 + ' + Me.maskedTextBox2.Anchor = System.Windows.Forms.AnchorStyles.Left + Me.maskedTextBox2.Location = New System.Drawing.Point(388, 116) + Me.maskedTextBox2.Mask = "(999)000-0000" + Me.maskedTextBox2.Name = "maskedTextBox2" + Me.maskedTextBox2.TabIndex = 7 + ' + 'comboBox1 + ' + Me.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left + Me.comboBox1.FormattingEnabled = True + Me.comboBox1.Items.AddRange(New Object() {"AK - Alaska", "WA - Washington"}) + Me.comboBox1.Location = New System.Drawing.Point(388, 87) + Me.comboBox1.Name = "comboBox1" + Me.comboBox1.Size = New System.Drawing.Size(100, 21) + Me.comboBox1.TabIndex = 5 + ' + 'textBox1 + ' + Me.textBox1.Anchor = CType((System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.textBox1.Location = New System.Drawing.Point(68, 4) + Me.textBox1.Name = "textBox1" + Me.textBox1.Size = New System.Drawing.Size(249, 20) + Me.textBox1.TabIndex = 0 + ' + 'label7 + ' + Me.label7.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.label7.AutoSize = True + Me.label7.Location = New System.Drawing.Point(28, 143) + Me.label7.Name = "label7" + Me.label7.Size = New System.Drawing.Size(34, 14) + Me.label7.TabIndex = 26 + Me.label7.Text = "Notes" + ' + 'label8 + ' + Me.label8.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.label8.AutoSize = True + Me.label8.Location = New System.Drawing.Point(4, 119) + Me.label8.Name = "label8" + Me.label8.Size = New System.Drawing.Size(58, 14) + Me.label8.TabIndex = 32 + Me.label8.Text = "Phone (W)" + ' + 'richTextBox1 + ' + Me.tableLayoutPanel1.SetColumnSpan(Me.richTextBox1, 3) + Me.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill + Me.richTextBox1.Location = New System.Drawing.Point(68, 143) + Me.richTextBox1.Name = "richTextBox1" + Me.richTextBox1.Size = New System.Drawing.Size(552, 140) + Me.richTextBox1.TabIndex = 8 + Me.richTextBox1.Text = "" + ' + 'cancelBtn + ' + Me.cancelBtn.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel + Me.cancelBtn.Location = New System.Drawing.Point(558, 306) + Me.cancelBtn.Name = "cancelBtn" + Me.cancelBtn.TabIndex = 1 + Me.cancelBtn.Text = "Cancel" + ' + 'okBtn + ' + Me.okBtn.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) + Me.okBtn.DialogResult = System.Windows.Forms.DialogResult.OK + Me.okBtn.Location = New System.Drawing.Point(476, 306) + Me.okBtn.Name = "okBtn" + Me.okBtn.TabIndex = 0 + Me.okBtn.Text = "OK" + ' + 'BasicDataEntryForm + ' + Me.ClientSize = New System.Drawing.Size(642, 338) + Me.Controls.Add(Me.okBtn) + Me.Controls.Add(Me.cancelBtn) + Me.Controls.Add(Me.tableLayoutPanel1) + Me.Name = "BasicDataEntryForm" + Me.Padding = New System.Windows.Forms.Padding(9) + Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual + Me.Text = "Basic Data Entry" + Me.tableLayoutPanel1.ResumeLayout(False) + Me.tableLayoutPanel1.PerformLayout() + Me.ResumeLayout(False) + + End Sub + Friend WithEvents tableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel + Friend WithEvents label1 As System.Windows.Forms.Label + Friend WithEvents label2 As System.Windows.Forms.Label + Friend WithEvents label3 As System.Windows.Forms.Label + Friend WithEvents label4 As System.Windows.Forms.Label + Friend WithEvents label5 As System.Windows.Forms.Label + Friend WithEvents label6 As System.Windows.Forms.Label + Friend WithEvents label7 As System.Windows.Forms.Label + Friend WithEvents label8 As System.Windows.Forms.Label + Friend WithEvents label9 As System.Windows.Forms.Label + Friend WithEvents cancelBtn As System.Windows.Forms.Button + Friend WithEvents okBtn As System.Windows.Forms.Button + Friend WithEvents textBox1 As System.Windows.Forms.TextBox + Friend WithEvents textBox2 As System.Windows.Forms.TextBox + Friend WithEvents textBox3 As System.Windows.Forms.TextBox + Friend WithEvents textBox4 As System.Windows.Forms.TextBox + Friend WithEvents textBox5 As System.Windows.Forms.TextBox + Friend WithEvents maskedTextBox1 As System.Windows.Forms.MaskedTextBox + Friend WithEvents maskedTextBox2 As System.Windows.Forms.MaskedTextBox + Friend WithEvents comboBox1 As System.Windows.Forms.ComboBox + Friend WithEvents richTextBox1 As System.Windows.Forms.RichTextBox + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New BasicDataEntryForm()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/VB/localizableform.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/VB/localizableform.vb new file mode 100644 index 0000000000..b8817fff75 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel.LocalizableForm/VB/localizableform.vb @@ -0,0 +1,233 @@ + '--------------------------------------------------------------------- +' This file is part of the Microsoft .NET Framework SDK Code Samples. +' +' Copyright (C) Microsoft Corporation. All rights reserved. +' +'This source code is intended only as a supplement to Microsoft +'Development Tools and/or on-line documentation. See these other +'materials for detailed information regarding Microsoft code samples. +' +'THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY +'KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +'IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A +'PARTICULAR PURPOSE. +'--------------------------------------------------------------------- +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Public Class LocalizableForm + Inherits Form + + Private tableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel + Private listView1 As System.Windows.Forms.ListView + Private panel1 As System.Windows.Forms.Panel + Private WithEvents button3 As System.Windows.Forms.Button + Private WithEvents button2 As System.Windows.Forms.Button + Private WithEvents button1 As System.Windows.Forms.Button + Private tableLayoutPanel2 As System.Windows.Forms.TableLayoutPanel + Private WithEvents button4 As System.Windows.Forms.Button + Private WithEvents button5 As System.Windows.Forms.Button + Private WithEvents button6 As System.Windows.Forms.Button + Private label1 As System.Windows.Forms.Label + + Private components As System.ComponentModel.IContainer = Nothing + + Public Sub New() + InitializeComponent() + End Sub + + Private Sub AddText(sender As Object, e As EventArgs) Handles button3.Click, button2.Click, button1.Click, button4.Click, button5.Click, button6.Click + CType(sender, Button).Text += "x" + End Sub + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + Private Sub InitializeComponent() + Dim listViewGroup16 As New System.Windows.Forms.ListViewGroup("First Group", System.Windows.Forms.HorizontalAlignment.Left) + Dim listViewGroup17 As New System.Windows.Forms.ListViewGroup("Second Group", System.Windows.Forms.HorizontalAlignment.Left) + Dim listViewGroup18 As New System.Windows.Forms.ListViewGroup("Third Group", System.Windows.Forms.HorizontalAlignment.Left) + Dim listViewItem26 As New System.Windows.Forms.ListViewItem("Item 1") + Dim listViewItem27 As New System.Windows.Forms.ListViewItem("Item 2") + Dim listViewItem28 As New System.Windows.Forms.ListViewItem("Item 3") + Dim listViewItem29 As New System.Windows.Forms.ListViewItem("Item 4") + Dim listViewItem30 As New System.Windows.Forms.ListViewItem("Item 5") + Me.tableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel() + Me.listView1 = New System.Windows.Forms.ListView() + Me.panel1 = New System.Windows.Forms.Panel() + Me.button3 = New System.Windows.Forms.Button() + Me.button2 = New System.Windows.Forms.Button() + Me.button1 = New System.Windows.Forms.Button() + Me.tableLayoutPanel2 = New System.Windows.Forms.TableLayoutPanel() + Me.button4 = New System.Windows.Forms.Button() + Me.button5 = New System.Windows.Forms.Button() + Me.button6 = New System.Windows.Forms.Button() + Me.label1 = New System.Windows.Forms.Label() + Me.tableLayoutPanel1.SuspendLayout() + Me.panel1.SuspendLayout() + Me.tableLayoutPanel2.SuspendLayout() + Me.SuspendLayout() + ' + ' tableLayoutPanel1 + ' + Me.tableLayoutPanel1.ColumnCount = 2 + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle()) + Me.tableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)) + Me.tableLayoutPanel1.Controls.Add(Me.listView1, 1, 0) + Me.tableLayoutPanel1.Controls.Add(Me.panel1, 0, 0) + Me.tableLayoutPanel1.Location = New System.Drawing.Point(2, 52) + Me.tableLayoutPanel1.Name = "tableLayoutPanel1" + Me.tableLayoutPanel1.RowCount = 1 + Me.tableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)) + Me.tableLayoutPanel1.Size = New System.Drawing.Size(524, 270) + Me.tableLayoutPanel1.TabIndex = 1 + ' + ' listView1 + ' + Me.listView1.Dock = System.Windows.Forms.DockStyle.Fill + listViewGroup16.Header = "First Group" + listViewGroup16.Name = Nothing + listViewGroup17.Header = "Second Group" + listViewGroup17.Name = Nothing + listViewGroup18.Header = "Third Group" + listViewGroup18.Name = Nothing + Me.listView1.Groups.AddRange(New System.Windows.Forms.ListViewGroup() {listViewGroup16, listViewGroup17, listViewGroup18}) + 'this.listView1.IsBackgroundImageTiled = false; + listViewItem26.Group = listViewGroup16 + listViewItem27.Group = listViewGroup16 + listViewItem28.Group = listViewGroup17 + listViewItem29.Group = listViewGroup17 + listViewItem30.Group = listViewGroup18 + Me.listView1.Items.AddRange(New System.Windows.Forms.ListViewItem() {listViewItem26, listViewItem27, listViewItem28, listViewItem29, listViewItem30}) + Me.listView1.Location = New System.Drawing.Point(90, 3) + Me.listView1.Name = "listView1" + Me.listView1.Size = New System.Drawing.Size(431, 264) + Me.listView1.TabIndex = 1 + ' + ' panel1 + ' + Me.panel1.Anchor = System.Windows.Forms.AnchorStyles.Top + Me.panel1.AutoSize = True + Me.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink + Me.panel1.Controls.Add(Me.button3) + Me.panel1.Controls.Add(Me.button2) + Me.panel1.Controls.Add(Me.button1) + Me.panel1.Location = New System.Drawing.Point(3, 3) + Me.panel1.Name = "panel1" + Me.panel1.Size = New System.Drawing.Size(81, 86) + Me.panel1.TabIndex = 2 + ' + ' button3 + ' + Me.button3.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button3.AutoSize = True + Me.button3.Location = New System.Drawing.Point(3, 60) + Me.button3.Name = "button3" + Me.button3.TabIndex = 2 + Me.button3.Text = "Add Text" + ' + ' button2 + ' + Me.button2.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button2.AutoSize = True + Me.button2.Location = New System.Drawing.Point(3, 31) + Me.button2.Name = "button2" + Me.button2.TabIndex = 1 + Me.button2.Text = "Add Text" + ' + ' button1 + ' + Me.button1.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button1.AutoSize = True + Me.button1.Location = New System.Drawing.Point(3, 2) + Me.button1.Name = "button1" + Me.button1.TabIndex = 0 + Me.button1.Text = "Add Text" + ' + ' tableLayoutPanel2 + ' + Me.tableLayoutPanel2.Anchor = CType(System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.tableLayoutPanel2.AutoSize = True + Me.tableLayoutPanel2.ColumnCount = 3 + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)) + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)) + Me.tableLayoutPanel2.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)) + Me.tableLayoutPanel2.Controls.Add(Me.button4, 0, 0) + Me.tableLayoutPanel2.Controls.Add(Me.button5, 1, 0) + Me.tableLayoutPanel2.Controls.Add(Me.button6, 2, 0) + Me.tableLayoutPanel2.Location = New System.Drawing.Point(284, 328) + Me.tableLayoutPanel2.Name = "tableLayoutPanel2" + Me.tableLayoutPanel2.RowCount = 1 + Me.tableLayoutPanel2.RowStyles.Add(New System.Windows.Forms.RowStyle()) + Me.tableLayoutPanel2.Size = New System.Drawing.Size(243, 34) + Me.tableLayoutPanel2.TabIndex = 2 + ' + ' button4 + ' + Me.button4.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button4.AutoSize = True + Me.button4.Location = New System.Drawing.Point(3, 5) + Me.button4.Name = "button4" + Me.button4.TabIndex = 0 + Me.button4.Text = "Add Text" + ' + ' button5 + ' + Me.button5.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button5.AutoSize = True + Me.button5.Location = New System.Drawing.Point(84, 5) + Me.button5.Name = "button5" + Me.button5.TabIndex = 1 + Me.button5.Text = "Add Text" + ' + ' button6 + ' + Me.button6.Anchor = CType(System.Windows.Forms.AnchorStyles.Left Or System.Windows.Forms.AnchorStyles.Right, System.Windows.Forms.AnchorStyles) + Me.button6.AutoSize = True + Me.button6.Location = New System.Drawing.Point(165, 5) + Me.button6.Name = "button6" + Me.button6.TabIndex = 2 + Me.button6.Text = "Add Text" + ' + ' label1 + ' + Me.label1.Location = New System.Drawing.Point(8, 7) + Me.label1.Name = "label1" + Me.label1.Size = New System.Drawing.Size(518, 40) + Me.label1.TabIndex = 3 + Me.label1.Text = "Click on any button to add text to the button. This simulates localizing strings," + " and provides a good demonstration of how the dialog will automatically adjust w" + "hen those longer strings are added to the UI." + ' + ' LocalizableForm + ' + Me.ClientSize = New System.Drawing.Size(539, 374) + Me.Controls.Add(label1) + Me.Controls.Add(tableLayoutPanel2) + Me.Controls.Add(tableLayoutPanel1) + Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle + Me.Name = "LocalizableForm" + Me.Text = "Localizable Dialog" + Me.tableLayoutPanel1.ResumeLayout(False) + Me.tableLayoutPanel1.PerformLayout() + Me.panel1.ResumeLayout(False) + Me.panel1.PerformLayout() + Me.tableLayoutPanel2.ResumeLayout(False) + Me.tableLayoutPanel2.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New LocalizableForm()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel/VB/form1.vb new file mode 100644 index 0000000000..7db47eed0e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TableLayoutPanel/VB/form1.vb @@ -0,0 +1,857 @@ +' +Imports System.Collections +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.Layout +Imports System.Diagnostics + +Public Class Form1 + Inherits System.Windows.Forms.Form + + Dim tlpGrowStyle As TableLayoutPanelGrowStyle = _ + TableLayoutPanelGrowStyle.AddRows + + ' + Private Sub enumerateChildrenBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles enumerateChildrenBtn.Click + + Dim c As Control + For Each c In Me.TableLayoutPanel1.Controls + + Trace.WriteLine(c.ToString()) + + Next + + End Sub + ' + + ' + Private Sub getColumnBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles getColumnBtn.Click + + Dim c As Control + For Each c In Me.TableLayoutPanel1.Controls + + Trace.WriteLine(Me.TableLayoutPanel1.GetColumn(c)) + + Next + + End Sub + ' + + + ' + Private Sub getRowBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles getRowBtn.Click + + Dim c As Control + For Each c In Me.TableLayoutPanel1.Controls + + Trace.WriteLine(Me.TableLayoutPanel1.GetRow(c)) + + Next + + End Sub + ' + + ' + Private Sub getcontrolFromPosBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles getcontrolFromPosBtn.Click + + + Trace.WriteLine(Me.TableLayoutPanel1.ColumnCount) + Trace.WriteLine(Me.TableLayoutPanel1.RowCount) + + For i As Integer = 0 To Me.TableLayoutPanel1.ColumnCount - 1 + For j As Integer = 0 To Me.TableLayoutPanel1.RowCount - 1 + + Dim c As Control = Me.TableLayoutPanel1.GetControlFromPosition(i, j) + + If c IsNot Nothing Then + + Trace.WriteLine(c.ToString()) + + End If + Next + Next + + End Sub + ' + + ' + Private Sub swapControlsBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles swapControlsBtn.Click + + Dim c1 As Control = Me.TableLayoutPanel1.GetControlFromPosition(0, 0) + Dim c2 As Control = Me.TableLayoutPanel1.GetControlFromPosition(0, 1) + + If c1 IsNot Nothing And c2 IsNot Nothing Then + + Me.TableLayoutPanel1.SetColumn(c2, 0) + Me.TableLayoutPanel1.SetColumn(c1, 1) + + End If + + End Sub + ' + + ' + Private Sub swapRowsBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles swapRowsBtn.Click + + Dim c1 As Control = Me.TableLayoutPanel1.GetControlFromPosition(0, 0) + Dim c2 As Control = Me.TableLayoutPanel1.GetControlFromPosition(1, 0) + + If c1 IsNot Nothing And c2 IsNot Nothing Then + + Me.TableLayoutPanel1.SetRow(c2, 0) + Me.TableLayoutPanel1.SetRow(c1, 1) + + End If + + + End Sub + ' + + ' + Private Sub borderStyleOutsetRadioBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles borderStyleOutsetRadioBtn.CheckedChanged + + Me.TableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Outset + + End Sub + + Private Sub borderStyleNoneRadioBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles borderStyleNoneRadioBtn.CheckedChanged + + Me.TableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.None + + End Sub + + Private Sub borderStyleInsetRadioBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles borderStyleInsetRadioBtn.CheckedChanged + + Me.TableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset + + End Sub + ' + + ' + Private Sub growStyleNoneBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles growStyleNoneBtn.CheckedChanged + + Me.tlpGrowStyle = TableLayoutPanelGrowStyle.FixedSize + + End Sub + + Private Sub growStyleAddRowBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles growStyleAddRowBtn.CheckedChanged + + Me.tlpGrowStyle = TableLayoutPanelGrowStyle.AddRows + + End Sub + + Private Sub growStyleAddColumnBtn_CheckedChanged( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles growStyleAddColumnBtn.CheckedChanged + + Me.tlpGrowStyle = TableLayoutPanelGrowStyle.AddColumns + + End Sub + + Private Sub testGrowStyleBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles testGrowStyleBtn.Click + + Me.TableLayoutPanel1.GrowStyle = Me.tlpGrowStyle + + Try + + Me.TableLayoutPanel1.Controls.Add(New Button()) + + Catch ex As ArgumentException + + Trace.WriteLine(ex.Message) + + End Try + + End Sub + ' + + ' + Private Sub toggleColumnStylesBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles toggleColumnStylesBtn.Click + + Dim styles As TableLayoutColumnStyleCollection = _ + Me.TableLayoutPanel1.ColumnStyles + + For Each style As ColumnStyle In styles + + If style.SizeType = SizeType.Absolute Then + + style.SizeType = SizeType.AutoSize + + ElseIf style.SizeType = SizeType.AutoSize Then + + style.SizeType = SizeType.Percent + + ' Set the column width to be a percentage + ' of the TableLayoutPanel control's width. + style.Width = 33 + + Else + + ' Set the column width to 50 pixels. + style.SizeType = SizeType.Absolute + style.Width = 50 + + End If + + Next + + End Sub + ' + + ' + Private Sub toggleRowStylesBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles toggleRowStylesBtn.Click + + Dim styles As TableLayoutRowStyleCollection = _ + Me.TableLayoutPanel1.RowStyles + + For Each style As RowStyle In styles + + If style.SizeType = SizeType.Absolute Then + + style.SizeType = SizeType.AutoSize + + ElseIf style.SizeType = SizeType.AutoSize Then + + style.SizeType = SizeType.Percent + + ' Set the row height to be a percentage + ' of the TableLayoutPanel control's height. + style.Height = 33 + + Else + + ' Set the row height to 50 pixels. + style.SizeType = SizeType.Absolute + style.Height = 50 + + End If + + Next + + End Sub + ' + + ' + Private Sub TableLayoutPanel1_PaintCell( _ + ByVal sender As Object, _ + ByVal e As System.Windows.Forms.TableLayoutCellPaintEventArgs) _ + Handles TableLayoutPanel1.CellPaint + + Dim g As Graphics = e.Graphics + + g.FillEllipse( _ + Brushes.ForestGreen, _ + New Rectangle( _ + e.ClipRectangle.X + 2, _ + e.ClipRectangle.Y + 2, _ + e.ClipRectangle.Width - 4, _ + e.ClipRectangle.Height - 4)) + + + + g.DrawRectangle( _ + Pens.Red, _ + New Rectangle( _ + e.ClipRectangle.X + 2, _ + e.ClipRectangle.Y + 2, _ + e.ClipRectangle.Width - 4, _ + e.ClipRectangle.Height - 4)) + + End Sub + ' + + ' + Private Sub toggleSpanBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles toggleSpanBtn.Click + + Dim c As Control = Me.TableLayoutPanel1.GetControlFromPosition(0, 0) + + If c IsNot Nothing Then + + Dim xSpan As Integer = Me.TableLayoutPanel1.GetColumnSpan(c) + Dim ySpan As Integer = Me.TableLayoutPanel1.GetRowSpan(c) + + If xSpan > 1 Then + + xSpan = 1 + ySpan = 1 + + Else + + xSpan = 2 + ySpan = 2 + + End If + + Me.TableLayoutPanel1.SetColumnSpan(c, xSpan) + Me.TableLayoutPanel1.SetRowSpan(c, ySpan) + + End If + + End Sub + ' + + ' + Private Sub toggleMarginsBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles toggleMarginsBtn.Click + + For Each c As Control In Me.TableLayoutPanel1.Controls + + If c.Margin.All > 5 Then + + Dim m As Padding = c.Margin + m.All = 5 + c.Margin = m + + Else + + Dim m As Padding = c.Margin + m.All = 10 + c.Margin = m + + End If + + Next + + End Sub + ' + + ' + Private Sub togglePaddingBtn_Click( _ + ByVal sender As System.Object, _ + ByVal e As System.EventArgs) _ + Handles togglePaddingBtn.Click + + If Me.TableLayoutPanel1.Padding.All > 5 Then + + Dim p As Padding = Me.TableLayoutPanel1.Padding + p.All = 5 + Me.TableLayoutPanel1.Padding = p + + Else + + Dim p As Padding = Me.TableLayoutPanel1.Padding + p.All = 10 + Me.TableLayoutPanel1.Padding = p + + End If + + End Sub + ' + +#Region " Windows Form Designer generated code " + + Public Sub New() + MyBase.New() + + 'This call is required by the Windows Form Designer. + InitializeComponent() + + End Sub + + 'Form overrides dispose to clean up the component list. + Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + End Sub + Friend WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel + Friend WithEvents Button1 As System.Windows.Forms.Button + Friend WithEvents Button2 As System.Windows.Forms.Button + Friend WithEvents Button3 As System.Windows.Forms.Button + Friend WithEvents Button4 As System.Windows.Forms.Button + Friend WithEvents enumerateChildrenBtn As System.Windows.Forms.Button + Friend WithEvents testGrowStyleBtn As System.Windows.Forms.Button + Friend WithEvents getColumnBtn As System.Windows.Forms.Button + Friend WithEvents getcontrolFromPosBtn As System.Windows.Forms.Button + Friend WithEvents getRowBtn As System.Windows.Forms.Button + Friend WithEvents swapControlsBtn As System.Windows.Forms.Button + Friend WithEvents borderStyleNoneRadioBtn As System.Windows.Forms.RadioButton + Friend WithEvents borderStyleOutsetRadioBtn As System.Windows.Forms.RadioButton + Friend WithEvents borderStyleInsetRadioBtn As System.Windows.Forms.RadioButton + Friend WithEvents growStyleNoneBtn As System.Windows.Forms.RadioButton + Friend WithEvents growStyleAddRowBtn As System.Windows.Forms.RadioButton + Friend WithEvents growStyleAddColumnBtn As System.Windows.Forms.RadioButton + Friend WithEvents toggleColumnStylesBtn As System.Windows.Forms.Button + Friend WithEvents DemoTableLayoutPanel1 As DemoTableLayoutPanel + Friend WithEvents Button12 As System.Windows.Forms.Button + Friend WithEvents Button10 As System.Windows.Forms.Button + Friend WithEvents Button11 As System.Windows.Forms.Button + Friend WithEvents toggleRowStylesBtn As System.Windows.Forms.Button + Friend WithEvents toggleSpanBtn As System.Windows.Forms.Button + Friend WithEvents swapRowsBtn As System.Windows.Forms.Button + Friend WithEvents toggleMarginsBtn As System.Windows.Forms.Button + Friend WithEvents togglePaddingBtn As System.Windows.Forms.Button + + '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.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel + Me.Button1 = New System.Windows.Forms.Button + Me.Button2 = New System.Windows.Forms.Button + Me.Button3 = New System.Windows.Forms.Button + Me.Button4 = New System.Windows.Forms.Button + Me.enumerateChildrenBtn = New System.Windows.Forms.Button + Me.testGrowStyleBtn = New System.Windows.Forms.Button + Me.getColumnBtn = New System.Windows.Forms.Button + Me.getcontrolFromPosBtn = New System.Windows.Forms.Button + Me.getRowBtn = New System.Windows.Forms.Button + Me.swapControlsBtn = New System.Windows.Forms.Button + Me.borderStyleNoneRadioBtn = New System.Windows.Forms.RadioButton + Me.borderStyleOutsetRadioBtn = New System.Windows.Forms.RadioButton + Me.borderStyleInsetRadioBtn = New System.Windows.Forms.RadioButton + Me.growStyleNoneBtn = New System.Windows.Forms.RadioButton + Me.growStyleAddRowBtn = New System.Windows.Forms.RadioButton + Me.growStyleAddColumnBtn = New System.Windows.Forms.RadioButton + Me.toggleColumnStylesBtn = New System.Windows.Forms.Button + Me.DemoTableLayoutPanel1 = New DemoTableLayoutPanel + Me.Button12 = New System.Windows.Forms.Button + Me.Button10 = New System.Windows.Forms.Button + Me.Button11 = New System.Windows.Forms.Button + Me.toggleRowStylesBtn = New System.Windows.Forms.Button + Me.toggleSpanBtn = New System.Windows.Forms.Button + Me.swapRowsBtn = New System.Windows.Forms.Button + Me.toggleMarginsBtn = New System.Windows.Forms.Button + Me.togglePaddingBtn = New System.Windows.Forms.Button + Me.TableLayoutPanel1.SuspendLayout() + Me.DemoTableLayoutPanel1.SuspendLayout() + Me.SuspendLayout() + ' + 'TableLayoutPanel1 + ' + Me.TableLayoutPanel1.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.OutsetDouble + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle) + Me.TableLayoutPanel1.Controls.Add(Me.Button1, 0, 0) + Me.TableLayoutPanel1.Controls.Add(Me.Button2, 1, 0) + Me.TableLayoutPanel1.Controls.Add(Me.Button3, 0, 0) + Me.TableLayoutPanel1.Controls.Add(Me.Button4, 0, 0) + Me.TableLayoutPanel1.Location = New System.Drawing.Point(123, 24) + Me.TableLayoutPanel1.Name = "TableLayoutPanel1" + Me.TableLayoutPanel1.RowCount = 4 + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle) + Me.TableLayoutPanel1.Size = New System.Drawing.Size(286, 230) + Me.TableLayoutPanel1.TabIndex = 0 + ' + 'Button1 + ' + Me.Button1.Anchor = System.Windows.Forms.AnchorStyles.None + Me.Button1.Location = New System.Drawing.Point(105, 77) + Me.Button1.Name = "Button1" + Me.Button1.TabIndex = 1 + Me.Button1.Text = "Button1" + ' + 'Button2 + ' + Me.Button2.Anchor = System.Windows.Forms.AnchorStyles.None + Me.Button2.Location = New System.Drawing.Point(105, 155) + Me.Button2.Name = "Button2" + Me.Button2.TabIndex = 2 + Me.Button2.Text = "Button2" + ' + 'Button3 + ' + Me.Button3.Anchor = System.Windows.Forms.AnchorStyles.None + Me.Button3.Location = New System.Drawing.Point(105, 6) + Me.Button3.Name = "Button3" + Me.Button3.TabIndex = 3 + Me.Button3.Text = "Button3" + ' + 'Button4 + ' + Me.Button4.Anchor = System.Windows.Forms.AnchorStyles.None + Me.TableLayoutPanel1.SetColumnSpan(Me.Button4, 3) + Me.Button4.Location = New System.Drawing.Point(26, 38) + Me.Button4.Name = "Button4" + Me.Button4.Size = New System.Drawing.Size(234, 30) + Me.Button4.TabIndex = 4 + Me.Button4.Text = "Button4" + ' + 'enumerateChildrenBtn + ' + Me.enumerateChildrenBtn.AutoSize = True + Me.enumerateChildrenBtn.Location = New System.Drawing.Point(629, 274) + Me.enumerateChildrenBtn.Name = "enumerateChildrenBtn" + Me.enumerateChildrenBtn.Size = New System.Drawing.Size(105, 23) + Me.enumerateChildrenBtn.TabIndex = 1 + Me.enumerateChildrenBtn.Text = "Enumerate Children" + ' + 'testGrowStyleBtn + ' + Me.testGrowStyleBtn.AutoSize = True + Me.testGrowStyleBtn.Location = New System.Drawing.Point(67, 274) + Me.testGrowStyleBtn.Name = "testGrowStyleBtn" + Me.testGrowStyleBtn.Size = New System.Drawing.Size(88, 23) + Me.testGrowStyleBtn.TabIndex = 2 + Me.testGrowStyleBtn.Text = "Test GrowStyle" + ' + 'getColumnBtn + ' + Me.getColumnBtn.Location = New System.Drawing.Point(165, 274) + Me.getColumnBtn.Name = "getColumnBtn" + Me.getColumnBtn.TabIndex = 3 + Me.getColumnBtn.Text = "GetColumn" + ' + 'getcontrolFromPosBtn + ' + Me.getcontrolFromPosBtn.AutoSize = True + Me.getcontrolFromPosBtn.Location = New System.Drawing.Point(329, 274) + Me.getcontrolFromPosBtn.Name = "getcontrolFromPosBtn" + Me.getcontrolFromPosBtn.Size = New System.Drawing.Size(123, 23) + Me.getcontrolFromPosBtn.TabIndex = 4 + Me.getcontrolFromPosBtn.Text = "GetControlFromPosition" + ' + 'getRowBtn + ' + Me.getRowBtn.Location = New System.Drawing.Point(247, 274) + Me.getRowBtn.Name = "getRowBtn" + Me.getRowBtn.TabIndex = 5 + Me.getRowBtn.Text = "GetRow" + ' + 'swapControlsBtn + ' + Me.swapControlsBtn.AutoSize = True + Me.swapControlsBtn.Location = New System.Drawing.Point(459, 274) + Me.swapControlsBtn.Name = "swapControlsBtn" + Me.swapControlsBtn.Size = New System.Drawing.Size(81, 23) + Me.swapControlsBtn.TabIndex = 6 + Me.swapControlsBtn.Text = "Swap Controls" + ' + 'borderStyleNoneRadioBtn + ' + Me.borderStyleNoneRadioBtn.Location = New System.Drawing.Point(35, 26) + Me.borderStyleNoneRadioBtn.Name = "borderStyleNoneRadioBtn" + Me.borderStyleNoneRadioBtn.Size = New System.Drawing.Size(52, 30) + Me.borderStyleNoneRadioBtn.TabIndex = 8 + Me.borderStyleNoneRadioBtn.Text = "None" + ' + 'borderStyleOutsetRadioBtn + ' + Me.borderStyleOutsetRadioBtn.AutoSize = True + Me.borderStyleOutsetRadioBtn.Location = New System.Drawing.Point(35, 62) + Me.borderStyleOutsetRadioBtn.Name = "borderStyleOutsetRadioBtn" + Me.borderStyleOutsetRadioBtn.Size = New System.Drawing.Size(52, 25) + Me.borderStyleOutsetRadioBtn.TabIndex = 9 + Me.borderStyleOutsetRadioBtn.Text = "Outset" + ' + 'borderStyleInsetRadioBtn + ' + Me.borderStyleInsetRadioBtn.Location = New System.Drawing.Point(35, 92) + Me.borderStyleInsetRadioBtn.Name = "borderStyleInsetRadioBtn" + Me.borderStyleInsetRadioBtn.Size = New System.Drawing.Size(52, 25) + Me.borderStyleInsetRadioBtn.TabIndex = 10 + Me.borderStyleInsetRadioBtn.Text = "Inset" + ' + 'growStyleNoneBtn + ' + Me.growStyleNoneBtn.AutoSize = True + Me.growStyleNoneBtn.Location = New System.Drawing.Point(67, 304) + Me.growStyleNoneBtn.Name = "growStyleNoneBtn" + Me.growStyleNoneBtn.TabIndex = 13 + Me.growStyleNoneBtn.Text = "Fixed" + ' + 'growStyleAddRowBtn + ' + Me.growStyleAddRowBtn.AutoSize = True + Me.growStyleAddRowBtn.Location = New System.Drawing.Point(67, 335) + Me.growStyleAddRowBtn.Name = "growStyleAddRowBtn" + Me.growStyleAddRowBtn.TabIndex = 14 + Me.growStyleAddRowBtn.Text = "Add Rows" + ' + 'growStyleAddColumnBtn + ' + Me.growStyleAddColumnBtn.AutoSize = True + Me.growStyleAddColumnBtn.Location = New System.Drawing.Point(67, 366) + Me.growStyleAddColumnBtn.Name = "growStyleAddColumnBtn" + Me.growStyleAddColumnBtn.TabIndex = 15 + Me.growStyleAddColumnBtn.Text = "Add Columns" + ' + 'toggleColumnStylesBtn + ' + Me.toggleColumnStylesBtn.Location = New System.Drawing.Point(69, 397) + Me.toggleColumnStylesBtn.Name = "toggleColumnStylesBtn" + Me.toggleColumnStylesBtn.Size = New System.Drawing.Size(118, 24) + Me.toggleColumnStylesBtn.TabIndex = 16 + Me.toggleColumnStylesBtn.Text = "Toggle ColumnStyles" + ' + 'DemoTableLayoutPanel1 + ' + Me.DemoTableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!)) + Me.DemoTableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!)) + Me.DemoTableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!)) + Me.DemoTableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100.0!)) + Me.DemoTableLayoutPanel1.Controls.Add(Me.Button12) + Me.DemoTableLayoutPanel1.Controls.Add(Me.Button10, 0, 1) + Me.DemoTableLayoutPanel1.Controls.Add(Me.Button11, 1, 1) + Me.DemoTableLayoutPanel1.Location = New System.Drawing.Point(446, 24) + Me.DemoTableLayoutPanel1.Name = "DemoTableLayoutPanel1" + Me.DemoTableLayoutPanel1.RowCount = 2 + Me.DemoTableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50.0!)) + Me.DemoTableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50.0!)) + Me.DemoTableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50.0!)) + Me.DemoTableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50.0!)) + Me.DemoTableLayoutPanel1.Size = New System.Drawing.Size(256, 230) + Me.DemoTableLayoutPanel1.TabIndex = 11 + ' + 'Button12 + ' + Me.Button12.Anchor = System.Windows.Forms.AnchorStyles.None + Me.Button12.Location = New System.Drawing.Point(90, 13) + Me.Button12.Name = "Button12" + Me.Button12.TabIndex = 9 + Me.Button12.Text = "Button12" + ' + 'Button10 + ' + Me.Button10.Anchor = System.Windows.Forms.AnchorStyles.None + Me.Button10.Location = New System.Drawing.Point(90, 63) + Me.Button10.Name = "Button10" + Me.Button10.TabIndex = 12 + Me.Button10.Text = "Button10" + ' + 'Button11 + ' + Me.Button11.Anchor = System.Windows.Forms.AnchorStyles.None + Me.Button11.Location = New System.Drawing.Point(90, 153) + Me.Button11.Name = "Button11" + Me.Button11.TabIndex = 8 + Me.Button11.Text = "Button11" + ' + 'toggleRowStylesBtn + ' + Me.toggleRowStylesBtn.Location = New System.Drawing.Point(67, 440) + Me.toggleRowStylesBtn.Name = "toggleRowStylesBtn" + Me.toggleRowStylesBtn.Size = New System.Drawing.Size(120, 22) + Me.toggleRowStylesBtn.TabIndex = 17 + Me.toggleRowStylesBtn.Text = "Toggle RowStyles" + ' + 'toggleSpanBtn + ' + Me.toggleSpanBtn.Location = New System.Drawing.Point(247, 398) + Me.toggleSpanBtn.Name = "toggleSpanBtn" + Me.toggleSpanBtn.TabIndex = 18 + Me.toggleSpanBtn.Text = "Toggle Span" + ' + 'swapRowsBtn + ' + Me.swapRowsBtn.Location = New System.Drawing.Point(458, 305) + Me.swapRowsBtn.Name = "swapRowsBtn" + Me.swapRowsBtn.Size = New System.Drawing.Size(82, 23) + Me.swapRowsBtn.TabIndex = 19 + Me.swapRowsBtn.Text = "Swap Rows" + ' + 'toggleMarginsBtn + ' + Me.toggleMarginsBtn.Location = New System.Drawing.Point(328, 397) + Me.toggleMarginsBtn.Name = "toggleMarginsBtn" + Me.toggleMarginsBtn.Size = New System.Drawing.Size(93, 24) + Me.toggleMarginsBtn.TabIndex = 20 + Me.toggleMarginsBtn.Text = "Toggle Margins" + ' + 'togglePaddingBtn + ' + Me.togglePaddingBtn.Location = New System.Drawing.Point(458, 396) + Me.togglePaddingBtn.Name = "togglePaddingBtn" + Me.togglePaddingBtn.Size = New System.Drawing.Size(94, 23) + Me.togglePaddingBtn.TabIndex = 21 + Me.togglePaddingBtn.Text = "Toggle Padding" + ' + 'Form1 + ' + Me.ClientSize = New System.Drawing.Size(773, 489) + Me.Controls.Add(Me.togglePaddingBtn) + Me.Controls.Add(Me.toggleMarginsBtn) + Me.Controls.Add(Me.swapRowsBtn) + Me.Controls.Add(Me.toggleSpanBtn) + Me.Controls.Add(Me.toggleRowStylesBtn) + Me.Controls.Add(Me.toggleColumnStylesBtn) + Me.Controls.Add(Me.growStyleAddColumnBtn) + Me.Controls.Add(Me.growStyleAddRowBtn) + Me.Controls.Add(Me.growStyleNoneBtn) + Me.Controls.Add(Me.DemoTableLayoutPanel1) + Me.Controls.Add(Me.borderStyleInsetRadioBtn) + Me.Controls.Add(Me.borderStyleOutsetRadioBtn) + Me.Controls.Add(Me.borderStyleNoneRadioBtn) + Me.Controls.Add(Me.swapControlsBtn) + Me.Controls.Add(Me.getRowBtn) + Me.Controls.Add(Me.getcontrolFromPosBtn) + Me.Controls.Add(Me.getColumnBtn) + Me.Controls.Add(Me.testGrowStyleBtn) + Me.Controls.Add(Me.enumerateChildrenBtn) + Me.Controls.Add(Me.TableLayoutPanel1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.TableLayoutPanel1.ResumeLayout(False) + Me.DemoTableLayoutPanel1.ResumeLayout(False) + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + Friend Shared ReadOnly Property GetInstance() As Form1 + Get + If m_DefaultInstance Is Nothing OrElse m_DefaultInstance.IsDisposed() Then + SyncLock m_SyncObject + If m_DefaultInstance Is Nothing OrElse m_DefaultInstance.IsDisposed() Then + m_DefaultInstance = New Form1 + End If + End SyncLock + End If + Return m_DefaultInstance + End Get + End Property + + Private Shared m_DefaultInstance As Form1 + Private Shared m_SyncObject As New Object +#End Region + + + +End Class + +' +Public Class DemoTableLayoutPanel + Inherits TableLayoutPanel + + Protected Overrides Sub OnCellPaint( _ + ByVal e As System.Windows.Forms.TableLayoutCellPaintEventArgs) + + MyBase.OnCellPaint(e) + + Dim c As Control = Me.GetControlFromPosition(e.Column, e.Row) + + If c IsNot Nothing Then + Dim g As Graphics = e.Graphics + + g.DrawRectangle( _ + Pens.Red, _ + e.CellBounds.Location.X + 1, _ + e.CellBounds.Location.Y + 1, _ + e.CellBounds.Width - 2, _ + e.CellBounds.Height - 2) + + g.FillRectangle( _ + Brushes.Blue, _ + e.CellBounds.Location.X + 1, _ + e.CellBounds.Location.Y + 1, _ + e.CellBounds.Width - 2, _ + e.CellBounds.Height - 2) + End If + + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/VB/Form1.vb new file mode 100644 index 0000000000..959875e3f7 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.TextRendererExamples/VB/Form1.vb @@ -0,0 +1,181 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + + + +Public Class Form1 + Inherits Form + + Public Sub New() + InitializeComponent() + + End Sub + + + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + + End Sub + + ' + Private Sub MeasureText1(ByVal e As PaintEventArgs) + Dim text1 As String = "Measure this text" + Dim arialBold As New Font("Arial", 12.0F) + Dim textSize As Size = TextRenderer.MeasureText(text1, arialBold) + TextRenderer.DrawText(e.Graphics, text1, arialBold, _ + New Rectangle(New Point(10, 10), textSize), Color.Red) + + End Sub + + ' + ' + Private Sub MeasureText2(ByVal e As PaintEventArgs) + Dim text1 As String = "How big is this text?" + Dim arialBold As New Font("Arial", 12.0F) + + ' Indicate a size taller than it is wide. + Dim proposedSize As New Size(40, 60) + + Dim textSize As Size = TextRenderer.MeasureText(text1, _ + arialBold, proposedSize, TextFormatFlags.WordBreak) + TextRenderer.DrawText(e.Graphics, text1, arialBold, _ + New Rectangle(New Point(10, 10), textSize), Color.Red, _ + TextFormatFlags.WordBreak) + + End Sub + + ' + ' + Private Sub RenderText1(ByVal e As PaintEventArgs) + TextRenderer.DrawText(e.Graphics, "Regular Text", _ + Me.Font, New Point(10, 10), SystemColors.ControlText) + + End Sub + + + ' + ' + Private Sub RenderText2(ByVal e As PaintEventArgs) + TextRenderer.DrawText(e.Graphics, "Regular Text", _ + Me.Font, New Rectangle(10, 10, 100, 100), _ + SystemColors.ControlText) + + End Sub + + + ' + ' + Private Sub RenderText3(ByVal e As PaintEventArgs) + TextRenderer.DrawText(e.Graphics, "Regular Text", Me.Font, _ + New Point(10, 10), Color.Red, Color.PowderBlue) + + End Sub + + ' + ' + Private Sub RenderText4(ByVal e As PaintEventArgs) + TextRenderer.DrawText(e.Graphics, "Regular Text.", _ + Me.Font, New Rectangle(10, 10, 70, 70), _ + SystemColors.ControlText, SystemColors.ControlDark) + + End Sub + + ' + ' + Private Sub RenderText5(ByVal e As PaintEventArgs) + TextRenderer.DrawText(e.Graphics, "Some text.", _ + Me.Font, New Point(10, 10), SystemColors.ControlText, _ + TextFormatFlags.Bottom) + + End Sub + + ' + ' + Private Sub RenderText6(ByVal e As PaintEventArgs) + Dim flags As TextFormatFlags = TextFormatFlags.Bottom Or _ + TextFormatFlags.EndEllipsis + TextRenderer.DrawText(e.Graphics, _ + "This is some text that will be clipped at the end.", _ + Me.Font, New Rectangle(10, 10, 100, 50), SystemColors.ControlText, flags) + + End Sub + + ' + ' + Private Sub RenderText7(ByVal e As PaintEventArgs) + TextRenderer.DrawText(e.Graphics, "This is some text.", _ + Me.Font, New Point(10, 10), Color.White, Color.SteelBlue, _ + TextFormatFlags.Default) + + End Sub + + ' + ' + Private Sub RenderText8(ByVal e As PaintEventArgs) + Dim flags As TextFormatFlags = _ + TextFormatFlags.Bottom Or TextFormatFlags.WordBreak + TextRenderer.DrawText(e.Graphics, _ + "This is some text that will display on multiple lines.", _ + Me.Font, New Rectangle(10, 10, 100, 50), _ + SystemColors.ControlText, SystemColors.ControlDark, flags) + + End Sub + + + ' + Private Sub InitializeComponent() + Me.SuspendLayout() + ' + ' Form1 + ' + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Name = "Form1" + Me.ResumeLayout(False) + + End Sub + + + Private Sub Form1_Paint(ByVal sender As Object, _ + ByVal e As PaintEventArgs) Handles MyBase.Paint + MeasureText2(e) + + End Sub + + ' + Private Sub DrawALineOfText(ByVal e As PaintEventArgs) + ' Declare strings to render on the form. + Dim stringsToPaint() As String = {"Tail", "Spin", " Toys"} + + ' Declare fonts for rendering the strings. + Dim fonts() As Font = {New Font("Arial", 14, FontStyle.Regular), _ + New Font("Arial", 14, FontStyle.Italic), _ + New Font("Arial", 14, FontStyle.Regular)} + + Dim startPoint As New Point(10, 10) + + ' Set TextFormatFlags to no padding so strings are drawn together. + Dim flags As TextFormatFlags = TextFormatFlags.NoPadding + + ' Declare a proposed size with dimensions set to the maximum integer value. + Dim proposedSize As Size = New Size(Integer.MaxValue, Integer.MaxValue) + + ' Measure each string with its font and NoPadding value and draw it to the form. + For i As Integer = 0 To stringsToPaint.Length - 1 + Dim size As Size = TextRenderer.MeasureText(e.Graphics, _ + stringsToPaint(i), fonts(i), proposedSize, flags) + Dim rect As Rectangle = New Rectangle(startPoint, size) + TextRenderer.DrawText(e.Graphics, stringsToPaint(i), fonts(i), _ + startPoint, Color.Black, flags) + startPoint.X += size.Width + Next + End Sub + ' +End Class + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/VB/GridStrip.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/VB/GridStrip.vb new file mode 100644 index 0000000000..e53774b089 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.GridStrip/VB/GridStrip.vb @@ -0,0 +1,485 @@ + ' +Imports System.Collections.Generic +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Drawing.Imaging +Imports System.Text +Imports System.Windows.Forms +Imports System.Windows.Forms.Layout + + +' +' The following class implements a sliding-tile puzzle. +' The GridStrip control is a custom ToolStrip that arranges +' its ToolStripButton controls in a grid layout. There is +' one empty cell, into which the user can slide an adjacent +' tile with a drag-and-drop operation. Tiles that are eligible +' for moving are highlighted. +Public Class GridStrip + Inherits ToolStrip + + ' The button that is the drag source. + Private dragButton As ToolStripButton = Nothing + + ' Settings for the ToolStrip control's TableLayoutPanel. + ' This provides access to the cell position of each + ' ToolStripButton. + Private tableSettings As TableLayoutSettings = Nothing + + ' The empty cell. ToolStripButton controls that are + ' adjacent to this button can be moved to this button's + ' cell position. + Private emptyCellButton As ToolStripButton = Nothing + + ' The dimensions of each tile. A tile is represented + ' by a ToolStripButton controls. + Private tileSize As New Size(128, 128) + + ' The number of rows in the GridStrip control. + Private rows As Integer = 5 + + ' The number of columns in the GridStrip control. + Private columns As Integer = 5 + + ' The one-time initialzation behavior is enforced + ' with this field. For more information, see the + ' OnPaint method. + Private firstTime As Boolean = False + + ' This is a required by the Windows Forms designer. + Private components As System.ComponentModel.IContainer + + + ' The default constructor. + Public Sub New() + MyBase.New() + + Me.InitializeComponent() + + Me.InitializeTableLayoutSettings() + End Sub + + ' This property exposes the empty cell to the + ' GridStripRenderer class. + Friend ReadOnly Property EmptyCell() As ToolStripButton + Get + Return Me.emptyCellButton + End Get + End Property + + + ' This utility method initializes the TableLayoutPanel + ' which contains the ToolStripButton controls. + Private Sub InitializeTableLayoutSettings() + + ' Specify the numbers of rows and columns in the GridStrip control. + Me.tableSettings = CType(MyBase.LayoutSettings, TableLayoutSettings) + Me.tableSettings.ColumnCount = Me.rows + Me.tableSettings.RowCount = Me.columns + + ' Create a dummy bitmap with the dimensions of each tile. + ' The GridStrip control sizes itself based on these dimensions. + Dim b As New Bitmap(tileSize.Width, tileSize.Height) + + ' Populate the GridStrip control with ToolStripButton controls. + Dim i As Integer + For i = 0 To (Me.tableSettings.ColumnCount) - 1 + Dim j As Integer + For j = 0 To (Me.tableSettings.RowCount) - 1 + ' Create a new ToolStripButton control. + Dim btn As New ToolStripButton() + btn.DisplayStyle = ToolStripItemDisplayStyle.Image + btn.Image = b + btn.ImageAlign = ContentAlignment.MiddleCenter + btn.ImageScaling = ToolStripItemImageScaling.None + btn.Margin = System.Windows.Forms.Padding.Empty + btn.Padding = System.Windows.Forms.Padding.Empty + + ' Add the new ToolStripButton control to the GridStrip. + Me.Items.Add(btn) + + ' Set the cell position of the ToolStripButton control. + Dim cellPos As New TableLayoutPanelCellPosition(i, j) + Me.tableSettings.SetCellPosition(btn, cellPos) + + ' If this is the ToolStripButton control at cell (0,0), + ' assign it as the empty cell button. + If i = 0 AndAlso j = 0 Then + btn.Text = "Empty Cell" + btn.Image = b + Me.emptyCellButton = btn + End If + Next j + Next i + End Sub + + + ' This method defines the Paint event behavior. + ' The GridStripRenderer requires that the GridStrip + ' be fully layed out when it is renders, so this + ' initialization code cannot be placed in the + ' GridStrip constructor. By the time the Paint + ' event is raised, the control layout has been + ' completed, so the GridStripRenderer can paint + ' correctly. This one-time initialization is + ' implemented with the firstTime field. + Protected Overrides Sub OnPaint(e As PaintEventArgs) + MyBase.OnPaint(e) + + If Not Me.firstTime Then + Me.Renderer = New GridStripRenderer() + + ' Comment this line to see the unscrambled image. + Me.ScrambleButtons() + Me.firstTime = True + End If + End Sub + + + ' This utility method changes the ToolStripButton control + ' positions in the TableLayoutPanel. This scrambles the + ' buttons to initialize the puzzle. + Private Sub ScrambleButtons() + Dim i As Integer = 0 + Dim lastElement As Integer = Me.Items.Count - 1 + + While i <> lastElement AndAlso lastElement - i > 1 + Dim pos1 As TableLayoutPanelCellPosition = _ + Me.tableSettings.GetCellPosition(Me.Items(i)) + + Dim pos2 As TableLayoutPanelCellPosition = _ + Me.tableSettings.GetCellPosition(Me.Items(lastElement)) + + Me.tableSettings.SetCellPosition(Me.Items(i), pos2) + i += 1 + + Me.tableSettings.SetCellPosition(Me.Items(lastElement), pos1) + lastElement -= 1 + End While + End Sub + + + ' This method defines the MouseDown event behavior. + ' If the user has clicked on a valid drag source, + ' the drag operation starts. + Protected Overrides Sub OnMouseDown(mea As MouseEventArgs) + MyBase.OnMouseDown(mea) + + Dim btn As ToolStripButton = CType(Me.GetItemAt(mea.Location), ToolStripButton) + + If (btn IsNot Nothing) Then + If Me.IsValidDragSource(btn) Then + Me.dragButton = btn + End If + End If + End Sub + + + ' This method defines the MouseMove event behavior. + Protected Overrides Sub OnMouseMove(mea As MouseEventArgs) + MyBase.OnMouseMove(mea) + + ' Is a drag operation pending? + If (Me.dragButton IsNot Nothing) Then + ' A drag operation is pending. Call DoDragDrop to + ' determine the disposition of the operation. + Dim dropEffect As DragDropEffects = Me.DoDragDrop(New DataObject(Me.dragButton), DragDropEffects.Move) + End If + End Sub + + ' + ' This method defines the DragOver event behavior. + Protected Overrides Sub OnDragOver(dea As DragEventArgs) + MyBase.OnDragOver(dea) + + ' Get the ToolStripButton control + ' at the given mouse position. + Dim p As New Point(dea.X, dea.Y) + Dim item As ToolStripButton = CType(Me.GetItemAt(Me.PointToClient(p)), ToolStripButton) + + + ' If the ToolStripButton control is the empty cell, + ' indicate that the move operation is valid. + If item Is Me.emptyCellButton Then + ' Set the drag operation to indicate a valid move. + dea.Effect = DragDropEffects.Move + End If + End Sub + ' + + + ' This method defines the DragDrop event behavior. + Protected Overrides Sub OnDragDrop(dea As DragEventArgs) + MyBase.OnDragDrop(dea) + + ' Did a valid move operation occur? + If dea.Effect = DragDropEffects.Move Then + ' The move operation is valid. Adjust the state + ' of the GridStrip control's TableLayoutPanel, + ' by swapping the positions of the source button + ' and the empty cell button. + ' Get the cell of the control to move. + Dim sourcePos As TableLayoutPanelCellPosition = tableSettings.GetCellPosition(Me.dragButton) + + ' Get the cell of the emptyCellButton. + Dim dropPos As TableLayoutPanelCellPosition = tableSettings.GetCellPosition(Me.emptyCellButton) + + ' Move the control to the empty cell. + tableSettings.SetCellPosition(Me.dragButton, dropPos) + + ' Set the position of the empty cell to + ' that of the previously occupied cell. + tableSettings.SetCellPosition(Me.emptyCellButton, sourcePos) + + ' Reset the drag operation. + Me.dragButton = Nothing + End If + End Sub + + + ' This method defines the DragLeave event behavior. + ' If the mouse leaves the client area of the GridStrip + ' control, the drag operation is canceled. + Protected Overrides Sub OnDragLeave(e As EventArgs) + MyBase.OnDragLeave(e) + + ' Reset the drag operation. + Me.dragButton = Nothing + End Sub + + + ' This method defines the ueryContinueDrag event behavior. + ' If the mouse leaves the client area of the GridStrip + ' control, the drag operation is canceled. + Protected Overrides Sub OnQueryContinueDrag(qcdevent As QueryContinueDragEventArgs) + MyBase.OnQueryContinueDrag(qcdevent) + + ' Get the current mouse position, in screen coordinates. + Dim mousePos As Point = Me.PointToClient(Control.MousePosition) + + ' If the mouse position is outside the GridStrip control's + ' client area, cancel the drag operation. Be sure to + ' transform the mouse's screen coordinates to client coordinates. + If Not Me.ClientRectangle.Contains(mousePos) Then + qcdevent.Action = DragAction.Cancel + End If + End Sub + + + ' This utility method determines if a button + ' is positioned relative to the empty cell + ' such that it can be dragged into the empty cell. + Overloads Private Function IsValidDragSource(b As ToolStripButton) As Boolean + Dim sourcePos As TableLayoutPanelCellPosition = tableSettings.GetCellPosition(b) + + Dim emptyPos As TableLayoutPanelCellPosition = tableSettings.GetCellPosition(Me.emptyCellButton) + + Return IsValidDragSource(sourcePos, emptyPos) + + End Function + + + ' This utility method determines if a cell position + ' is adjacent to the empty cell. + Friend Overloads Shared Function IsValidDragSource( _ + ByVal sourcePos As TableLayoutPanelCellPosition, _ + ByVal emptyPos As TableLayoutPanelCellPosition) As Boolean + Dim returnValue As Boolean = False + + ' A cell is considered to be a valid drag source if it + ' is adjacent to the empty cell. Cells that are positioned + ' on a diagonal are not valid. + If sourcePos.Column = emptyPos.Column - 1 AndAlso sourcePos.Row = emptyPos.Row OrElse _ + (sourcePos.Column = emptyPos.Column + 1 AndAlso sourcePos.Row = emptyPos.Row) OrElse _ + (sourcePos.Column = emptyPos.Column AndAlso sourcePos.Row = emptyPos.Row - 1) OrElse _ + (sourcePos.Column = emptyPos.Column AndAlso sourcePos.Row = emptyPos.Row + 1) Then + returnValue = True + End If + + Return returnValue + End Function + ' + + ' + ' This class implements a custom ToolStripRenderer for the + ' GridStrip control. It customizes three aspects of the + ' GridStrip control's appearance: GridStrip border, + ' ToolStripButton border, and ToolStripButton image. + Friend Class GridStripRenderer + Inherits ToolStripRenderer + + ' The style of the empty cell's text. + Private Shared style As New StringFormat() + + ' The thickness (width or height) of a + ' ToolStripButton control's border. + Private Shared borderThickness As Integer = 2 + + ' The main bitmap that is the source for the + ' subimagesthat are assigned to individual + ' ToolStripButton controls. + Private bmp As Bitmap = Nothing + + ' The brush that paints the background of + ' the GridStrip control. + Private backgroundBrush As Brush = Nothing + + + ' This is the static constructor. It initializes the + ' StringFormat for drawing the text in the empty cell. + Shared Sub New() + style.Alignment = StringAlignment.Center + style.LineAlignment = StringAlignment.Center + End Sub + + ' This method initializes the GridStripRenderer by + ' creating the image that is used as the source for + ' the individual button images. + Protected Overrides Sub Initialize(ts As ToolStrip) + MyBase.Initialize(ts) + + Me.InitializeBitmap(ts) + End Sub + + ' + ' This method initializes an individual ToolStripButton + ' control. It copies a subimage from the GridStripRenderer's + ' main image, according to the position and size of + ' the ToolStripButton. + Protected Overrides Sub InitializeItem(item As ToolStripItem) + MyBase.InitializeItem(item) + + Dim gs As GridStrip = item.Owner + + ' The empty cell does not receive a subimage. + If ((TypeOf (item) Is ToolStripButton) And _ + (item IsNot gs.EmptyCell)) Then + ' Copy the subimage from the appropriate + ' part of the main image. + Dim subImage As Bitmap = bmp.Clone(item.Bounds, PixelFormat.Undefined) + + ' Assign the subimage to the ToolStripButton + ' control's Image property. + item.Image = subImage + End If + End Sub + ' + + ' This utility method creates the main image that + ' is the source for the subimages of the individual + ' ToolStripButton controls. + Private Sub InitializeBitmap(toolStrip As ToolStrip) + ' Create the main bitmap, into which the image is drawn. + Me.bmp = New Bitmap(toolStrip.Size.Width, toolStrip.Size.Height) + + ' Draw a fancy pattern. This could be any image or drawing. + Dim g As Graphics = Graphics.FromImage(bmp) + Try + ' Draw smoothed lines. + g.SmoothingMode = SmoothingMode.AntiAlias + + ' Draw the image. In this case, it is + ' a number of concentric ellipses. + Dim i As Integer + For i = 0 To toolStrip.Size.Width - 8 Step 8 + g.DrawEllipse(Pens.Blue, 0, 0, i, i) + Next i + Finally + g.Dispose() + End Try + End Sub + + ' + ' This method draws a border around the GridStrip control. + Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs) + MyBase.OnRenderToolStripBorder(e) + + ControlPaint.DrawFocusRectangle(e.Graphics, e.AffectedBounds, SystemColors.ControlDarkDark, SystemColors.ControlDarkDark) + End Sub + ' + + ' + ' This method renders the GridStrip control's background. + Protected Overrides Sub OnRenderToolStripBackground(e As ToolStripRenderEventArgs) + MyBase.OnRenderToolStripBackground(e) + + ' This late initialization is a workaround. The gradient + ' depends on the bounds of the GridStrip control. The bounds + ' are dependent on the layout engine, which hasn't fully + ' performed layout by the time the Initialize method runs. + If Me.backgroundBrush Is Nothing Then + Me.backgroundBrush = New LinearGradientBrush(e.ToolStrip.ClientRectangle, SystemColors.ControlLightLight, SystemColors.ControlDark, 90, True) + End If + + ' Paint the GridStrip control's background. + e.Graphics.FillRectangle(Me.backgroundBrush, e.AffectedBounds) + End Sub + ' + + ' + ' This method draws a border around the button's image. If the background + ' to be rendered belongs to the empty cell, a string is drawn. Otherwise, + ' a border is drawn at the edges of the button. + Protected Overrides Sub OnRenderButtonBackground(e As ToolStripItemRenderEventArgs) + MyBase.OnRenderButtonBackground(e) + + ' Define some local variables for convenience. + Dim g As Graphics = e.Graphics + Dim gs As GridStrip = e.ToolStrip + Dim gsb As ToolStripButton = e.Item + + ' Calculate the rectangle around which the border is painted. + Dim imageRectangle As New Rectangle(borderThickness, borderThickness, e.Item.Width - 2 * borderThickness, e.Item.Height - 2 * borderThickness) + + ' If rendering the empty cell background, draw an + ' explanatory string, centered in the ToolStripButton. + If gsb Is gs.EmptyCell Then + e.Graphics.DrawString("Drag to here", gsb.Font, SystemBrushes.ControlDarkDark, imageRectangle, style) + Else + ' If the button can be a drag source, paint its border red. + ' otherwise, paint its border a dark color. + Dim b As Brush = IIf(gs.IsValidDragSource(gsb), Brushes.Red, SystemBrushes.ControlDarkDark) + + ' Draw the top segment of the border. + Dim borderSegment As New Rectangle(0, 0, e.Item.Width, imageRectangle.Top) + g.FillRectangle(b, borderSegment) + + ' Draw the right segment. + borderSegment = New Rectangle(imageRectangle.Right, 0, e.Item.Bounds.Right - imageRectangle.Right, imageRectangle.Bottom) + g.FillRectangle(b, borderSegment) + + ' Draw the left segment. + borderSegment = New Rectangle(0, 0, imageRectangle.Left, e.Item.Height) + g.FillRectangle(b, borderSegment) + + ' Draw the bottom segment. + borderSegment = New Rectangle(0, imageRectangle.Bottom, e.Item.Width, e.Item.Bounds.Bottom - imageRectangle.Bottom) + g.FillRectangle(b, borderSegment) + End If + End Sub + End Class + ' + ' + + #Region "Windows Forms Designer generated code" + + + Private Sub InitializeComponent() + Me.components = New System.ComponentModel.Container() + Me.SuspendLayout() + ' + ' GridStrip + ' + Me.AllowDrop = True + Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None + Me.CanOverflow = False + Me.Dock = System.Windows.Forms.DockStyle.None + Me.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden + Me.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Table + Me.ResumeLayout(False) + End Sub + + #End Region + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/VB/Form1.vb new file mode 100644 index 0000000000..1fae681ba3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.MdiForm/VB/Form1.vb @@ -0,0 +1,275 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +' This code example demonstrates an MDI form +' that supports menu merging and moveable +' ToolStrip controls +Public Class Form1 + Inherits Form + Private menuStrip1 As MenuStrip + Private toolStripMenuItem1 As ToolStripMenuItem + Private WithEvents newToolStripMenuItem As ToolStripMenuItem + Private toolStripPanel1 As ToolStripPanel + Private toolStrip1 As ToolStrip + Private toolStripPanel2 As ToolStripPanel + Private toolStrip2 As ToolStrip + Private toolStripPanel3 As ToolStripPanel + Private toolStrip3 As ToolStrip + Private toolStripPanel4 As ToolStripPanel + Private toolStrip4 As ToolStrip + + Private components As System.ComponentModel.IContainer = Nothing + + Public Sub New() + InitializeComponent() + End Sub + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + + ' + ' This method creates a new ChildForm instance + ' and attaches it to the MDI parent form. + Private Sub newToolStripMenuItem_Click( _ + ByVal sender As Object, _ + ByVal e As EventArgs) _ + Handles newToolStripMenuItem.Click + + Dim f As New ChildForm() + f.MdiParent = Me + f.Text = "Form - " + Me.MdiChildren.Length.ToString() + f.Show() + + End Sub + ' + + #Region "Windows Form Designer generated code" + + Private Sub InitializeComponent() + Me.menuStrip1 = New System.Windows.Forms.MenuStrip + Me.toolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem + Me.newToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripPanel1 = New System.Windows.Forms.ToolStripPanel + Me.toolStrip1 = New System.Windows.Forms.ToolStrip + Me.toolStripPanel2 = New System.Windows.Forms.ToolStripPanel + Me.toolStrip2 = New System.Windows.Forms.ToolStrip + Me.toolStripPanel3 = New System.Windows.Forms.ToolStripPanel + Me.toolStrip3 = New System.Windows.Forms.ToolStrip + Me.toolStripPanel4 = New System.Windows.Forms.ToolStripPanel + Me.toolStrip4 = New System.Windows.Forms.ToolStrip + Me.menuStrip1.SuspendLayout() + Me.toolStripPanel1.SuspendLayout() + Me.toolStripPanel2.SuspendLayout() + Me.toolStripPanel3.SuspendLayout() + Me.toolStripPanel4.SuspendLayout() + Me.SuspendLayout() + ' + 'menuStrip1 + ' + Me.menuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.toolStripMenuItem1}) + Me.menuStrip1.Location = New System.Drawing.Point(0, 0) + Me.menuStrip1.MdiWindowListItem = Me.toolStripMenuItem1 + Me.menuStrip1.Name = "menuStrip1" + Me.menuStrip1.Size = New System.Drawing.Size(292, 24) + Me.menuStrip1.TabIndex = 0 + Me.menuStrip1.Text = "menuStrip1" + ' + 'toolStripMenuItem1 + ' + Me.toolStripMenuItem1.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.newToolStripMenuItem}) + Me.toolStripMenuItem1.Name = "toolStripMenuItem1" + Me.toolStripMenuItem1.Size = New System.Drawing.Size(57, 20) + Me.toolStripMenuItem1.Text = "Window" + ' + 'newToolStripMenuItem + ' + Me.newToolStripMenuItem.Name = "newToolStripMenuItem" + Me.newToolStripMenuItem.Size = New System.Drawing.Size(106, 22) + Me.newToolStripMenuItem.Text = "New" + ' + 'toolStripPanel1 + ' + Me.toolStripPanel1.Controls.Add(Me.toolStrip1) + Me.toolStripPanel1.Dock = System.Windows.Forms.DockStyle.Left + Me.toolStripPanel1.Location = New System.Drawing.Point(0, 49) + Me.toolStripPanel1.Name = "toolStripPanel1" + Me.toolStripPanel1.Orientation = System.Windows.Forms.Orientation.Vertical + Me.toolStripPanel1.RowMargin = New System.Windows.Forms.Padding(0, 3, 0, 0) + Me.toolStripPanel1.Size = New System.Drawing.Size(26, 199) + ' + 'toolStrip1 + ' + Me.toolStrip1.Dock = System.Windows.Forms.DockStyle.None + Me.toolStrip1.Location = New System.Drawing.Point(0, 3) + Me.toolStrip1.Name = "toolStrip1" + Me.toolStrip1.Size = New System.Drawing.Size(26, 109) + Me.toolStrip1.TabIndex = 0 + ' + 'toolStripPanel2 + ' + Me.toolStripPanel2.Controls.Add(Me.toolStrip2) + Me.toolStripPanel2.Dock = System.Windows.Forms.DockStyle.Top + Me.toolStripPanel2.Location = New System.Drawing.Point(0, 24) + Me.toolStripPanel2.Name = "toolStripPanel2" + Me.toolStripPanel2.Orientation = System.Windows.Forms.Orientation.Horizontal + Me.toolStripPanel2.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0) + Me.toolStripPanel2.Size = New System.Drawing.Size(292, 25) + ' + 'toolStrip2 + ' + Me.toolStrip2.Dock = System.Windows.Forms.DockStyle.None + Me.toolStrip2.Location = New System.Drawing.Point(3, 0) + Me.toolStrip2.Name = "toolStrip2" + Me.toolStrip2.Size = New System.Drawing.Size(109, 25) + Me.toolStrip2.TabIndex = 0 + ' + 'toolStripPanel3 + ' + Me.toolStripPanel3.Controls.Add(Me.toolStrip3) + Me.toolStripPanel3.Dock = System.Windows.Forms.DockStyle.Right + Me.toolStripPanel3.Location = New System.Drawing.Point(266, 49) + Me.toolStripPanel3.Name = "toolStripPanel3" + Me.toolStripPanel3.Orientation = System.Windows.Forms.Orientation.Vertical + Me.toolStripPanel3.RowMargin = New System.Windows.Forms.Padding(0, 3, 0, 0) + Me.toolStripPanel3.Size = New System.Drawing.Size(26, 199) + ' + 'toolStrip3 + ' + Me.toolStrip3.Dock = System.Windows.Forms.DockStyle.None + Me.toolStrip3.Location = New System.Drawing.Point(0, 3) + Me.toolStrip3.Name = "toolStrip3" + Me.toolStrip3.Size = New System.Drawing.Size(26, 109) + Me.toolStrip3.TabIndex = 0 + ' + 'toolStripPanel4 + ' + Me.toolStripPanel4.Controls.Add(Me.toolStrip4) + Me.toolStripPanel4.Dock = System.Windows.Forms.DockStyle.Bottom + Me.toolStripPanel4.Location = New System.Drawing.Point(0, 248) + Me.toolStripPanel4.Name = "toolStripPanel4" + Me.toolStripPanel4.Orientation = System.Windows.Forms.Orientation.Horizontal + Me.toolStripPanel4.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0) + Me.toolStripPanel4.Size = New System.Drawing.Size(292, 25) + ' + 'toolStrip4 + ' + Me.toolStrip4.Dock = System.Windows.Forms.DockStyle.None + Me.toolStrip4.Location = New System.Drawing.Point(3, 0) + Me.toolStrip4.Name = "toolStrip4" + Me.toolStrip4.Size = New System.Drawing.Size(109, 25) + Me.toolStrip4.TabIndex = 0 + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.toolStripPanel3) + Me.Controls.Add(Me.toolStripPanel1) + Me.Controls.Add(Me.toolStripPanel2) + Me.Controls.Add(Me.menuStrip1) + Me.Controls.Add(Me.toolStripPanel4) + Me.IsMdiContainer = True + Me.MainMenuStrip = Me.menuStrip1 + Me.Name = "Form1" + Me.Text = "Form1" + Me.menuStrip1.ResumeLayout(False) + Me.menuStrip1.PerformLayout() + Me.toolStripPanel1.ResumeLayout(False) + Me.toolStripPanel1.PerformLayout() + Me.toolStripPanel2.ResumeLayout(False) + Me.toolStripPanel2.PerformLayout() + Me.toolStripPanel3.ResumeLayout(False) + Me.toolStripPanel3.PerformLayout() + Me.toolStripPanel4.ResumeLayout(False) + Me.toolStripPanel4.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + #End Region +End Class + + +Public Class ChildForm + Inherits Form + Private menuStrip1 As System.Windows.Forms.MenuStrip + Private toolStripMenuItem1 As System.Windows.Forms.ToolStripMenuItem + Private components As System.ComponentModel.IContainer = Nothing + + + Public Sub New() + InitializeComponent() + End Sub + + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + #Region "Windows Form Designer generated code" + + Private Sub InitializeComponent() + Me.menuStrip1 = New System.Windows.Forms.MenuStrip() + Me.toolStripMenuItem1 = New System.Windows.Forms.ToolStripMenuItem() + Me.menuStrip1.SuspendLayout() + Me.SuspendLayout() + ' + ' menuStrip1 + ' + Me.menuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.toolStripMenuItem1}) + Me.menuStrip1.Location = New System.Drawing.Point(0, 0) + Me.menuStrip1.Name = "menuStrip1" + Me.menuStrip1.Size = New System.Drawing.Size(292, 24) + Me.menuStrip1.TabIndex = 0 + Me.menuStrip1.Text = "menuStrip1" + ' + ' toolStripMenuItem1 + ' + Me.toolStripMenuItem1.Name = "toolStripMenuItem1" + Me.toolStripMenuItem1.Size = New System.Drawing.Size(90, 20) + Me.toolStripMenuItem1.Text = "ChildMenuItem" + ' + ' ChildForm + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(menuStrip1) + Me.MainMenuStrip = Me.menuStrip1 + Me.Name = "ChildForm" + Me.Text = "ChildForm" + Me.menuStrip1.ResumeLayout(False) + Me.menuStrip1.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + End Sub + + #End Region +End Class + + +Public Class Program + + ' + ' The main entry point for the application. + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb new file mode 100644 index 0000000000..b083a3422a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.Misc/VB/Program.vb @@ -0,0 +1,670 @@ + ' +Imports System.Collections.Generic +Imports System.Windows.Forms +Imports System.Drawing +' + +Public Class Program + + ' + ' The main entry point for the application. + ' + _ + Shared Sub Main() + Application.EnableVisualStyles() + + 'Application.Run(New Form1()) + 'Application.Run(New Form2()) + Application.Run(New Form3()) + 'Application.Run(New Form4()) + 'Application.Run(New Form5()) + 'Application.Run(New Form6()) + End Sub +End Class + +' +' This code example demonstrates how to use ToolStripPanel +' controls with a multiple document interface (MDI). +Public Class Form1 + Inherits Form + + Public Sub New() + ' Make the Form an MDI parent. + Me.IsMdiContainer = True + + ' + ' Create ToolStripPanel controls. + Dim tspTop As New ToolStripPanel() + Dim tspBottom As New ToolStripPanel() + Dim tspLeft As New ToolStripPanel() + Dim tspRight As New ToolStripPanel() + + ' Dock the ToolStripPanel controls to the edges of the form. + tspTop.Dock = DockStyle.Top + tspBottom.Dock = DockStyle.Bottom + tspLeft.Dock = DockStyle.Left + tspRight.Dock = DockStyle.Right + + ' Create ToolStrip controls to move among the + ' ToolStripPanel controls. + ' Create the "Top" ToolStrip control and add + ' to the corresponding ToolStripPanel. + Dim tsTop As New ToolStrip() + tsTop.Items.Add("Top") + tspTop.Join(tsTop) + + ' Create the "Bottom" ToolStrip control and add + ' to the corresponding ToolStripPanel. + Dim tsBottom As New ToolStrip() + tsBottom.Items.Add("Bottom") + tspBottom.Join(tsBottom) + + ' Create the "Right" ToolStrip control and add + ' to the corresponding ToolStripPanel. + Dim tsRight As New ToolStrip() + tsRight.Items.Add("Right") + tspRight.Join(tsRight) + + ' Create the "Left" ToolStrip control and add + ' to the corresponding ToolStripPanel. + Dim tsLeft As New ToolStrip() + tsLeft.Items.Add("Left") + tspLeft.Join(tsLeft) + ' + + ' + ' Create a MenuStrip control with a new window. + Dim ms As New MenuStrip() + Dim windowMenu As New ToolStripMenuItem("Window") + Dim windowNewMenu As New ToolStripMenuItem("New", Nothing, New EventHandler(AddressOf windowNewMenu_Click)) + windowMenu.DropDownItems.Add(windowNewMenu) + CType(windowMenu.DropDown, ToolStripDropDownMenu).ShowImageMargin = False + CType(windowMenu.DropDown, ToolStripDropDownMenu).ShowCheckMargin = True + + ' Assign the ToolStripMenuItem that displays + ' the list of child forms. + ms.MdiWindowListItem = windowMenu + + ' Add the window ToolStripMenuItem to the MenuStrip. + ms.Items.Add(windowMenu) + + ' Dock the MenuStrip to the top of the form. + ms.Dock = DockStyle.Top + + ' The Form.MainMenuStrip property determines the merge target. + Me.MainMenuStrip = ms + ' + + ' Add the ToolStripPanels to the form in reverse order. + Me.Controls.Add(tspRight) + Me.Controls.Add(tspLeft) + Me.Controls.Add(tspBottom) + Me.Controls.Add(tspTop) + + ' Add the MenuStrip last. + ' This is important for correct placement in the z-order. + Me.Controls.Add(ms) + End Sub + + ' This event handler is invoked when + ' the "New" ToolStripMenuItem is clicked. + ' It creates a new Form and sets its MdiParent + ' property to the main form. + Private Sub windowNewMenu_Click(ByVal sender As Object, ByVal e As EventArgs) + Dim f As New Form() + f.MdiParent = Me + f.Text = "Form - " + Me.MdiChildren.Length.ToString() + f.Show() + End Sub +End Class +' + +' +' This code example demonstrates how to use a ProfessionalRenderer +' to define custom professional colors at runtime. +' +Class Form2 + Inherits Form + + Public Sub New() + ' Create a new ToolStrip control. + Dim ts As New ToolStrip() + + ' Populate the ToolStrip control. + ts.Items.Add("Apples") + ts.Items.Add("Oranges") + ts.Items.Add("Pears") + ts.Items.Add("Change Colors", Nothing, New EventHandler(AddressOf ChangeColors_Click)) + + ' Create a new MenuStrip. + Dim ms As New MenuStrip() + + ' Dock the MenuStrip control to the top of the form. + ms.Dock = DockStyle.Top + + ' Add the top-level menu items. + ms.Items.Add("File") + ms.Items.Add("Edit") + ms.Items.Add("View") + ms.Items.Add("Window") + + ' + ' Add the ToolStrip to Controls collection. + Me.Controls.Add(ts) + + ' Add the MenuStrip control last. + ' This is important for correct placement in the z-order. + Me.Controls.Add(ms) + ' + End Sub + + ' + ' This event handler is invoked when the "Change colors" + ' ToolStripItem is clicked. It assigns the Renderer + ' property for the ToolStrip control. + Sub ChangeColors_Click(ByVal sender As Object, ByVal e As EventArgs) + ToolStripManager.Renderer = New ToolStripProfessionalRenderer(New CustomProfessionalColors()) + End Sub + ' +End Class +' + +' +' This class defines the gradient colors for +' the MenuStrip and the ToolStrip. +Class CustomProfessionalColors + Inherits ProfessionalColorTable + + Public Overrides ReadOnly Property ToolStripGradientBegin() As Color + Get + Return Color.BlueViolet + End Get + End Property + + Public Overrides ReadOnly Property ToolStripGradientMiddle() As Color + Get + Return Color.CadetBlue + End Get + End Property + + Public Overrides ReadOnly Property ToolStripGradientEnd() As Color + Get + Return Color.CornflowerBlue + End Get + End Property + + Public Overrides ReadOnly Property MenuStripGradientBegin() As Color + Get + Return Color.Salmon + End Get + End Property + + Public Overrides ReadOnly Property MenuStripGradientEnd() As Color + Get + Return Color.OrangeRed + End Get + End Property + +End Class +' +' + +' +' This code example demonstrates how to handle the Opening event. +' It also demonstrates dynamic item addition and dynamic +' SourceControl determination with reuse. +Class Form3 + Inherits Form + + ' Declare the ContextMenuStrip control. + Private fruitContextMenuStrip As ContextMenuStrip + + + Public Sub New() + ' Create a new ContextMenuStrip control. + fruitContextMenuStrip = New ContextMenuStrip() + + ' Attach an event handler for the + ' ContextMenuStrip control's Opening event. + AddHandler fruitContextMenuStrip.Opening, AddressOf cms_Opening + + ' Create a new ToolStrip control. + Dim ts As New ToolStrip() + + ' Create a ToolStripDropDownButton control and add it + ' to the ToolStrip control's Items collections. + Dim fruitToolStripDropDownButton As New ToolStripDropDownButton("Fruit", Nothing, Nothing, "Fruit") + ts.Items.Add(fruitToolStripDropDownButton) + + ' Dock the ToolStrip control to the top of the form. + ts.Dock = DockStyle.Top + + ' Assign the ContextMenuStrip control as the + ' ToolStripDropDownButton control's DropDown menu. + fruitToolStripDropDownButton.DropDown = fruitContextMenuStrip + + ' Create a new MenuStrip control and add a ToolStripMenuItem. + Dim ms As New MenuStrip() + Dim fruitToolStripMenuItem As New ToolStripMenuItem("Fruit", Nothing, Nothing, "Fruit") + ms.Items.Add(fruitToolStripMenuItem) + + ' Dock the MenuStrip control to the top of the form. + ms.Dock = DockStyle.Top + + ' Assign the MenuStrip control as the + ' ToolStripMenuItem's DropDown menu. + fruitToolStripMenuItem.DropDown = fruitContextMenuStrip + + ' Assign the ContextMenuStrip to the form's + ' ContextMenuStrip property. + Me.ContextMenuStrip = fruitContextMenuStrip + + ' Add the ToolStrip control to the Controls collection. + Me.Controls.Add(ts) + + 'Add a button to the form and assign its ContextMenuStrip. + Dim b As New Button() + b.Location = New System.Drawing.Point(60, 60) + Me.Controls.Add(b) + b.ContextMenuStrip = fruitContextMenuStrip + + ' Add the MenuStrip control last. + ' This is important for correct placement in the z-order. + Me.Controls.Add(ms) + End Sub + + ' + ' This event handler is invoked when the ContextMenuStrip + ' control's Opening event is raised. It demonstrates + ' dynamic item addition and dynamic SourceControl + ' determination with reuse. + Sub cms_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) + + ' Acquire references to the owning control and item. + Dim c As Control = fruitContextMenuStrip.SourceControl + Dim tsi As ToolStripDropDownItem = fruitContextMenuStrip.OwnerItem + + ' Clear the ContextMenuStrip control's + ' Items collection. + fruitContextMenuStrip.Items.Clear() + + ' Check the source control first. + If (c IsNot Nothing) Then + ' Add custom item (Form) + fruitContextMenuStrip.Items.Add(("Source: " + c.GetType().ToString())) + ElseIf (tsi IsNot Nothing) Then + ' Add custom item (ToolStripDropDownButton or ToolStripMenuItem) + fruitContextMenuStrip.Items.Add(("Source: " + tsi.GetType().ToString())) + End If + + ' Populate the ContextMenuStrip control with its default items. + fruitContextMenuStrip.Items.Add("-") + fruitContextMenuStrip.Items.Add("Apples") + fruitContextMenuStrip.Items.Add("Oranges") + fruitContextMenuStrip.Items.Add("Pears") + + ' Set Cancel to false. + ' It is optimized to true based on empty entry. + e.Cancel = False + End Sub + ' +End Class +' + +' +' This code example demonstrates using the Spring property +' to interactively center a ToolStripStatusLabel in a StatusStrip. +Class Form4 + Inherits Form + + ' Declare the ToolStripStatusLabel. + Private middleLabel As ToolStripStatusLabel + + + Public Sub New() + ' Create a new StatusStrip control. + Dim ss As New StatusStrip() + + ' Add the leftmost label. + ss.Items.Add("Left") + + ' Handle middle label separately -- action will occur + ' when the label is clicked. + middleLabel = New ToolStripStatusLabel("Middle (Spring)") + AddHandler middleLabel.Click, AddressOf middleLabel_Click + ss.Items.Add(middleLabel) + + ' Add the rightmost label + ss.Items.Add("Right") + + ' Add the StatusStrip control to the controls collection. + Me.Controls.Add(ss) + End Sub + + ' + ' This event hadler is invoked when the + ' middleLabel control is clicked. It toggles + ' the value of the Spring property. + Sub middleLabel_Click(ByVal sender As Object, ByVal e As EventArgs) + + ' Toggle the value of the Spring property. + middleLabel.Spring = middleLabel.Spring Xor True + + ' Set the Text property according to the + ' value of the Spring property. + middleLabel.Text = IIf(middleLabel.Spring, _ + "Middle (Spring - True)", "Middle (Spring - False)") + End Sub + ' +End Class +' + +' +' This code example demonstrates how to set the check +' and image margins for a ToolStripMenuItem. +Class Form5 + Inherits Form + + ' + Public Sub New() + ' Size the form to show three wide menu items. + Me.Width = 500 + Me.Text = "ToolStripContextMenuStrip: Image and Check Margins" + + ' Create a new MenuStrip control. + Dim ms As New MenuStrip() + + ' Create the ToolStripMenuItems for the MenuStrip control. + Dim bothMargins As New ToolStripMenuItem("BothMargins") + Dim imageMarginOnly As New ToolStripMenuItem("ImageMargin") + Dim checkMarginOnly As New ToolStripMenuItem("CheckMargin") + Dim noMargins As New ToolStripMenuItem("NoMargins") + + ' Customize the DropDowns menus. + ' This ToolStripMenuItem has an image margin + ' and a check margin. + bothMargins.DropDown = CreateCheckImageContextMenuStrip() + CType(bothMargins.DropDown, ContextMenuStrip).ShowImageMargin = True + CType(bothMargins.DropDown, ContextMenuStrip).ShowCheckMargin = True + + ' This ToolStripMenuItem has only an image margin. + imageMarginOnly.DropDown = CreateCheckImageContextMenuStrip() + CType(imageMarginOnly.DropDown, ContextMenuStrip).ShowImageMargin = True + CType(imageMarginOnly.DropDown, ContextMenuStrip).ShowCheckMargin = False + + ' This ToolStripMenuItem has only a check margin. + checkMarginOnly.DropDown = CreateCheckImageContextMenuStrip() + CType(checkMarginOnly.DropDown, ContextMenuStrip).ShowImageMargin = False + CType(checkMarginOnly.DropDown, ContextMenuStrip).ShowCheckMargin = True + + ' This ToolStripMenuItem has no image and no check margin. + noMargins.DropDown = CreateCheckImageContextMenuStrip() + CType(noMargins.DropDown, ContextMenuStrip).ShowImageMargin = False + CType(noMargins.DropDown, ContextMenuStrip).ShowCheckMargin = False + + ' Populate the MenuStrip control with the ToolStripMenuItems. + ms.Items.Add(bothMargins) + ms.Items.Add(imageMarginOnly) + ms.Items.Add(checkMarginOnly) + ms.Items.Add(noMargins) + + ' Dock the MenuStrip control to the top of the form. + ms.Dock = DockStyle.Top + + ' Add the MenuStrip control to the controls collection last. + ' This is important for correct placement in the z-order. + Me.Controls.Add(ms) + End Sub + ' + + ' This utility method creates a Bitmap for use in + ' a ToolStripMenuItem's image margin. + Friend Function CreateSampleBitmap() As Bitmap + + ' The Bitmap is a smiley face. + Dim sampleBitmap As New Bitmap(32, 32) + Dim g As Graphics = Graphics.FromImage(sampleBitmap) + + Dim p As New Pen(ProfessionalColors.ButtonPressedBorder) + Try + ' Set the Pen width. + p.Width = 4 + + ' Set up the mouth geometry. + Dim curvePoints() As Point = _ + {New Point(4, 14), New Point(16, 24), New Point(28, 14)} + + ' Draw the mouth. + g.DrawCurve(p, curvePoints) + + ' Draw the eyes. + g.DrawEllipse(p, New Rectangle(New Point(7, 4), New Size(3, 3))) + g.DrawEllipse(p, New Rectangle(New Point(22, 4), New Size(3, 3))) + Finally + p.Dispose() + End Try + + Return sampleBitmap + End Function + + ' + ' This utility method creates a ContextMenuStrip control + ' that has four ToolStripMenuItems showing the four + ' possible combinations of image and check margins. + Friend Function CreateCheckImageContextMenuStrip() As ContextMenuStrip + ' Create a new ContextMenuStrip control. + Dim checkImageContextMenuStrip As New ContextMenuStrip() + + ' Create a ToolStripMenuItem with a + ' check margin and an image margin. + Dim yesCheckYesImage As New ToolStripMenuItem("Check, Image") + yesCheckYesImage.Checked = True + yesCheckYesImage.Image = CreateSampleBitmap() + + ' Create a ToolStripMenuItem with no + ' check margin and with an image margin. + Dim noCheckYesImage As New ToolStripMenuItem("No Check, Image") + noCheckYesImage.Checked = False + noCheckYesImage.Image = CreateSampleBitmap() + + ' Create a ToolStripMenuItem with a + ' check margin and without an image margin. + Dim yesCheckNoImage As New ToolStripMenuItem("Check, No Image") + yesCheckNoImage.Checked = True + + ' Create a ToolStripMenuItem with no + ' check margin and no image margin. + Dim noCheckNoImage As New ToolStripMenuItem("No Check, No Image") + noCheckNoImage.Checked = False + + ' Add the ToolStripMenuItems to the ContextMenuStrip control. + checkImageContextMenuStrip.Items.Add(yesCheckYesImage) + checkImageContextMenuStrip.Items.Add(noCheckYesImage) + checkImageContextMenuStrip.Items.Add(yesCheckNoImage) + checkImageContextMenuStrip.Items.Add(noCheckNoImage) + + Return checkImageContextMenuStrip + End Function + ' +End Class +' + +' +' This example demonstrates how to apply a +' custom professional renderer to an individual +' ToolStrip or to the application as a whole. +Class Form6 + Inherits Form + Private targetComboBox As New ComboBox() + + + Public Sub New() + + ' Alter the renderer at the top level. + ' Create and populate a new ToolStrip control. + Dim ts As New ToolStrip() + ts.Name = "ToolStrip" + ts.Items.Add("Apples") + ts.Items.Add("Oranges") + ts.Items.Add("Pears") + + ' Create a new menustrip with a new window. + Dim ms As New MenuStrip() + ms.Name = "MenuStrip" + ms.Dock = DockStyle.Top + + ' add top level items + Dim fileMenuItem As New ToolStripMenuItem("File") + ms.Items.Add(fileMenuItem) + ms.Items.Add("Edit") + ms.Items.Add("View") + ms.Items.Add("Window") + + ' Add subitems to the "File" menu. + fileMenuItem.DropDownItems.Add("Open") + fileMenuItem.DropDownItems.Add("Save") + fileMenuItem.DropDownItems.Add("Save As...") + fileMenuItem.DropDownItems.Add("-") + fileMenuItem.DropDownItems.Add("Exit") + + ' Add a Button control to apply renderers. + Dim applyButton As New Button() + applyButton.Text = "Apply Custom Renderer" + AddHandler applyButton.Click, AddressOf applyButton_Click + + ' Add the ComboBox control for choosing how + ' to apply the renderers. + targetComboBox.Items.Add("All") + targetComboBox.Items.Add("MenuStrip") + targetComboBox.Items.Add("ToolStrip") + targetComboBox.Items.Add("Reset") + + ' Create and set up a TableLayoutPanel control. + Dim tlp As New TableLayoutPanel() + tlp.Dock = DockStyle.Fill + tlp.RowCount = 1 + tlp.ColumnCount = 2 + tlp.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize)) + tlp.ColumnStyles.Add(New ColumnStyle(SizeType.Percent)) + tlp.Controls.Add(applyButton) + tlp.Controls.Add(targetComboBox) + + ' Create a GroupBox for the TableLayoutPanel control. + Dim gb As New GroupBox() + gb.Text = "Apply Renderers" + gb.Dock = DockStyle.Fill + gb.Controls.Add(tlp) + + ' Add the GroupBox to the form. + Me.Controls.Add(gb) + + ' Add the ToolStrip to the form's Controls collection. + Me.Controls.Add(ts) + + ' Add the MenuStrip control last. + ' This is important for correct placement in the z-order. + Me.Controls.Add(ms) + End Sub + + ' + ' This event handler is invoked when + ' the "Apply Renderers" button is clicked. + ' Depending on the value selected in a ComboBox + ' control, it applies a custom renderer selectively + ' to individual MenuStrip or ToolStrip controls, + ' or it applies a custom renderer to the + ' application as a whole. + Sub applyButton_Click(ByVal sender As Object, ByVal e As EventArgs) + Dim ms As ToolStrip = ToolStripManager.FindToolStrip("MenuStrip") + Dim ts As ToolStrip = ToolStripManager.FindToolStrip("ToolStrip") + + If targetComboBox.SelectedItem IsNot Nothing Then + + Select Case targetComboBox.SelectedItem.ToString() + Case "Reset" + ms.RenderMode = ToolStripRenderMode.ManagerRenderMode + ts.RenderMode = ToolStripRenderMode.ManagerRenderMode + + ' Set the default RenderMode to Professional. + ToolStripManager.RenderMode = ToolStripManagerRenderMode.Professional + + Exit Select + + Case "All" + ms.RenderMode = ToolStripRenderMode.ManagerRenderMode + ts.RenderMode = ToolStripRenderMode.ManagerRenderMode + + ' Assign the custom renderer at the application level. + ToolStripManager.Renderer = New CustomProfessionalRenderer() + + Exit Select + + Case "MenuStrip" + ' Assign the custom renderer to the MenuStrip control only. + ms.Renderer = New CustomProfessionalRenderer() + + Exit Select + + Case "ToolStrip" + ' Assign the custom renderer to the ToolStrip control only. + ts.Renderer = New CustomProfessionalRenderer() + + Exit Select + End Select + + End If + End Sub + ' +End Class + +' +' This type demonstrates a custom renderer. It overrides the +' OnRenderMenuItemBackground and OnRenderButtonBackground methods +' to customize the backgrounds of MenuStrip items and ToolStrip buttons. +Class CustomProfessionalRenderer + Inherits ToolStripProfessionalRenderer + + ' + Protected Overrides Sub OnRenderMenuItemBackground(e As ToolStripItemRenderEventArgs) + If e.Item.Selected Then + Dim b = New SolidBrush(ProfessionalColors.SeparatorLight) + Try + e.Graphics.FillEllipse(b, e.Item.ContentRectangle) + Finally + b.Dispose() + End Try + Else + Dim p As New Pen(ProfessionalColors.SeparatorLight) + Try + e.Graphics.DrawEllipse(p, e.Item.ContentRectangle) + Finally + p.Dispose() + End Try + End If + End Sub + ' + + ' + Protected Overrides Sub OnRenderButtonBackground(e As ToolStripItemRenderEventArgs) + Dim r As Rectangle = Rectangle.Inflate(e.Item.ContentRectangle, - 2, - 2) + + If e.Item.Selected Then + Dim b = New SolidBrush(ProfessionalColors.SeparatorLight) + Try + e.Graphics.FillRectangle(b, r) + Finally + b.Dispose() + End Try + Else + Dim p As New Pen(ProfessionalColors.SeparatorLight) + Try + e.Graphics.DrawRectangle(p, r) + Finally + p.Dispose() + End Try + End If + End Sub + ' +End Class +' +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb new file mode 100644 index 0000000000..adca696b21 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StackView/VB/StackView.vb @@ -0,0 +1,481 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.IO +Imports System.Windows.Forms + +Public Class StackView + Inherits UserControl + Private stackStrip As ToolStrip + Private WithEvents mailStackButton As ToolStripButton + Private WithEvents calendarStackButton As ToolStripButton + Private WithEvents contactsStackButton As ToolStripButton + Private WithEvents tasksStackButton As ToolStripButton + + Private components As System.ComponentModel.IContainer = Nothing + + ' + Private Shared mailBmp As Bitmap + Private Shared calendarBmp As Bitmap + Private Shared contactsBmp As Bitmap + Private Shared tasksBmp As Bitmap + + Private Shared mailBmpEnc As String = "Qk32BgAAAAAAADYAAAAoAAAA" + _ + "GAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7uv4yFvouE" + _ + "vYmDu4eBuYV/t4N9tYB7s355sXt3tntxsnhwsHZurXNsrHFrp21pomln" + _ + "oGdlnmVjnWNi7u7u7u7u7u7u7u7u7u7uwY6H9N3C/vDa/ejM+tSp+cye" + _ + "98OS9bqI87F/87KA8qt68KRy76Bu7phl7ZVi7JVi54xb0ntSoGVj7u7u" + _ + "7u7u7u7u7u7u7u7uwo+Ix6WZ9ujb//bn/u/b/OfL++HA+9iv+tev+tSr" + _ + "+tKo+cyg+Mic9b+S9LqM8al35ZZmoXBSoWdk7u7u7u7u7u7u7u7u7u7u" + _ + "xZSN9ejayaOY9uvh//js/vXo/e/a/evS/OfL/OTF+927+9u1+tSq+tKl" + _ + "+cqW8buFqHZa7JVdn2hm7u7u7u7u7u7u7u7u7u7uxZSN//ns9ercxqKV" + _ + "+O7k//nw//fu//fr/vTl/u/c/uvU/eLB/N+7+tev8b6Hq3pe+Lh6/69q" + _ + "oWpp7u7u7u7u7u7u7u7u7u7ux5eP//vv//vw9OncxKOX9+7m//v1//nz" + _ + "//jx//bs/+7Z/erQ/eTC8syiqntg+M6a/9Oh/8CFom1s7u7u7u7u7u7u" + _ + "7u7u7u7uypqS//z4//v28ebYza2evp6V7+Lb8uzl8+3l8uvk9Ore9ejZ" + _ + "6NO/poVyt4xx5b2T/9ap/8ybpXFw7u7u7u7u7u7u7u7u7u7uzJ2V///8" + _ + "7uPbzaye/fv6/fv5v6GTvKCQvJ+Nu5qIupmJt5uKsZWE+u3e+unYo4Jq" + _ + "572O/9KjqHd17u7u7u7u7u7u7u7u7u7uzqCX7OHbzKud/fr58url5tnQ" + _ + "5dfO5dfN5dfM5NbM49TI3Mq+3Mm93Mm8382/+unbrIJp57WGrH597u7u" + _ + "7u7u7u7u7u7u7u7uz6GZ0LGj6uHa/fv67OLc6+Hb7eTd7ePd7eLb7eLb" + _ + "7uPb9e7l9evk9uvj9+zh/PHlzr61r4VtsoWC7u7u7u7u7u7u7u7u7u7u" + _ + "0aKXfdb/8uzn///////////////////////+//37/Pn3+fXv9fHp8+vl" + _ + "8enk7uXe1si/L6f3tYeC7u7u7u7u7u7u7u7u7u7uy6mkdM3/+vf1////" + _ + "/////////////////fz8/Pv69fPx7vDw7O/w2OfvxN/swt/thMXnK6ft" + _ + "r4SC7u7u7u7u7u7u7u7u7u7u1KeevuX6nNf2rN/7nNz9h9X+b8z+VMb/" + _ + "RsT/RsT/PsP/Obz7NLT2MbL0K6vuJ6XpKKfrLqrvr4J/7u7u7u7u7u7u" + _ + "7u7u7u7u28jC0rSo0O36yOv7x+r7v+f8suP9o97+jtj+idn+htX/e83/" + _ + "a8f/XcD/Tbn/SLf/R7b/rJKJ7u7u7u7u7u7u7u7u7u7u7u7u7u7u6ePi" + _ + "07ew29zd1e/61O/60e77y+z8vun9reH+mNn+gdH/ccj/ZMP/Vr3/t7/C" + _ + "uKCX7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u6uXk2b621rux1fH6" + _ + "3fL61/L7y+/8u+f9pt7+jNT+cMn/XcH/rZyW1c3L7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u6N/d07Op3d7f2/P60vD7xez8" + _ + "r+H9k9X+kr/cv6Wb7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u6uXk2L612cG31e73yOv7seL8uKWezLex7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u6eHg1LOpzaeayaqh4dvb7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + + Private Shared calendarBmpEnc As String = "Qk32BgAAAAAAADYAAAAo" + _ + "AAAAGAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7uuKOUkXxqemNO" + _ + "alM8YEgwYEgwYkoxYUgwYEgwY0szYkoxYEgwYEgwYEgwYEgwZEszYUgw" + _ + "YEgwY0oyYUgwYEgwYEgw7u7u7u7uuqWW6tPE27qlxKCLu5d837OUzKGC" + _ + "t41xsYpt37OUzKGCt41xrodq37OUzKGCt41xrodq37OUzKGCt41xrodq" + _ + "Zk447u7u7u7uvKaX//fz/+3i/NvFwJl6/+nb/d3H+c+1vJV2/+HP/tW8" + _ + "/MWluZJz/9vG/9Gw+8OfuJFy/86y/sKf97eSuJFyYEgw7u7u7u7uvaiZ" + _ + "//j2//Hq/OTY0qiL/+7h/+TR/N3J0KWI/+TU/9vE/9S4zqOF/+LR/9zE" + _ + "/sywzaKE/9e//8yt/sWizaKEYEgw7u7u7u7uv6qb//v5//j1//bx5Lug" + _ + "//Ho//Dl/+nb5Lqg/+fZ/+LQ/97I5Lqf/+XU/+HN/9zF5Lqf/9bC/9S7" + _ + "/9C05LqfYEgw7u7u7u7uwauc4bib1ayOxZyBvpd74LaY0qiKwJd7uJF1" + _ + "4LWWz6WGvJJ2D0XuBTnjBjXQAiy8ACm137OUzKGCt41xrodqYEgw7u7u" + _ + "7u7uxK6f//v6/Ozg/eHQx6CC/+/m+uHQ+tjDwpt9/+re/+DM/9O4I1Tz" + _ + "/9zG/9O5/86wASu4/9fC98Sm87uYuJFyYEgw7u7u7u7uxrCh//39//n0" + _ + "/One1qyQ//v4/vHn+uHR06mM//Pt/+rc/+HMPGr0/+TU/93H/9i/AzHJ" + _ + "/+LP/9i++curzaKEYEgw7u7u7u7ux7Kj//39//38/fbw5Luh//z7/vj1" + _ + "/uzh5Lug//fx//bv/+vgWoH2/+/m/+vd/+PQAzTa/+XU/+XU/97J5Lqf" + _ + "YUkx7u7u7u7uybOk47yh3rab1q2SzaWL4bqe2a+SzKKHwpqA4bmd1q2O" + _ + "x52CbY/5WYD3OWb0IFP0Aj3t4Lib06iJwJV5sopwYEgw7u7u7u7uzbep" + _ + "//39//n1//Dn1a2S/vv6+uvh9+DPyqKG//Tt+eXX+eDSxJx//One+tzH" + _ + "+dC3v5d6/9/K+9C1+8akuI9yalM97u7u7u7u0Lyu//39//r3//f03bWa" + _ + "//7+/vXx+urg1q2R//f0/O3i+eTV06mM//fy/+7i+NfCz6WI/+zg/+DM" + _ + "/9CzyZ6Adl5I7u7u7u7u0sCy//38//39//395L2j//7+//79/vn45L2j" + _ + "//38//n2/vLr5L2j//37//n2/unf5L2j/+/l/+nc/+DN5L2jf2dS7u7u" + _ + "7u7u6KaG6KaG6KSE56OB56B+55565pt25phy5ZVt5ZJp5I5k5Itf5Iha" + _ + "44RV44FR4n5M4ntI4XhE23I812w00mkzyGAo7u7u7u7u6amK/93L/dfD" + _ + "/9a+/s+2/syy/sis/sSl/cGh/byb/LeV+7SO+rCJ+auC+ad9+KN3+KBx" + _ + "95xu95pq9pdn9pVkyGAo7u7u7u7u662P/+LQ/t/M/t3K/drG/dfC/dK8" + _ + "/c63/Mqx/Mer+sKk+r6f+bqY+LaT+LGM96yG9qmA9aV69aB19J1w9Jps" + _ + "yGAo7u7u7u7u7LKV7LKV662P6aeG56F/559855x45pp05pdw5ZRs5ZFo" + _ + "5I5j5Itf5Ihb44VW44JS4n9O4nxK4XpG4XdC4XU/2Ws27u7u7u7upJqU" + _ + "////pJqU////n5aQ////mZCL////kYmF////iIJ+////fnp2////dXJv" + _ + "////bGpo////ZGNi////XV5c////7u7u7u7u7u7uICUg6enpICUg6enp" + _ + "ICUg6enpICUg6enpICUg6enpICUg6enpICUg3t7eICUg0NDQICUgvb29" + _ + "ICUguLi4ICUg7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u" + + Private Shared contactsBmpEnc As String = "Qk32BgAAAAAAADYAAAAo" + _ + "AAAAGAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7uuqWWh3FeeWJN" + _ + "alM8YEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgwYEgw" + _ + "YEgwYEgwYEgwYEgwYEgw7u7u7u7uuqWW//bx7t3T7trO7tfI79LB7865" + _ + "8Mqy8MWq8cCi8buZ8raR8rKJ862C86l69KV09KFt9Z5o9Zxk9Zph9Zph" + _ + "YEgw7u7u7u7uu6aX//n2//fy//Xv//Lr//Dn/+3j/+re/+ja/+XW/+LR" + _ + "/+DN/93J/9rF/9jB/9W9/9O5/9G2/8+z/86x9ZphYEgw7u7u7u7uvKiZ" + _ + "//z6//r30M/SGlmtA0uuA0WfAz+RATmHADV9zr23/+PTs4t1roRuqX1m" + _ + "pHhgoXRcoXRcoXRc/9C09Z1mYEgw7u7u7u7uvqqb//79//z7FFe3N3rV" + _ + "SYrkQ4XeA0OaGW3eC02nGkF4/+fZ/+TV/+LQ/9/M/9zI/9rE/9fA/9W8" + _ + "/9O59KFtYEgw7u7u7u7uwKyd//////7+E1i3Z57pUZDoTY7nA0SbGGze" + _ + "E2DIAzmD/+vfuZJ9s4t1roRuqX1mpHhgoXRcoXRc/9a99KV0YEgw7u7u" + _ + "7u7uwq6f////////GF69gKvkX5flA0WeGW7iA0+3GWzgEk+j/+7l/+zh" + _ + "/+nc/+bY/+TT/+HP/97L/9zH/9nD86t9YEgw7u7u7u7uxLCh////////" + _ + "tcDPE1StGly1yNXZ+fryBVG5BkGOz8rK//LqvpiEuZJ9s4t1roRuqX1m" + _ + "pHhgoXRc/93I87CHYEgw7u7u7u7uxrKk////////9fX1zdDTYWZsVFVW" + _ + "YWFhBkunubzC//jz//Xw//Ps//Do/+7k/+vf/+jb/+bX/+PS/+DO8raR" + _ + "YEgw7u7u7u7ux7Sm////////xMTEAAAAwcHBoqKihYWFVVVVn56d//r3" + _ + "//j0//bx//Tt//Hp/+/l/+zh/+nd/+fY/+TU8b2cYEgw7u7u7u7uybao" + _ + "////////ODg4LCws1tbWwcHBoqKihYWFZGRk//37//v5//n2//fy//Xv" + _ + "//Lr//Dn/+3j/+re/+ja8MOmYEgw7u7u7u7uy7iq////////U1NTSUlJ" + _ + "tLS01dXVwcHBoqKidXV1///+//38/LeL+7SI+q+D+ap++KV496Bz9p1w" + _ + "/+vg8MmxZk437u7u7u7uzbqs////////fn5+Y2NjXV1dbW1tWFhYwcHB" + _ + "hISE//////////79//z7//v4//n1//bx//Tu//Lq/+/m78+6b1dB7u7u" + _ + "7u7uz7yu////////xcXFbGxsgoKCoaGhjo6OVVVVra2t/////////LeL" + _ + "+7SI+q+D+ap++KV496Bz9p1w//Pr79TEeWJN7u7u7u7u0L6w////////" + _ + "8vLyuLi4jY2NiIiIhYWFtLS08fHx//////////////////////38//z6" + _ + "//r3//j0//bw7tnMgm1Z7u7u7u7u0b+x////////////////////////" + _ + "//////////////////////////////////////79//z7//v4//n1//fy" + _ + "i3Zj7u7u7u7u0sCy0b+x0L6wz72vzrutzLqsy7iqybeoyLWmxrOkxLGi" + _ + "w6+hwa2fv6udvqmbvKiZu6aXuaWWuKOUt6KTtqGStaCR7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + _ + "7u7u" + + Private Shared tasksBmpEnc As String = "Qk32BgAAAAAAADYAAAAoAAA" + _ + "AGAAAABgAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAA7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u3N3fkXxqeGB" + _ + "LalE5cVc/c1lBf2JKl3RZiWhMe1xBb1M5aE42Zkw0Zk01aE42YUkxYkk" + _ + "xYkkxkod97u7u7u7u7u7u7u7u7u7uv62e+ezi69nQ7M6+7Miz6L+prI+" + _ + "rWFKqmHyk7rWU77OO77CM8LCK8bCH8a2F8qp98aV13pZnZkwz7u7u7u7" + _ + "u7u7u7u7u7u7uv62e//37/vr3/vTw+uvkwLnaJDO/BhmzJjTDybTG99K" + _ + "8+NC49syy9sms9sao9cOl8LiV8KR0aU417u7u7u7u7u7u7u7u7u7uwK6" + _ + "f//7+//z7/Pj3xcTmLDvBFynIMEXkIDbXVGHO6dHO+tzJ+tjD+dW++dK" + _ + "5+c+19sWn8qd2Y0kx7u7u7u7u7u7u7u7u7u7uw7Gj/////Pv9wcTsKDj" + _ + "FFCnMRVjuZHX1PlPoFzHSeHPJ+d3O+tzI+tjD+dS9+dG59seq8ayEaEw" + _ + "07u7u7u7u7u7u7u7u7u7uxrWm9vf9pKzoJjjNGi7TR1nreoj/j5v8ZXf" + _ + "0N0zlJjTPv7LP+t7O+tvI+tfC+dS998qv8K+LaU427u7u7u7u7u7u7u7" + _ + "u7u7u08W619v5Kz7XJjrfTl/ze4v/tLr59/Dyoab2Znb0LUPmNUTO1sX" + _ + "R+9/N+tvH+tjC99C277GNbVI47u7u7u7u7u7u7u7u7u7uy7qt6+3+kp7" + _ + "4UGT4c4P/sbj+/Pr5/vj16ePykpz5Y3T0KDzfbHHR6dTS++HQ+tvG+dn" + _ + "D8bqabVI57u7u7u7u7u7u7u7u7u7uybeo////9ff/qLL/wsr//Pz///3" + _ + "8/vv5/ff09e7wpav4YnP0KDzajYzQ6NPT/N7O+NrG8b+idFlA7u7u7u7" + _ + "u7u7u7u7u7u7uyriq////////+Pn//v7///////////38/vr2/vj08er" + _ + "wmaL6WWvyMELXmJbS9OPb+d/Q88mxc1Y97u7u7u7u7u7u7u7u7u7uzLq" + _ + "s//////////////////////////7+//36/vr3/vn0+fDvsLT1WmruNUb" + _ + "Qta/V+uXX9M+6hWdP7u7u7u7u7u7u7u7u7u7uzryt///////////////" + _ + "///////////////7+//79//v3/vj0+O7wurz0TV3sSFTS08fa9t7PmXl" + _ + "h7u7u7u7u7u7u7u7u7u7uz72v/////////////////////fj1+Orh9uH" + _ + "W89TD88+78sew9NK99drNm5/xVWbwYWvV6dzgrIlw7u7u7u7u7u7u7u7" + _ + "u7u7u0L6w////////////////X4ycVYGSTHaIS21/SGN0SGJySF9vdnd" + _ + "9pZWQ89TDt7n1TF3oZGvOuJ2L7u7u7u7u7u7u7u7u7u7u0b+x///////" + _ + "/////////dJmou+Xsmd3ofs/fdcXVcMHSbrrNbbHCbHJ69dTD++3nw8H" + _ + "uNUjqZGjJ7u7u7u7u7u7u7u7u7u7u0b+x////////////////i6q2pMn" + _ + "StuzzYYycdLG+fs/ed8jaXY2eRl1t8uDU++je/O7mzsnmUFCX7u7u7u7" + _ + "u7u7u7u7u7u7u0sCy////////////////3ufqdZuqx+30V3aFXoCPaZW" + _ + "kjdDeTWx8v7Ko/vr2/fTv/fTu+/XxnZSu7u7u7u7u7u7u7u7u7u7u6ur" + _ + "r2Mq/0b+x0L6wz72vyLeqc5qpoMHLxfD3v+zzruXvkMjVaX6GwK6ewrC" + _ + "hwa+gwK6fv62e4OHi7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u5ObnfKa1eaOxcpyrcJWkboiW4+Pj7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7" + _ + "u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u" + + ' Static constructor to initialize + ' the form's static fields. + Shared Sub New() + ' Create the static bitmaps from Base64 encoding. + CreateBitmaps() + End Sub + + ' + Public Sub New() + Me.InitializeComponent() + + ' Assign icons to ToolStripButton controls. + Me.InitializeImages() + + ' Set up renderers. + Me.stackStrip.Renderer = New StackRenderer() + End Sub + + ' + ' This utility method assigns icons to each + ' ToolStripButton control. + Private Sub InitializeImages() + Me.mailStackButton.Image = mailBmp + Me.calendarStackButton.Image = calendarBmp + Me.contactsStackButton.Image = contactsBmp + Me.tasksStackButton.Image = tasksBmp + End Sub + + + ' This utility method creates bitmaps for all the icons. + ' It uses a utility method called DeserializeFromBase64 + ' to decode the Base64 image data. + Private Shared Sub CreateBitmaps() + mailBmp = DeserializeFromBase64(mailBmpEnc) + calendarBmp = DeserializeFromBase64(calendarBmpEnc) + contactsBmp = DeserializeFromBase64(contactsBmpEnc) + tasksBmp = DeserializeFromBase64(tasksBmpEnc) + End Sub + + + ' This utility method cretes a bitmap from + ' a Base64-encoded string. + Friend Shared Function DeserializeFromBase64(data As String) As Bitmap + ' Decode the string and create a memory stream + ' on the decoded string data. + Dim stream As New MemoryStream(Convert.FromBase64String(data)) + + ' Create a new bitmap from the stream. + Dim b As New Bitmap(stream) + + Return b + End Function + ' + + ' + ' This method handles the Load event for the UserControl. + Private Sub StackView_Load(sender As Object, e As EventArgs) Handles MyBase.Load + ' Dock bottom. + Me.Dock = DockStyle.Bottom + + ' Set AutoSize. + Me.AutoSize = True + End Sub + ' + + ' + ' This method handles the Click event for all + ' the ToolStripButton controls in the StackView. + Private Sub stackButton_Click(sender As Object, e As EventArgs) Handles mailStackButton.Click, calendarStackButton.Click, contactsStackButton.Click, tasksStackButton.Click + ' Define a "one of many" state, similar to + ' the logic of a RadioButton control. + Dim item As ToolStripItem + For Each item In Me.stackStrip.Items + If item IsNot sender AndAlso TypeOf item Is ToolStripButton Then + CType(item, ToolStripButton).Checked = False + End If + Next item + End Sub + ' + + Protected Overrides Sub Dispose(disposing As Boolean) + If disposing AndAlso (components IsNot Nothing) Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + + ' + Friend Class StackRenderer + Inherits ToolStripProfessionalRenderer + Private Shared titleBarGripBmp As Bitmap + Private Shared titleBarGripEnc As String = "Qk16AQAAAAAAADYAAAAoAAAAIwAAAAMAAAABABgAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5uGMyuGMy+/n5+/n5ANj+RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5wm8/RzIomHRh+/n5ANj+RzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMzHtMRzIoRzIozHtMANj+" + + ' Define titlebar colors. + Private Shared titlebarColor1 As Color = Color.FromArgb(89, 135, 214) + Private Shared titlebarColor2 As Color = Color.FromArgb(76, 123, 204) + Private Shared titlebarColor3 As Color = Color.FromArgb(63, 111, 194) + Private Shared titlebarColor4 As Color = Color.FromArgb(50, 99, 184) + Private Shared titlebarColor5 As Color = Color.FromArgb(38, 88, 174) + Private Shared titlebarColor6 As Color = Color.FromArgb(25, 76, 164) + Private Shared titlebarColor7 As Color = Color.FromArgb(12, 64, 154) + Private Shared borderColor As Color = Color.FromArgb(0, 0, 128) + + Shared Sub New() + titleBarGripBmp = StackView.DeserializeFromBase64(titleBarGripEnc) + End Sub + + Public Sub New() + End Sub + + Private Sub DrawTitleBar(ByVal g As Graphics, ByVal rect As Rectangle) + + ' Assign the image for the grip. + Dim titlebarGrip As Image = titleBarGripBmp + + ' Fill the titlebar. + ' This produces the gradient and the rounded-corner effect. + g.DrawLine(New Pen(titlebarColor1), rect.X, rect.Y, rect.X + rect.Width, rect.Y) + g.DrawLine(New Pen(titlebarColor2), rect.X, rect.Y + 1, rect.X + rect.Width, rect.Y + 1) + g.DrawLine(New Pen(titlebarColor3), rect.X, rect.Y + 2, rect.X + rect.Width, rect.Y + 2) + g.DrawLine(New Pen(titlebarColor4), rect.X, rect.Y + 3, rect.X + rect.Width, rect.Y + 3) + g.DrawLine(New Pen(titlebarColor5), rect.X, rect.Y + 4, rect.X + rect.Width, rect.Y + 4) + g.DrawLine(New Pen(titlebarColor6), rect.X, rect.Y + 5, rect.X + rect.Width, rect.Y + 5) + g.DrawLine(New Pen(titlebarColor7), rect.X, rect.Y + 6, rect.X + rect.Width, rect.Y + 6) + + ' Center the titlebar grip. + g.DrawImage(titlebarGrip, New Point(rect.X + (rect.Width / 2 - titlebarGrip.Width / 2), rect.Y + 1)) + End Sub + + + ' This method handles the RenderGrip event. + Protected Overrides Sub OnRenderGrip(e As ToolStripGripRenderEventArgs) + DrawTitleBar(e.Graphics, New Rectangle(0, 0, e.ToolStrip.Width, 7)) + End Sub + + + ' This method handles the RenderToolStripBorder event. + Protected Overrides Sub OnRenderToolStripBorder(e As ToolStripRenderEventArgs) + DrawTitleBar(e.Graphics, New Rectangle(0, 0, e.ToolStrip.Width, 7)) + End Sub + + + ' This method handles the RenderButtonBackground event. + Protected Overrides Sub OnRenderButtonBackground(e As ToolStripItemRenderEventArgs) + Dim g As Graphics = e.Graphics + Dim bounds As New Rectangle(Point.Empty, e.Item.Size) + + Dim gradientBegin As Color = Color.FromArgb(203, 225, 252) + Dim gradientEnd As Color = Color.FromArgb(125, 165, 224) + + Dim button As ToolStripButton = CType(e.Item, ToolStripButton) + + If button.Pressed OrElse button.Checked Then + gradientBegin = Color.FromArgb(254, 128, 62) + gradientEnd = Color.FromArgb(255, 223, 154) + ElseIf button.Selected Then + gradientBegin = Color.FromArgb(255, 255, 222) + gradientEnd = Color.FromArgb(255, 203, 136) + End If + + Dim b = New LinearGradientBrush(bounds, gradientBegin, gradientEnd, LinearGradientMode.Vertical) + Try + g.FillRectangle(b, bounds) + Finally + b.Dispose() + End Try + + e.Graphics.DrawRectangle(SystemPens.ControlDarkDark, bounds) + + g.DrawLine(SystemPens.ControlDarkDark, bounds.X, bounds.Y, bounds.Width - 1, bounds.Y) + + g.DrawLine(SystemPens.ControlDarkDark, bounds.X, bounds.Y, bounds.X, bounds.Height - 1) + + Dim toolStrip As ToolStrip = button.Owner + Dim nextItem As ToolStripButton = CType(button.Owner.GetItemAt(button.Bounds.X, button.Bounds.Bottom + 1), ToolStripButton) + + If nextItem Is Nothing Then + g.DrawLine(SystemPens.ControlDarkDark, bounds.X, bounds.Height - 1, bounds.X + bounds.Width - 1, bounds.Height - 1) + End If + End Sub + End Class + ' + + #Region "Component Designer generated code" + + + Private Sub InitializeComponent() + Me.stackStrip = New System.Windows.Forms.ToolStrip + Me.mailStackButton = New System.Windows.Forms.ToolStripButton + Me.calendarStackButton = New System.Windows.Forms.ToolStripButton + Me.contactsStackButton = New System.Windows.Forms.ToolStripButton + Me.tasksStackButton = New System.Windows.Forms.ToolStripButton + Me.stackStrip.SuspendLayout() + Me.SuspendLayout() + ' + 'stackStrip + ' + Me.stackStrip.CanOverflow = False + Me.stackStrip.Dock = System.Windows.Forms.DockStyle.Bottom + Me.stackStrip.Font = New System.Drawing.Font("Tahoma", 10.0!, System.Drawing.FontStyle.Bold) + Me.stackStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden + Me.stackStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.mailStackButton, Me.calendarStackButton, Me.contactsStackButton, Me.tasksStackButton}) + Me.stackStrip.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow + Me.stackStrip.Location = New System.Drawing.Point(0, 11) + Me.stackStrip.Name = "stackStrip" + Me.stackStrip.Padding = New System.Windows.Forms.Padding(0, 7, 0, 0) + Me.stackStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional + Me.stackStrip.Size = New System.Drawing.Size(150, 139) + Me.stackStrip.TabIndex = 0 + Me.stackStrip.Text = "toolStrip1" + ' + 'mailStackButton + ' + Me.mailStackButton.CheckOnClick = True + Me.mailStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft + Me.mailStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None + Me.mailStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer)) + Me.mailStackButton.Margin = New System.Windows.Forms.Padding(0) + Me.mailStackButton.Name = "mailStackButton" + Me.mailStackButton.Padding = New System.Windows.Forms.Padding(3) + Me.mailStackButton.Size = New System.Drawing.Size(149, 27) + Me.mailStackButton.Text = " Mail" + Me.mailStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft + ' + 'calendarStackButton + ' + Me.calendarStackButton.CheckOnClick = True + Me.calendarStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft + Me.calendarStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None + Me.calendarStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer)) + Me.calendarStackButton.Margin = New System.Windows.Forms.Padding(0) + Me.calendarStackButton.Name = "calendarStackButton" + Me.calendarStackButton.Padding = New System.Windows.Forms.Padding(3) + Me.calendarStackButton.Size = New System.Drawing.Size(149, 27) + Me.calendarStackButton.Text = " Calendar" + Me.calendarStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft + ' + 'contactsStackButton + ' + Me.contactsStackButton.CheckOnClick = True + Me.contactsStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft + Me.contactsStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None + Me.contactsStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer)) + Me.contactsStackButton.Margin = New System.Windows.Forms.Padding(0) + Me.contactsStackButton.Name = "contactsStackButton" + Me.contactsStackButton.Padding = New System.Windows.Forms.Padding(3) + Me.contactsStackButton.Size = New System.Drawing.Size(149, 27) + Me.contactsStackButton.Text = " Contacts" + Me.contactsStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft + ' + 'tasksStackButton + ' + Me.tasksStackButton.CheckOnClick = True + Me.tasksStackButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft + Me.tasksStackButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None + Me.tasksStackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer), CType(CType(238, Byte), Integer)) + Me.tasksStackButton.Margin = New System.Windows.Forms.Padding(0) + Me.tasksStackButton.Name = "tasksStackButton" + Me.tasksStackButton.Padding = New System.Windows.Forms.Padding(3) + Me.tasksStackButton.Size = New System.Drawing.Size(149, 27) + Me.tasksStackButton.Text = " Tasks" + Me.tasksStackButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft + ' + 'StackView + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.Controls.Add(Me.stackStrip) + Me.Name = "StackView" + Me.stackStrip.ResumeLayout(False) + Me.stackStrip.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + #End Region +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/VB/Form1.vb new file mode 100644 index 0000000000..8b8c51f846 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStrip.StandardMenu/VB/Form1.vb @@ -0,0 +1,380 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Public Sub New() + + Me.InitializeComponent() + + End Sub + + ' + ' This utility method assigns the value of a ToolStripItem + ' control's Text property to the Text property of the + ' ToolStripStatusLabel. + Private Sub UpdateStatus(ByVal item As ToolStripItem) + + If item IsNot Nothing Then + + Dim msg As String = String.Format("{0} selected", item.Text) + Me.StatusStrip1.Items(0).Text = msg + + End If + + End Sub + ' + + ' + ' This method is the DropDownItemClicked event handler. + ' It passes the ClickedItem object to a utility method + ' called UpdateStatus, which updates the text displayed + ' in the StatusStrip control. + Private Sub FileToolStripMenuItem_DropDownItemClicked( _ + ByVal sender As System.Object, _ + ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) _ + Handles FileToolStripMenuItem.DropDownItemClicked + + Me.UpdateStatus(e.ClickedItem) + + End Sub + ' + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + End Sub + Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip + Friend WithEvents FileToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents NewToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents OpenToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents toolStripSeparator As System.Windows.Forms.ToolStripSeparator + Friend WithEvents SaveToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents SaveAsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents toolStripSeparator1 As System.Windows.Forms.ToolStripSeparator + Friend WithEvents PrintToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents PrintPreviewToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents toolStripSeparator2 As System.Windows.Forms.ToolStripSeparator + Friend WithEvents ExitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents EditToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents UndoToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents RedoToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents toolStripSeparator3 As System.Windows.Forms.ToolStripSeparator + Friend WithEvents CutToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents CopyToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents PasteToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents toolStripSeparator4 As System.Windows.Forms.ToolStripSeparator + Friend WithEvents SelectAllToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents ToolsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents CustomizeToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents OptionsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents HelpToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents ContentsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents IndexToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents SearchToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents toolStripSeparator5 As System.Windows.Forms.ToolStripSeparator + Friend WithEvents AboutToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem + Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip + Friend WithEvents ToolStripStatusLabel1 As System.Windows.Forms.ToolStripStatusLabel + + '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() + Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1)) + Me.MenuStrip1 = New System.Windows.Forms.MenuStrip + Me.FileToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.NewToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.OpenToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripSeparator = New System.Windows.Forms.ToolStripSeparator + Me.SaveToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.SaveAsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator + Me.PrintToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.PrintPreviewToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripSeparator2 = New System.Windows.Forms.ToolStripSeparator + Me.ExitToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.EditToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.UndoToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.RedoToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripSeparator3 = New System.Windows.Forms.ToolStripSeparator + Me.CutToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.CopyToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.PasteToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripSeparator4 = New System.Windows.Forms.ToolStripSeparator + Me.SelectAllToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.ToolsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.CustomizeToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.OptionsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.HelpToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.ContentsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.IndexToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.SearchToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.toolStripSeparator5 = New System.Windows.Forms.ToolStripSeparator + Me.AboutToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem + Me.StatusStrip1 = New System.Windows.Forms.StatusStrip + Me.ToolStripStatusLabel1 = New System.Windows.Forms.ToolStripStatusLabel + Me.MenuStrip1.SuspendLayout() + Me.StatusStrip1.SuspendLayout() + Me.SuspendLayout() + ' + 'MenuStrip1 + ' + Me.MenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FileToolStripMenuItem, Me.EditToolStripMenuItem, Me.ToolsToolStripMenuItem, Me.HelpToolStripMenuItem}) + Me.MenuStrip1.Location = New System.Drawing.Point(0, 0) + Me.MenuStrip1.Name = "MenuStrip1" + Me.MenuStrip1.Size = New System.Drawing.Size(292, 24) + Me.MenuStrip1.TabIndex = 0 + Me.MenuStrip1.Text = "MenuStrip1" + ' + 'FileToolStripMenuItem + ' + Me.FileToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.NewToolStripMenuItem, Me.OpenToolStripMenuItem, Me.toolStripSeparator, Me.SaveToolStripMenuItem, Me.SaveAsToolStripMenuItem, Me.toolStripSeparator1, Me.PrintToolStripMenuItem, Me.PrintPreviewToolStripMenuItem, Me.toolStripSeparator2, Me.ExitToolStripMenuItem}) + Me.FileToolStripMenuItem.Name = "FileToolStripMenuItem" + Me.FileToolStripMenuItem.Size = New System.Drawing.Size(35, 20) + Me.FileToolStripMenuItem.Text = "&File" + ' + 'NewToolStripMenuItem + ' + Me.NewToolStripMenuItem.Image = CType(resources.GetObject("NewToolStripMenuItem.Image"), System.Drawing.Image) + Me.NewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.NewToolStripMenuItem.Name = "NewToolStripMenuItem" + Me.NewToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.N), System.Windows.Forms.Keys) + Me.NewToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.NewToolStripMenuItem.Text = "&New" + ' + 'OpenToolStripMenuItem + ' + Me.OpenToolStripMenuItem.Image = CType(resources.GetObject("OpenToolStripMenuItem.Image"), System.Drawing.Image) + Me.OpenToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.OpenToolStripMenuItem.Name = "OpenToolStripMenuItem" + Me.OpenToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.O), System.Windows.Forms.Keys) + Me.OpenToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.OpenToolStripMenuItem.Text = "&Open" + ' + 'toolStripSeparator + ' + Me.toolStripSeparator.Name = "toolStripSeparator" + Me.toolStripSeparator.Size = New System.Drawing.Size(149, 6) + ' + 'SaveToolStripMenuItem + ' + Me.SaveToolStripMenuItem.Image = CType(resources.GetObject("SaveToolStripMenuItem.Image"), System.Drawing.Image) + Me.SaveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem" + Me.SaveToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.S), System.Windows.Forms.Keys) + Me.SaveToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.SaveToolStripMenuItem.Text = "&Save" + ' + 'SaveAsToolStripMenuItem + ' + Me.SaveAsToolStripMenuItem.Name = "SaveAsToolStripMenuItem" + Me.SaveAsToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.SaveAsToolStripMenuItem.Text = "Save &As" + ' + 'toolStripSeparator1 + ' + Me.toolStripSeparator1.Name = "toolStripSeparator1" + Me.toolStripSeparator1.Size = New System.Drawing.Size(149, 6) + ' + 'PrintToolStripMenuItem + ' + Me.PrintToolStripMenuItem.Image = CType(resources.GetObject("PrintToolStripMenuItem.Image"), System.Drawing.Image) + Me.PrintToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.PrintToolStripMenuItem.Name = "PrintToolStripMenuItem" + Me.PrintToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.P), System.Windows.Forms.Keys) + Me.PrintToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.PrintToolStripMenuItem.Text = "&Print" + ' + 'PrintPreviewToolStripMenuItem + ' + Me.PrintPreviewToolStripMenuItem.Image = CType(resources.GetObject("PrintPreviewToolStripMenuItem.Image"), System.Drawing.Image) + Me.PrintPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.PrintPreviewToolStripMenuItem.Name = "PrintPreviewToolStripMenuItem" + Me.PrintPreviewToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.PrintPreviewToolStripMenuItem.Text = "Print Pre&view" + ' + 'toolStripSeparator2 + ' + Me.toolStripSeparator2.Name = "toolStripSeparator2" + Me.toolStripSeparator2.Size = New System.Drawing.Size(149, 6) + ' + 'ExitToolStripMenuItem + ' + Me.ExitToolStripMenuItem.Name = "ExitToolStripMenuItem" + Me.ExitToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.ExitToolStripMenuItem.Text = "E&xit" + ' + 'EditToolStripMenuItem + ' + Me.EditToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.UndoToolStripMenuItem, Me.RedoToolStripMenuItem, Me.toolStripSeparator3, Me.CutToolStripMenuItem, Me.CopyToolStripMenuItem, Me.PasteToolStripMenuItem, Me.toolStripSeparator4, Me.SelectAllToolStripMenuItem}) + Me.EditToolStripMenuItem.Name = "EditToolStripMenuItem" + Me.EditToolStripMenuItem.Size = New System.Drawing.Size(37, 20) + Me.EditToolStripMenuItem.Text = "&Edit" + ' + 'UndoToolStripMenuItem + ' + Me.UndoToolStripMenuItem.Name = "UndoToolStripMenuItem" + Me.UndoToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.Z), System.Windows.Forms.Keys) + Me.UndoToolStripMenuItem.Size = New System.Drawing.Size(150, 22) + Me.UndoToolStripMenuItem.Text = "&Undo" + ' + 'RedoToolStripMenuItem + ' + Me.RedoToolStripMenuItem.Name = "RedoToolStripMenuItem" + Me.RedoToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.Y), System.Windows.Forms.Keys) + Me.RedoToolStripMenuItem.Size = New System.Drawing.Size(150, 22) + Me.RedoToolStripMenuItem.Text = "&Redo" + ' + 'toolStripSeparator3 + ' + Me.toolStripSeparator3.Name = "toolStripSeparator3" + Me.toolStripSeparator3.Size = New System.Drawing.Size(147, 6) + ' + 'CutToolStripMenuItem + ' + Me.CutToolStripMenuItem.Image = CType(resources.GetObject("CutToolStripMenuItem.Image"), System.Drawing.Image) + Me.CutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.CutToolStripMenuItem.Name = "CutToolStripMenuItem" + Me.CutToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.X), System.Windows.Forms.Keys) + Me.CutToolStripMenuItem.Size = New System.Drawing.Size(150, 22) + Me.CutToolStripMenuItem.Text = "Cu&t" + ' + 'CopyToolStripMenuItem + ' + Me.CopyToolStripMenuItem.Image = CType(resources.GetObject("CopyToolStripMenuItem.Image"), System.Drawing.Image) + Me.CopyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.CopyToolStripMenuItem.Name = "CopyToolStripMenuItem" + Me.CopyToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.C), System.Windows.Forms.Keys) + Me.CopyToolStripMenuItem.Size = New System.Drawing.Size(150, 22) + Me.CopyToolStripMenuItem.Text = "&Copy" + ' + 'PasteToolStripMenuItem + ' + Me.PasteToolStripMenuItem.Image = CType(resources.GetObject("PasteToolStripMenuItem.Image"), System.Drawing.Image) + Me.PasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta + Me.PasteToolStripMenuItem.Name = "PasteToolStripMenuItem" + Me.PasteToolStripMenuItem.ShortcutKeys = CType((System.Windows.Forms.Keys.Control Or System.Windows.Forms.Keys.V), System.Windows.Forms.Keys) + Me.PasteToolStripMenuItem.Size = New System.Drawing.Size(150, 22) + Me.PasteToolStripMenuItem.Text = "&Paste" + ' + 'toolStripSeparator4 + ' + Me.toolStripSeparator4.Name = "toolStripSeparator4" + Me.toolStripSeparator4.Size = New System.Drawing.Size(147, 6) + ' + 'SelectAllToolStripMenuItem + ' + Me.SelectAllToolStripMenuItem.Name = "SelectAllToolStripMenuItem" + Me.SelectAllToolStripMenuItem.Size = New System.Drawing.Size(150, 22) + Me.SelectAllToolStripMenuItem.Text = "Select &All" + ' + 'ToolsToolStripMenuItem + ' + Me.ToolsToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.CustomizeToolStripMenuItem, Me.OptionsToolStripMenuItem}) + Me.ToolsToolStripMenuItem.Name = "ToolsToolStripMenuItem" + Me.ToolsToolStripMenuItem.Size = New System.Drawing.Size(44, 20) + Me.ToolsToolStripMenuItem.Text = "&Tools" + ' + 'CustomizeToolStripMenuItem + ' + Me.CustomizeToolStripMenuItem.Name = "CustomizeToolStripMenuItem" + Me.CustomizeToolStripMenuItem.Size = New System.Drawing.Size(134, 22) + Me.CustomizeToolStripMenuItem.Text = "&Customize" + ' + 'OptionsToolStripMenuItem + ' + Me.OptionsToolStripMenuItem.Name = "OptionsToolStripMenuItem" + Me.OptionsToolStripMenuItem.Size = New System.Drawing.Size(134, 22) + Me.OptionsToolStripMenuItem.Text = "&Options" + ' + 'HelpToolStripMenuItem + ' + Me.HelpToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ContentsToolStripMenuItem, Me.IndexToolStripMenuItem, Me.SearchToolStripMenuItem, Me.toolStripSeparator5, Me.AboutToolStripMenuItem}) + Me.HelpToolStripMenuItem.Name = "HelpToolStripMenuItem" + Me.HelpToolStripMenuItem.Size = New System.Drawing.Size(40, 20) + Me.HelpToolStripMenuItem.Text = "&Help" + ' + 'ContentsToolStripMenuItem + ' + Me.ContentsToolStripMenuItem.Name = "ContentsToolStripMenuItem" + Me.ContentsToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.ContentsToolStripMenuItem.Text = "&Contents" + ' + 'IndexToolStripMenuItem + ' + Me.IndexToolStripMenuItem.Name = "IndexToolStripMenuItem" + Me.IndexToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.IndexToolStripMenuItem.Text = "&Index" + ' + 'SearchToolStripMenuItem + ' + Me.SearchToolStripMenuItem.Name = "SearchToolStripMenuItem" + Me.SearchToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.SearchToolStripMenuItem.Text = "&Search" + ' + 'toolStripSeparator5 + ' + Me.toolStripSeparator5.Name = "toolStripSeparator5" + Me.toolStripSeparator5.Size = New System.Drawing.Size(149, 6) + ' + 'AboutToolStripMenuItem + ' + Me.AboutToolStripMenuItem.Name = "AboutToolStripMenuItem" + Me.AboutToolStripMenuItem.Size = New System.Drawing.Size(152, 22) + Me.AboutToolStripMenuItem.Text = "&About..." + ' + 'StatusStrip1 + ' + Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripStatusLabel1}) + Me.StatusStrip1.Location = New System.Drawing.Point(0, 251) + Me.StatusStrip1.Name = "StatusStrip1" + Me.StatusStrip1.Size = New System.Drawing.Size(292, 22) + Me.StatusStrip1.TabIndex = 1 + Me.StatusStrip1.Text = "StatusStrip1" + ' + 'ToolStripStatusLabel1 + ' + Me.ToolStripStatusLabel1.Name = "ToolStripStatusLabel1" + Me.ToolStripStatusLabel1.Size = New System.Drawing.Size(111, 17) + Me.ToolStripStatusLabel1.Text = "ToolStripStatusLabel1" + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(292, 273) + Me.Controls.Add(Me.StatusStrip1) + Me.Controls.Add(Me.MenuStrip1) + Me.MainMenuStrip = Me.MenuStrip1 + Me.Name = "Form1" + Me.Text = "Form1" + Me.MenuStrip1.ResumeLayout(False) + Me.MenuStrip1.PerformLayout() + Me.StatusStrip1.ResumeLayout(False) + Me.StatusStrip1.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/VB/Form1.vb new file mode 100644 index 0000000000..2b2d53a685 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripContainer/VB/Form1.vb @@ -0,0 +1,30 @@ +' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + Private tsc As ToolStripContainer + Private rtb As RichTextBox + Public Sub New() + InitializeComponent() + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Private Sub InitializeComponent() + Me.tsc = New System.Windows.Forms.ToolStripContainer() + Me.rtb = New System.Windows.Forms.RichTextBox() + Me.tsc.ContentPanel.Controls.Add(Me.rtb) + Me.Controls.Add(tsc) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb new file mode 100644 index 0000000000..be1c392513 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.ToolStripControlHost/VB/form1.vb @@ -0,0 +1,260 @@ + + +Imports System.Drawing +Imports System.Collections +Imports System.ComponentModel +Imports System.Windows.Forms +Imports System.Data + +Class Form1 + Inherits System.Windows.Forms.Form + + Private components As System.ComponentModel.IContainer = Nothing + Private textbox1 As ToolStripTextBox + + Public Sub New() + InitializeComponent() + InitializeDropDownMonthCalendar() + textbox1 = New ToolStripTextBox() + textbox1.Width = 70 + toolStrip1.Items.Add(textbox1) + InitializeDateTimePickerHost() + + End Sub + + Shared Sub Main() + Application.Run(New Form1()) + + End Sub + + Private Sub InitializeComponent() + Me.toolStrip1 = New System.Windows.Forms.ToolStrip() + Me.ToolStripPanel1 = New System.Windows.Forms.ToolStripPanel() + Me.SuspendLayout() + ' + ' toolStrip1 + ' + Me.toolStrip1.Anchor = System.Windows.Forms.AnchorStyles.Right + Me.toolStrip1.Dock = System.Windows.Forms.DockStyle.None + Me.toolStrip1.Location = New System.Drawing.Point(0, 0) + Me.toolStrip1.Name = "toolStrip1" + Me.toolStrip1.TabIndex = 1 + Me.toolStrip1.Text = "toolStrip1" + Me.toolStrip1.Visible = True + ' + ' ToolStripPanel1 + ' + Me.ToolStripPanel1.AutoSize = True + Me.ToolStripPanel1.Dock = System.Windows.Forms.DockStyle.Top + Me.ToolStripPanel1.Location = New System.Drawing.Point(9, 9) + Me.ToolStripPanel1.Name = "ToolStripPanel1" + Me.ToolStripPanel1.Orientation = System.Windows.Forms.Orientation.Horizontal + Me.ToolStripPanel1.RowMargin = New System.Windows.Forms.Padding(0) + Me.ToolStripPanel1.Size = New System.Drawing.Size(274, 25) + Me.ToolStripPanel1.TabIndex = 0 + Me.ToolStripPanel1.Text = "ToolStripPanelToolStripPanelTop" + Me.ToolStripPanel1.Join(Me.toolStrip1) + ' + ' Form1 + ' + Me.AutoSize = True + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Controls.Add(ToolStripPanel1) + Me.Name = "Form1" + Me.Padding = New System.Windows.Forms.Padding(9) + Me.Text = "Form1" + Me.ResumeLayout(False) + Me.PerformLayout() + + End Sub + + + ' + ' Clean up any resources being used. + ' + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + If disposing Then + If (components IsNot Nothing) Then + components.Dispose() + End If + End If + MyBase.Dispose(disposing) + + End Sub + + Private toolStrip1 As System.Windows.Forms.ToolStrip + Private ToolStripPanel1 As System.Windows.Forms.ToolStripPanel + + ' The following snippet demonstrates the ToolStripControlHost(Control) + ' constructor, the ToolStripControlHost.Font, Width, DisplayStyle, + ' Text properties. + ' + Private dateTimePickerHost As ToolStripControlHost + + + Private Sub InitializeDateTimePickerHost() + + ' Create a new ToolStripControlHost, passing in a control. + dateTimePickerHost = New ToolStripControlHost(New DateTimePicker()) + + ' Set the font on the ToolStripControlHost, this will affect the hosted control. + dateTimePickerHost.Font = New Font("Arial", 7.0F, FontStyle.Italic) + + ' Set the Width property, this will also affect the hosted control. + dateTimePickerHost.Width = 100 + dateTimePickerHost.DisplayStyle = ToolStripItemDisplayStyle.Text + + ' Setting the Text property requires a string that converts to a + ' DateTime type since that is what the hosted control requires. + dateTimePickerHost.Text = "12/23/2005" + + ' Cast the Control property back to the original type to set a + ' type-specific property. + CType(dateTimePickerHost.Control, DateTimePicker).Format = DateTimePickerFormat.Short + + ' Add the control host to the ToolStrip. + toolStrip1.Items.Add(dateTimePickerHost) + + End Sub + ' + + ' The following example shows how to set the custom + ' ToolStripMonthCalendar control. + ' + Dim WithEvents monthCalendar As ToolStripMonthCalendar + + Private Sub InitializeDropDownMonthCalendar() + + ' Declare the drop-down button and the drop-down. + Dim dropDownButton2 As New ToolStripDropDownButton() + + ' Set the image to the MonthCalendar embedded bitmap + ' image. + dropDownButton2.Image = New Bitmap(GetType(MonthCalendar), "MonthCalendar.bmp") + + ' Add the button to the ToolStrip. + toolStrip1.Items.Add(dropDownButton2) + + ' Construct a new drop-down. + Dim dropDown As New ToolStripDropDown() + + ' Construct a new wrapped MonthCalendar control. + monthCalendar = New ToolStripMonthCalendar() + + ' Set a date in boldface. + monthCalendar.AddBoldedDate(DateTime.Today.AddDays(7)) + + 'Add the calendar to the drop-down. + dropDown.Items.Add(monthCalendar) + + 'Set the drop-down on the DropDownButton. + dropDownButton2.DropDown = dropDown + + End Sub + + + Public Sub monthCalendar_DateChanged( _ + ByVal sender As Object, _ + ByVal e As DateRangeEventArgs) _ + Handles monthCalendar.DateChanged + + textbox1.Text = e.Start.ToShortDateString() + + End Sub + ' + +End Class + +' The following example shows how to wrap a control +' using ToolStripControlHost. +' +'Declare a class that inherits from ToolStripControlHost. + +Public Class ToolStripMonthCalendar + Inherits ToolStripControlHost + + ' + ' Call the base constructor passing in a MonthCalendar instance. + Public Sub New() + MyBase.New(New MonthCalendar()) + + End Sub + ' + + ' + Public ReadOnly Property MonthCalendarControl() As MonthCalendar + Get + Return CType(Control, MonthCalendar) + End Get + End Property + ' + + ' + ' Expose the MonthCalendar.FirstDayOfWeek as a property. + Public Property FirstDayOfWeek() As Day + Get + Return MonthCalendarControl.FirstDayOfWeek + End Get + Set + MonthCalendarControl.FirstDayOfWeek = value + End Set + End Property + + ' Expose the AddBoldedDate method. + Public Sub AddBoldedDate(ByVal dateToBold As DateTime) + MonthCalendarControl.AddBoldedDate(dateToBold) + + End Sub + ' + + ' Subscribe and unsubscribe the control events you wish to expose. + ' + ' + Protected Overrides Sub OnSubscribeControlEvents(ByVal c As Control) + + ' Call the base so the base events are connected. + MyBase.OnSubscribeControlEvents(c) + + ' Cast the control to a MonthCalendar control. + Dim monthCalendarControl As MonthCalendar = _ + CType(c, MonthCalendar) + + ' Add the event. + AddHandler monthCalendarControl.DateChanged, _ + AddressOf HandleDateChanged + + End Sub + ' + + ' + Protected Overrides Sub OnUnsubscribeControlEvents(ByVal c As Control) + ' Call the base method so the basic events are unsubscribed. + MyBase.OnUnsubscribeControlEvents(c) + + ' Cast the control to a MonthCalendar control. + Dim monthCalendarControl As MonthCalendar = _ + CType(c, MonthCalendar) + + ' Remove the event. + RemoveHandler monthCalendarControl.DateChanged, _ + AddressOf HandleDateChanged + + End Sub + ' + ' + + ' + ' Declare the DateChanged event. + Public Event DateChanged As DateRangeEventHandler + + ' Raise the DateChanged event. + Private Sub HandleDateChanged(ByVal sender As Object, _ + ByVal e As DateRangeEventArgs) + + RaiseEvent DateChanged(Me, e) + End Sub +End Class +' +' +' + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/VB/form1.vb new file mode 100644 index 0000000000..a43b0be657 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.UserInputWalkthrough/VB/form1.vb @@ -0,0 +1,603 @@ +' User Input Test Application for new Windows Forms user input conceptual topics +' in Visual Studio 2005 documentation. + +' +Imports System.Drawing +Imports System.ComponentModel +Imports System.Windows.Forms + +Namespace UserInputWalkthrough + + Public Class Form1 + Inherits Form + + Dim Label1 As New Label + Dim Label2 As New Label + Dim TextBoxOutput As New TextBox + Dim WithEvents TextBoxInput As New TextBox + Dim WithEvents GroupBoxEvents As New GroupBox + Dim WithEvents ButtonClear As New Button + Dim WithEvents LinkLabelDrag As New LinkLabel + + Dim WithEvents CheckBoxToggleAll As New CheckBox + Dim WithEvents CheckBoxMouse As New CheckBox + Dim WithEvents CheckBoxMouseEnter As New CheckBox + Dim WithEvents CheckBoxMouseMove As New CheckBox + Dim WithEvents CheckBoxMousePoints As New CheckBox + Dim WithEvents CheckBoxMouseDrag As New CheckBox + Dim WithEvents CheckBoxMouseDragOver As New CheckBox + Dim WithEvents CheckBoxKeyboard As New CheckBox + Dim WithEvents CheckBoxKeyUpDown As New CheckBox + Dim WithEvents CheckBoxFocus As New CheckBox + Dim WithEvents CheckBoxValidation As New CheckBox + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + MyBase.New() + End Sub + + Private Sub Form1_Load(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles MyBase.Load + + Me.GroupBoxEvents.SuspendLayout() + Me.SuspendLayout() + + Label1.Location = New Point(232, 12) + Label1.Size = New Size(98, 14) + Label1.AutoSize = True + Label1.Text = "Generated Events:" + + Label2.Location = New Point(13, 12) + Label2.Size = New Size(95, 14) + Label2.AutoSize = True + Label2.Text = "User Input Target:" + + TextBoxInput.Location = New Point(13, 34) + TextBoxInput.Size = New Size(200, 200) + TextBoxInput.AllowDrop = True + TextBoxInput.AutoSize = False + TextBoxInput.Cursor = Cursors.Cross + TextBoxInput.Multiline = True + TextBoxInput.TabIndex = 1 + + LinkLabelDrag.AllowDrop = True + LinkLabelDrag.AutoSize = True + LinkLabelDrag.Location = New Point(13, 240) + LinkLabelDrag.Size = New Size(175, 14) + LinkLabelDrag.TabIndex = 2 + LinkLabelDrag.TabStop = True + LinkLabelDrag.Text = "Click here to use as a drag source" + LinkLabelDrag.Links.Add(New LinkLabel.Link(0, _ + LinkLabelDrag.Text.Length)) + + GroupBoxEvents.Location = New Point(13, 281) + GroupBoxEvents.Size = New Size(200, 302) + GroupBoxEvents.TabIndex = 3 + GroupBoxEvents.TabStop = False + GroupBoxEvents.Text = "Event Filter:" + GroupBoxEvents.Controls.Add(CheckBoxMouseEnter) + GroupBoxEvents.Controls.Add(CheckBoxToggleAll) + GroupBoxEvents.Controls.Add(CheckBoxMousePoints) + GroupBoxEvents.Controls.Add(CheckBoxKeyUpDown) + GroupBoxEvents.Controls.Add(CheckBoxMouseDragOver) + GroupBoxEvents.Controls.Add(CheckBoxMouseDrag) + GroupBoxEvents.Controls.Add(CheckBoxValidation) + GroupBoxEvents.Controls.Add(CheckBoxMouseMove) + GroupBoxEvents.Controls.Add(CheckBoxFocus) + GroupBoxEvents.Controls.Add(CheckBoxKeyboard) + GroupBoxEvents.Controls.Add(CheckBoxMouse) + + CheckBoxToggleAll.AutoSize = True + CheckBoxToggleAll.Location = New Point(7, 20) + CheckBoxToggleAll.Size = New Size(122, 17) + CheckBoxToggleAll.TabIndex = 4 + CheckBoxToggleAll.Text = "Toggle All Events" + + CheckBoxMouse.AutoSize = True + CheckBoxMouse.Location = New Point(7, 45) + CheckBoxMouse.Size = New Size(137, 17) + CheckBoxMouse.TabIndex = 5 + CheckBoxMouse.Text = "Mouse and Click Events" + + CheckBoxMouseEnter.AutoSize = True + CheckBoxMouseEnter.Location = New Point(26, 69) + CheckBoxMouseEnter.Margin = New Padding(3, 3, 3, 1) + CheckBoxMouseEnter.Size = New System.Drawing.Size(151, 17) + CheckBoxMouseEnter.TabIndex = 6 + CheckBoxMouseEnter.Text = "Mouse Enter/Hover/Leave" + + CheckBoxMouseMove.AutoSize = True + CheckBoxMouseMove.Location = New Point(26, 89) + CheckBoxMouseMove.Margin = New Padding(3, 2, 3, 3) + CheckBoxMouseMove.Size = New Size(120, 17) + CheckBoxMouseMove.TabIndex = 7 + CheckBoxMouseMove.Text = "Mouse Move Events" + + CheckBoxMousePoints.AutoSize = True + CheckBoxMousePoints.Location = New Point(26, 112) + CheckBoxMousePoints.Margin = New Padding(3, 3, 3, 1) + CheckBoxMousePoints.Size = New Size(141, 17) + CheckBoxMousePoints.TabIndex = 8 + CheckBoxMousePoints.Text = "Draw Mouse Points" + + CheckBoxMouseDrag.AutoSize = True + CheckBoxMouseDrag.Location = New Point(26, 135) + CheckBoxMouseDrag.Margin = New Padding(3, 1, 3, 3) + CheckBoxMouseDrag.Size = New Size(151, 17) + CheckBoxMouseDrag.TabIndex = 9 + CheckBoxMouseDrag.Text = "Mouse Drag && Drop Events" + + CheckBoxMouseDragOver.AutoSize = True + CheckBoxMouseDragOver.Location = New Point(44, 159) + CheckBoxMouseDragOver.Size = New Size(142, 17) + CheckBoxMouseDragOver.TabIndex = 10 + CheckBoxMouseDragOver.Text = "Mouse Drag Over Events" + + CheckBoxKeyboard.AutoSize = True + CheckBoxKeyboard.Location = New Point(8, 184) + CheckBoxKeyboard.Size = New Size(103, 17) + CheckBoxKeyboard.TabIndex = 11 + CheckBoxKeyboard.Text = "Keyboard Events" + + CheckBoxKeyUpDown.AutoSize = True + CheckBoxKeyUpDown.Location = New Point(26, 207) + CheckBoxKeyUpDown.Margin = New Padding(3, 3, 3, 1) + CheckBoxKeyUpDown.Size = New Size(133, 17) + CheckBoxKeyUpDown.TabIndex = 12 + CheckBoxKeyUpDown.Text = "Key Up && Down Events" + + CheckBoxFocus.AutoSize = True + CheckBoxFocus.Location = New Point(8, 233) + CheckBoxFocus.Margin = New Padding(3, 2, 3, 3) + CheckBoxFocus.Size = New Size(146, 17) + CheckBoxFocus.TabIndex = 13 + CheckBoxFocus.Text = "Focus && Activation Events" + + CheckBoxValidation.AutoSize = True + CheckBoxValidation.Location = New Point(8, 257) + CheckBoxValidation.Size = New Size(104, 17) + CheckBoxValidation.TabIndex = 14 + CheckBoxValidation.Text = "Validation Events" + + TextBoxOutput.Location = New Point(232, 34) + TextBoxOutput.Size = New Size(308, 510) + TextBoxOutput.Multiline = True + TextBoxOutput.CausesValidation = False + TextBoxOutput.ReadOnly = True + TextBoxOutput.ScrollBars = ScrollBars.Vertical + TextBoxOutput.TabIndex = 15 + TextBoxOutput.WordWrap = False + + ButtonClear.Location = New Point(232, 560) + ButtonClear.Size = New Size(308, 23) + ButtonClear.TabIndex = 16 + ButtonClear.Text = "Clear Event List" + + Me.ClientSize = New Size(552, 595) + Me.Controls.Add(LinkLabelDrag) + Me.Controls.Add(ButtonClear) + Me.Controls.Add(GroupBoxEvents) + Me.Controls.Add(Label1) + Me.Controls.Add(Label2) + Me.Controls.Add(TextBoxInput) + Me.Controls.Add(TextBoxOutput) + Me.Text = "User Input Events" + + Me.GroupBoxEvents.ResumeLayout(False) + Me.GroupBoxEvents.PerformLayout() + Me.ResumeLayout(False) + Me.PerformLayout() + CheckAllChildCheckBoxes(Me, True) + End Sub + + ' Recursively search the form for all contained checkboxes and + ' initially check them + Private Sub CheckAllChildCheckBoxes(ByRef parent As Control, _ + ByVal value As Boolean) + + Dim currentControl As Control + Dim box As CheckBox + For Each currentControl In parent.Controls + box = TryCast(currentControl, CheckBox) + If box IsNot Nothing Then + box.Checked = value + End If + + 'Recurse if control contains other controls + If currentControl.Controls.Count > 0 Then + CheckAllChildCheckBoxes(currentControl, value) + End If + Next + End Sub + + ' All-purpose method for displaying a line of text in one of the + ' text boxes. + Private Sub DisplayLine(ByRef line As String) + + TextBoxOutput.AppendText(line) + TextBoxOutput.AppendText(ControlChars.NewLine) + End Sub + + ' Click event handler for the button that clears the text box. + Private Sub ButtonClear_Click(ByVal sender As Object, _ + ByVal e As System.EventArgs) Handles ButtonClear.Click + + TextBoxOutput.Invalidate() + TextBoxOutput.Clear() + End Sub + + Private Sub TextBoxInput_KeyDown(ByVal sender As Object, _ + ByVal e As KeyEventArgs) Handles TextBoxInput.KeyDown + + If CheckBoxKeyUpDown.Checked = True Then + DisplayLine("KeyDown: " + e.KeyData.ToString()) + End If + End Sub + + Private Sub TextBoxInput_KeyUp(ByVal sender As Object, _ + ByVal e As KeyEventArgs) Handles TextBoxInput.KeyUp + + If CheckBoxKeyUpDown.Checked = True Then + DisplayLine("KeyUp: " + e.KeyData.ToString()) + End If + End Sub + + Private Sub TextBoxInput_KeyPress(ByVal sender As Object, _ + ByVal e As KeyPressEventArgs) Handles TextBoxInput.KeyPress + + If CheckBoxKeyboard.Checked = True Then + + If Char.IsWhiteSpace(e.KeyChar) Then + Dim keyVal As Integer + keyVal = AscW(e.KeyChar) + DisplayLine("KeyPress: WS-" + keyVal.ToString()) + Else + DisplayLine("KeyPress: " + e.KeyChar.ToString()) + End If + End If + End Sub + + Private Sub TextBoxInput_Click(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.Click + + If CheckBoxMouse.Checked = True Then + DisplayLine("Click event") + End If + End Sub + + Private Sub TextBoxInput_DoubleClick(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.DoubleClick + + If CheckBoxMouse.Checked = True Then + DisplayLine("DoubleClick event") + End If + End Sub + + Private Sub TextBoxInput_MouseClick(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles TextBoxInput.MouseClick + + If CheckBoxMouse.Checked = True Then + DisplayLine("MouseClick: " + e.Button.ToString() + _ + " " + e.Location.ToString()) + End If + End Sub + + Private Sub TextBoxInput_MouseDoubleClick(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles TextBoxInput.MouseDoubleClick + + If CheckBoxMouse.Checked = True Then + DisplayLine("MouseDoubleClick: " + e.Button.ToString() + _ + " " + e.Location.ToString()) + End If + End Sub + + Private Sub TextBoxInput_MouseDown(ByVal sender As System.Object, _ + ByVal e As MouseEventArgs) Handles TextBoxInput.MouseDown + + If CheckBoxMouse.Checked = True Then + DisplayLine("MouseDown: " + e.Button.ToString() + _ + " " + e.Location.ToString()) + End If + End Sub + + Private Sub TextBoxInput_MouseUp(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles TextBoxInput.MouseUp + + If CheckBoxMouse.Checked = True Then + DisplayLine("MouseUp: " + e.Button.ToString() + _ + " " + e.Location.ToString()) + End If + + ' The TextBox control was designed to change focus only on + ' the primary click, so force focus to avoid user confusion. + If TextBoxInput.Focused = False Then + TextBoxInput.Focus() + End If + End Sub + + Private Sub TextBoxInput_MouseEnter(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.MouseEnter + + If CheckBoxMouseEnter.Checked = True Then + DisplayLine("MouseEnter event") + End If + End Sub + + Private Sub TextBoxInput_MouseHover(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.MouseHover + + If CheckBoxMouseEnter.Checked = True Then + DisplayLine("MouseHover event") + End If + End Sub + + Private Sub TextBoxInput_MouseLeave(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.MouseLeave + + If CheckBoxMouseEnter.Checked = True Then + DisplayLine("MouseLeave event") + End If + End Sub + + Private Sub TextBoxInput_MouseWheel(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles TextBoxInput.MouseWheel + + If CheckBoxMouse.Checked = True Then + DisplayLine("MouseWheel: " + e.Delta.ToString() + _ + " detents at " + e.Location.ToString()) + End If + End Sub + + Private Sub TextBoxInput_MouseMove(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles TextBoxInput.MouseMove + + If CheckBoxMouseMove.Checked = True Then + DisplayLine("MouseMove: " + e.Button.ToString() + " " + _ + e.Location.ToString()) + End If + + If CheckBoxMousePoints.Checked = True Then + Dim g As Graphics = TextBoxInput.CreateGraphics() + g.FillRectangle(Brushes.Black, e.Location.X, _ + e.Location.Y, 1, 1) + g.Dispose() + End If + End Sub + + Private Sub TextBoxInput_MouseCaptureChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles TextBoxInput.MouseCaptureChanged + + If CheckBoxMouseDrag.Checked = True Then + DisplayLine("MouseCaptureChanged event") + End If + End Sub + + Private Sub TextBoxInput_DragEnter(ByVal sender As Object, _ + ByVal e As DragEventArgs) Handles TextBoxInput.DragEnter + + Dim pt As Point + If CheckBoxMouseDrag.Checked = True Then + pt = New Point(e.X, e.Y) + DisplayLine("DragEnter: " + _ + CovertKeyStateToString(e.KeyState) _ + + " at " + pt.ToString()) + End If + End Sub + + Private Sub TextBoxInput_DragDrop(ByVal sender As Object, _ + ByVal e As DragEventArgs) Handles TextBoxInput.DragDrop + + If CheckBoxMouseDrag.Checked = True Then + Dim pt As Point + pt = New Point(e.X, e.Y) + + DisplayLine("DragDrop: " + _ + CovertKeyStateToString(e.KeyState) _ + + " at " + pt.ToString()) + End If + End Sub + + Private Sub TextBoxInput_DragOver(ByVal sender As Object, _ + ByVal e As DragEventArgs) Handles TextBoxInput.DragOver + + If CheckBoxMouseDragOver.Checked = True Then + Dim pt As Point + pt = New Point(e.X, e.Y) + DisplayLine("DragOver: " + _ + CovertKeyStateToString(e.KeyState) _ + + " at " + pt.ToString()) + End If + + ' Allow if drop data is of type string. + If Not (e.Data.GetDataPresent(GetType(String))) Then + e.Effect = DragDropEffects.None + Else + e.Effect = DragDropEffects.Copy + End If + End Sub + + Private Sub TextBoxInput_DragLeave(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.DragLeave + + If CheckBoxMouseDrag.Checked = True Then + DisplayLine("DragLeave event") + End If + End Sub + + Private Function CovertKeyStateToString(ByVal keyState As Integer) _ + As String + + Dim keyString As String = "None" + + ' Which button was pressed? + If ((keyState And 1) = 1) Then + keyString = "Left" + ElseIf ((keyState And 2) = 2) Then + keyString = "Right" + ElseIf ((keyState And 16) = 16) Then + keyString = "Middle" + End If + + ' Are one or more modifier keys also pressed? + If ((keyState And 4) = 4) Then + keyString += "+SHIFT" + End If + If ((keyState And 8) = 8) Then + keyString += "+CTRL" + End If + If ((keyState And 32) = 32) Then + keyString += "+ALT" + End If + + Return keyString + End Function + + Private Sub TextBoxInput_Enter(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.Enter + + If CheckBoxFocus.Checked = True Then + DisplayLine("Enter event") + End If + End Sub + + Private Sub TextBoxInput_Leave(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.Leave + + If CheckBoxFocus.Checked = True Then + DisplayLine("Leave event") + End If + End Sub + + Private Sub TextBoxInput_GotFocus(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.GotFocus + + If CheckBoxFocus.Checked = True Then + DisplayLine("GotFocus event") + End If + End Sub + + Private Sub TextBoxInput_LostFocus(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.LostFocus + + If CheckBoxFocus.Checked = True Then + DisplayLine("LostFocus event") + End If + End Sub + + Private Sub TextBoxInput_Validated(ByVal sender As Object, _ + ByVal e As EventArgs) Handles TextBoxInput.Validated + + If CheckBoxValidation.Checked = True Then + DisplayLine("Validated event") + End If + End Sub + + Private Sub TextBoxInput_Validating(ByVal sender As Object, _ + ByVal e As CancelEventArgs) _ + Handles TextBoxInput.Validating + + If CheckBoxValidation.Checked = True Then + DisplayLine("Validating event") + End If + End Sub + + Private Sub CheckBoxToggleAll_CheckedChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles CheckBoxToggleAll.CheckedChanged + + Dim cb As CheckBox + cb = TryCast(sender, CheckBox) + If cb IsNot Nothing Then + CheckAllChildCheckBoxes(Me, cb.Checked) + End If + End Sub + + Private Sub CheckBoxMouse_CheckedChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles CheckBoxMouse.CheckedChanged + + ConfigureCheckBoxSettings() + End Sub + + Private Sub CheckBoxMouseDrag_CheckedChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles CheckBoxMouseDrag.CheckedChanged + + ConfigureCheckBoxSettings() + End Sub + + Private Sub CheckBoxKeyboard_CheckedChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles CheckBoxKeyboard.CheckedChanged + + ConfigureCheckBoxSettings() + End Sub + + Private Sub CheckBoxMouseMove_CheckedChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles CheckBoxMouseEnter.CheckedChanged, _ + CheckBoxMouseMove.CheckedChanged + + ConfigureCheckBoxSettings() + End Sub + + ' Reconcile dependencies between the check box + ' selection choices. + Private Sub ConfigureCheckBoxSettings() + + ' CheckBoxMouse is a top-level check box. + If CheckBoxMouse.Checked = False Then + CheckBoxMouseEnter.Enabled = False + CheckBoxMouseMove.Enabled = False + CheckBoxMouseDrag.Enabled = False + CheckBoxMouseDragOver.Enabled = False + CheckBoxMousePoints.Enabled = False + Else + CheckBoxMouseEnter.Enabled = True + CheckBoxMouseMove.Enabled = True + CheckBoxMouseDrag.Enabled = True + CheckBoxMousePoints.Enabled = True + + ' Enable children depending on the state of the parent. + If CheckBoxMouseDrag.Checked = False Then + CheckBoxMouseDragOver.Enabled = False + Else + CheckBoxMouseDragOver.Enabled = True + End If + End If + + If CheckBoxKeyboard.Checked = False Then + CheckBoxKeyUpDown.Enabled = False + Else + CheckBoxKeyUpDown.Enabled = True + End If + End Sub + + Private Sub LinkLabelDrag_MouseDown(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles LinkLabelDrag.MouseDown + + Dim data As String = "Sample Data" + LinkLabelDrag.DoDragDrop(data, DragDropEffects.All) + End Sub + + Private Sub LinkLabelDrag_GiveFeedback(ByVal sender As Object, _ + ByVal e As GiveFeedbackEventArgs) _ + Handles LinkLabelDrag.GiveFeedback + + If ((e.Effect And DragDropEffects.Copy) = _ + DragDropEffects.Copy) Then + LinkLabelDrag.Cursor = Cursors.HSplit + Else + LinkLabelDrag.Cursor = Cursors.Default + End If + End Sub + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer/VB/form1.vb new file mode 100644 index 0000000000..8a9ca37b30 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer/VB/form1.vb @@ -0,0 +1,391 @@ +' This sample might go in a VisualStyleRenderer conceptual topic, or the VisualStyleRenderer +' class itself. The sample defines a custom control that imitates a window using VisualStyleElements +' for the window parts. It handles resizing and moving the window. + +' This sample uses the following VisualStyleRenderer members: +' Snippet10: VisualStyleRenderer.GetPartSize (with ThemeSizeType.True) +' Snippet10: VisualStyleRenderer.GetPoint (with PointProperty.Offset) +' Snippet20: VisualStyleRenderer.DrawBackground +' Snippet30: VisualStyleRenderer.GetBackgroundRegion +' Snippet40: VisualStyleRenderer.IsElementDefined +' Snippet40: VisualStyleRenderer(VisualStyleElement) constructor +' Snippet40: VisualStyleRenderer.SetParameters + +' Work Items: - Try to make HitTestBackground method work in MouseDown event handler. +' - Why does the offset value obtained for the close button make it draw a bit +' too far to the right? +' - Right now I'm hard-coding the height of the status bar rect to 22, which +' visual matches the standard Windows version. Doing GetPartSize on this +' part only returns a height of 15, which is way to short; is this a bug? + +' +Imports System.Text +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Collections.Generic +Imports System.Windows.Forms +Imports System.Windows.Forms.VisualStyles + +Namespace VisualStyleRendererSample + + Class Form1 + Inherits Form + + Public Sub New() + With Me + .Size = New Size(800, 600) + .Location = New Point(20, 20) + .BackColor = Color.DarkGray + End With + Dim Window1 As New ImitationWindow() + Controls.Add(Window1) + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + End Class + + Public Class ImitationWindow + Inherits Control + + Private windowElements As _ + New Dictionary(Of String, VisualStyleElement) + Private elementRectangles As _ + New Dictionary(Of String, Rectangle) + Private renderer As VisualStyleRenderer = Nothing + Private closeButtonOffset As Point + Private gripperSize As Size + Private closeButtonSize As Size + Private isResizing As Boolean = False + Private isMoving As Boolean = False + Private isClosing As Boolean = False + Private captionHeight As Integer + Private frameThickness As Integer + Private statusHeight As Integer = 22 + Private originalClick As New Point() + Private resizeOffset As New Point() + + Public Sub New() + With Me + .Location = New Point(50, 50) + .Size = New Size(350, 300) + .BackColor = Color.Azure + .DoubleBuffered = True + .MinimumSize = New Size(300, 200) + .Font = SystemFonts.CaptionFont + .Text = "Imitation Window" + End With + + ' Create a collection of VisualStyleElement objects. + With windowElements + .Add("windowCaption", _ + VisualStyleElement.Window.Caption.Active) + .Add("windowBottom", _ + VisualStyleElement.Window.FrameBottom.Active) + .Add("windowLeft", _ + VisualStyleElement.Window.FrameLeft.Active) + .Add("windowRight", _ + VisualStyleElement.Window.FrameRight.Active) + .Add("windowClose", _ + VisualStyleElement.Window.CloseButton.Normal) + .Add("statusBar", _ + VisualStyleElement.Status.Bar.Normal) + .Add("statusGripper", _ + VisualStyleElement.Status.Gripper.Normal) + End With + + ' Get the sizes and location offsets for the window parts + ' as specified by the visual style, and then use this + ' information to calcualate the rectangles for each part. + GetPartDetails() + CalculateRectangles() + End Sub + + ' + ' Get the sizes and offsets for the window parts as specified + ' by the visual style. + Private Sub GetPartDetails() + ' Do nothing further if visual styles are not enabled. + If Not Application.RenderWithVisualStyles Then + Return + End If + + Using g As Graphics = Me.CreateGraphics() + ' Get the size and offset of the close button. + If SetRenderer(windowElements("windowClose")) Then + closeButtonSize = _ + renderer.GetPartSize(g, ThemeSizeType.True) + closeButtonOffset = _ + renderer.GetPoint(PointProperty.Offset) + End If + + ' Get the height of the window caption. + If SetRenderer(windowElements("windowCaption")) Then + captionHeight = renderer.GetPartSize(g, _ + ThemeSizeType.True).Height + End If + + ' Get the thickness of the left, bottom, and right + ' window frame. + If SetRenderer(windowElements("windowLeft")) Then + frameThickness = renderer.GetPartSize(g, _ + ThemeSizeType.True).Width + End If + + ' Get the size of the resizing gripper. + If SetRenderer(windowElements("statusGripper")) Then + gripperSize = renderer.GetPartSize(g, _ + ThemeSizeType.True) + End If + End Using + End Sub + ' + + ' Use the part metrics to determine the current size of the + ' rectangles for all of the window parts. + Private Sub CalculateRectangles() + + Dim heightMinusFrame As Integer = _ + ClientRectangle.Height - frameThickness + + ' Calculate the window frame rectangles and add them + ' to the Dictionary of rectangles. + elementRectangles("windowCaption") = _ + New Rectangle(0, 0, ClientRectangle.Width, _ + captionHeight) + elementRectangles("windowBottom") = _ + New Rectangle(0, heightMinusFrame, _ + ClientRectangle.Width, frameThickness) + elementRectangles("windowLeft") = _ + New Rectangle(0, captionHeight, frameThickness, _ + heightMinusFrame - captionHeight) + elementRectangles("windowRight") = _ + New Rectangle(ClientRectangle.Width - frameThickness, _ + captionHeight, frameThickness, _ + heightMinusFrame - captionHeight) + + ' Calculate the window button rectangle and add it + ' to the Dictionary of rectangles. + elementRectangles("windowClose") = _ + New Rectangle(ClientRectangle.Right + _ + closeButtonOffset.X, closeButtonOffset.Y, _ + closeButtonSize.Width, closeButtonSize.Height) + + ' Calculate the status bar rectangles and add them + ' to the Dictionary of rectangles. + elementRectangles("statusBar") = _ + New Rectangle(frameThickness, _ + heightMinusFrame - statusHeight, _ + ClientRectangle.Width - 2 * frameThickness, _ + statusHeight) + elementRectangles("statusGripper") = _ + New Rectangle(ClientRectangle.Right - _ + gripperSize.Width - frameThickness, _ + heightMinusFrame - gripperSize.Height, _ + gripperSize.Width, gripperSize.Height) + End Sub + + ' + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + MyBase.OnPaint(e) + + ' Ensure that visual styles are supported. + If Not Application.RenderWithVisualStyles Then + Me.Text = "Visual styles are not enabled." + TextRenderer.DrawText(e.Graphics, Me.Text, Me.Font, _ + Me.Location, Me.ForeColor) + Return + End If + + ' Set the clip region to define the curved corners of + ' the caption. + SetClipRegion() + + ' Draw each part of the window. + Dim entry As KeyValuePair(Of String, VisualStyleElement) + For Each entry In windowElements + If SetRenderer(entry.Value) Then + renderer.DrawBackground(e.Graphics, _ + elementRectangles(entry.Key)) + End If + Next entry + + ' Draw the caption text. + TextRenderer.DrawText(e.Graphics, Me.Text, Me.Font, _ + elementRectangles("windowCaption"), Color.White, _ + TextFormatFlags.VerticalCenter Or _ + TextFormatFlags.HorizontalCenter) + End Sub + ' + + ' Initiate dragging, resizing, or closing the imitation window. + Private Sub ImitationWindow_MouseDown(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles Me.MouseDown + + ' The user clicked the close button. + If elementRectangles("windowClose"). _ + Contains(e.Location) Then + + windowElements("windowClose") = _ + VisualStyleElement.Window.CloseButton.Pressed + isClosing = True + + ' The user clicked the status grip. + ElseIf elementRectangles("statusGripper"). _ + Contains(e.Location) Then + + isResizing = True + Me.Cursor = Cursors.SizeNWSE + resizeOffset.X = Me.Right - Me.Left - e.X + resizeOffset.Y = Me.Bottom - Me.Top - e.Y + + ' The user clicked the window caption. + ElseIf elementRectangles("windowCaption"). _ + Contains(e.Location) Then + + isMoving = True + originalClick.X = e.X + originalClick.Y = e.Y + End If + Invalidate() + End Sub + + ' Stop any current resizing or moving actions. + Private Sub ImitationWindow_MouseUp(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles Me.MouseUp + + ' Stop moving the location of the window rectangles. + If isMoving Then + isMoving = False + + ' Change the cursor back to the default if the + ' user stops resizing. + ElseIf isResizing Then + isResizing = False + + ' Close the application if the user clicks the + ' close button. + ElseIf elementRectangles("windowClose"). _ + Contains(e.Location) And isClosing Then + Application.Exit() + End If + End Sub + + ' Handle resizing or moving actions. + Private Sub ImitationWindow_MouseMove(ByVal sender As Object, _ + ByVal e As MouseEventArgs) Handles Me.MouseMove + + ' The left mouse button is down. + If (MouseButtons.Left And e.Button) = _ + MouseButtons.Left Then + + ' Calculate the new control size if the user is + ' dragging the resizing grip. + If isResizing Then + Me.Width = e.X + resizeOffset.X + Me.Height = e.Y + resizeOffset.Y + CalculateRectangles() + + ' Calculate the new location of the control if + ' the user is dragging the window caption. + ElseIf isMoving Then + Dim XChange As Integer = Me.Location.X + _ + (e.X - originalClick.X) + Dim YChange As Integer = Me.Location.Y + _ + (e.Y - originalClick.Y) + Me.Location = New Point(XChange, YChange) + + ' Cancel the closing action if the user clicked and + ' held down on the close button, and has dragged the + ' pointer outside the button. + ElseIf Not elementRectangles("windowClose"). _ + Contains(e.Location) And isClosing Then + + isClosing = False + windowElements("windowClose") = _ + VisualStyleElement.Window.CloseButton.Normal + End If + + ' The left mouse button is not down. + Else + ' Paint the close button hot if the cursor is on it. + If elementRectangles("windowClose"). _ + Contains(e.Location) Then + windowElements("windowClose") = _ + VisualStyleElement.Window.CloseButton.Hot + Else + windowElements("windowClose") = _ + VisualStyleElement.Window.CloseButton.Normal + End If + + ' Use a resizing cursor if the cursor is on the + ' status grip. + If elementRectangles("statusGripper"). _ + Contains(e.Location) Then + Me.Cursor = Cursors.SizeNWSE + Else + Me.Cursor = Cursors.Default + End If + End If + Invalidate() + End Sub + + ' + ' Calculate and set the clipping region for the control + ' so that the corners of the title bar are rounded. + Private Sub SetClipRegion() + If Not Application.RenderWithVisualStyles Then + Return + End If + + Using g As Graphics = Me.CreateGraphics() + ' Get the current region for the window caption. + If SetRenderer(windowElements("windowCaption")) Then + Dim clipRegion As Region = _ + renderer.GetBackgroundRegion(g, _ + elementRectangles("windowCaption")) + + ' Get the client rectangle, but exclude the + ' region of the window caption. + Dim height As Integer = _ + CInt(clipRegion.GetBounds(g).Height) + Dim nonCaptionRect As _ + New Rectangle(ClientRectangle.X, _ + ClientRectangle.Y + height, _ + ClientRectangle.Width, _ + ClientRectangle.Height - height) + + ' Add the rectangle to the caption region, and + ' make this region the form's clipping region. + clipRegion.Union(nonCaptionRect) + Me.Region = clipRegion + End If + End Using + End Sub + ' + + ' + ' Set the VisualStyleRenderer to a new element. + Private Function SetRenderer(ByVal element As _ + VisualStyleElement) As Boolean + + If Not VisualStyleRenderer.IsElementDefined(element) Then + Return False + End If + + If renderer Is Nothing Then + renderer = New VisualStyleRenderer(element) + Else + renderer.SetParameters(element) + End If + + Return True + End Function + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/VB/form1.vb new file mode 100644 index 0000000000..a7926504a3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleRenderer_Simple/VB/form1.vb @@ -0,0 +1,60 @@ +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.VisualStyles + +Namespace SimpleVisualStyleRendererSample + + Class Form1 + Inherits Form + + Public Sub New() + Me.Size = New Size(400, 400) + Me.BackColor = Color.WhiteSmoke + Me.Controls.Add(New CustomControl()) + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + End Class + + Public Class CustomControl + Inherits Control + + ' + Private renderer As VisualStyleRenderer = Nothing + Private element As VisualStyleElement = _ + VisualStyleElement.StartPanel.LogOffButtons.Normal + + Public Sub New() + Me.Location = New Point(50, 50) + Me.Size = New Size(200, 200) + Me.BackColor = SystemColors.ActiveBorder + + If Application.RenderWithVisualStyles And _ + VisualStyleRenderer.IsElementDefined(element) Then + renderer = New VisualStyleRenderer(element) + End If + End Sub + ' + + ' + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + ' Draw the element if the renderer has been set. + If (renderer IsNot Nothing) Then + renderer.DrawBackground(e.Graphics, Me.ClientRectangle) + + ' Visual styles are disabled or the element is undefined, + ' so just draw a message. + Else + Me.Text = "Visual styles are disabled." + TextRenderer.DrawText(e.Graphics, Me.Text, Me.Font, _ + New Point(0, 0), Me.ForeColor) + End If + End Sub + ' + + End Class +End Namespace \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb new file mode 100644 index 0000000000..098a410be6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser.ObjectForScripting/vb/form1.vb @@ -0,0 +1,73 @@ +' +Imports System.Windows.Forms +Imports System.Security.Permissions + + _ + _ +Public Class Form1 + Inherits Form + + Private webBrowser1 As New WebBrowser() + Private WithEvents button1 As New Button() + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + Public Sub New() + button1.Text = "call script code from client code" + button1.Dock = DockStyle.Top + webBrowser1.Dock = DockStyle.Fill + Controls.Add(webBrowser1) + Controls.Add(button1) + End Sub + + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + ' + webBrowser1.AllowWebBrowserDrop = False + ' + ' + webBrowser1.IsWebBrowserContextMenuEnabled = False + ' + ' + webBrowser1.WebBrowserShortcutsEnabled = False + ' + ' + webBrowser1.ObjectForScripting = Me + ' + ' + ' Uncomment the following line when you are finished debugging. + 'webBrowser1.ScriptErrorsSuppressed = True + ' + + webBrowser1.DocumentText = _ + "" & _ + "" + End Sub + + ' + Public Sub Test(ByVal message As String) + MessageBox.Show(message, "client code") + End Sub + ' + + Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button1.Click + + ' + webBrowser1.Document.InvokeScript("test", _ + New String() {"called from client code"}) + ' + + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/VB/form1.vb new file mode 100644 index 0000000000..40e38e1041 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms.WebBrowser/VB/form1.vb @@ -0,0 +1,378 @@ +' +Imports System.Windows.Forms +Imports System.Security.Permissions + + _ +Public Class Form1 + Inherits Form + + Public Sub New() + + ' Create the form layout. If you are using Visual Studio, + ' you can replace this code with code generated by the designer. + InitializeForm() + + ' Load the user's home page. + webBrowser1.GoHome() + + End Sub + + + ' + ' Displays the Save dialog box. + Private Sub saveAsToolStripMenuItem_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles saveAsToolStripMenuItem.Click + + webBrowser1.ShowSaveAsDialog() + + End Sub + ' + + ' + ' Displays the Page Setup dialog box. + Private Sub pageSetupToolStripMenuItem_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles pageSetupToolStripMenuItem.Click + + webBrowser1.ShowPageSetupDialog() + + End Sub + ' + + ' + ' Displays the Print dialog box. + Private Sub printToolStripMenuItem_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles printToolStripMenuItem.Click + + webBrowser1.ShowPrintDialog() + + End Sub + ' + + ' + ' Displays the Print Preview dialog box. + Private Sub printPreviewToolStripMenuItem_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles printPreviewToolStripMenuItem.Click + + webBrowser1.ShowPrintPreviewDialog() + + End Sub + ' + + ' + ' Displays the Properties dialog box. + Private Sub propertiesToolStripMenuItem_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles propertiesToolStripMenuItem.Click + + webBrowser1.ShowPropertiesDialog() + + End Sub + ' + + ' Selects all the text in the text box when the user clicks it. + Private Sub toolStripTextBox1_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles toolStripTextBox1.Click + + toolStripTextBox1.SelectAll() + + End Sub + ' + + ' Navigates to the URL in the address box when + ' the ENTER key is pressed while the ToolStripTextBox has focus. + Private Sub toolStripTextBox1_KeyDown( _ + ByVal sender As Object, ByVal e As KeyEventArgs) _ + Handles toolStripTextBox1.KeyDown + + If (e.KeyCode = Keys.Enter) Then + Navigate(toolStripTextBox1.Text) + End If + + End Sub + + ' Navigates to the URL in the address box when + ' the Go button is clicked. + Private Sub goButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles goButton.Click + + Navigate(toolStripTextBox1.Text) + + End Sub + + ' Navigates to the given URL if it is valid. + Private Sub Navigate(ByVal address As String) + + If String.IsNullOrEmpty(address) Then Return + If address.Equals("about:blank") Then Return + If Not address.StartsWith("http://") And _ + Not address.StartsWith("https://") Then + address = "http://" & address + End If + + Try + webBrowser1.Navigate(New Uri(address)) + Catch ex As System.UriFormatException + Return + End Try + + End Sub + + ' Updates the URL in TextBoxAddress upon navigation. + Private Sub webBrowser1_Navigated(ByVal sender As Object, _ + ByVal e As WebBrowserNavigatedEventArgs) _ + Handles webBrowser1.Navigated + + toolStripTextBox1.Text = webBrowser1.Url.ToString() + + End Sub + ' + + ' + ' Navigates webBrowser1 to the previous page in the history. + Private Sub backButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles backButton.Click + + webBrowser1.GoBack() + + End Sub + + ' Disables the Back button at the beginning of the navigation history. + Private Sub webBrowser1_CanGoBackChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles webBrowser1.CanGoBackChanged + + backButton.Enabled = webBrowser1.CanGoBack + + End Sub + ' + + ' + ' Navigates webBrowser1 to the next page in history. + Private Sub forwardButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles forwardButton.Click + + webBrowser1.GoForward() + + End Sub + + ' Disables the Forward button at the end of navigation history. + Private Sub webBrowser1_CanGoForwardChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles webBrowser1.CanGoForwardChanged + + forwardButton.Enabled = webBrowser1.CanGoForward + + End Sub + ' + + ' + ' Halts the current navigation and any sounds or animations on + ' the page. + Private Sub stopButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles stopButton.Click + + webBrowser1.Stop() + + End Sub + ' + + ' + ' Reloads the current page. + Private Sub refreshButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles refreshButton.Click + + ' Skip refresh if about:blank is loaded to avoid removing + ' content specified by the DocumentText property. + If Not webBrowser1.Url.Equals("about:blank") Then + webBrowser1.Refresh() + End If + + End Sub + ' + + ' + ' Navigates webBrowser1 to the home page of the current user. + Private Sub homeButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles homeButton.Click + + webBrowser1.GoHome() + + End Sub + ' + + ' + ' Navigates webBrowser1 to the search page of the current user. + Private Sub searchButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles searchButton.Click + + webBrowser1.GoSearch() + + End Sub + ' + + ' + ' Prints the current document Imports the current print settings. + Private Sub printButton_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles printButton.Click + + webBrowser1.Print() + + End Sub + ' + + ' + ' Updates the status bar with the current browser status text. + Private Sub webBrowser1_StatusTextChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles webBrowser1.StatusTextChanged + + toolStripStatusLabel1.Text = webBrowser1.StatusText + + End Sub + ' + + ' + ' Updates the title bar with the current document title. + Private Sub webBrowser1_DocumentTitleChanged( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles webBrowser1.DocumentTitleChanged + + Me.Text = webBrowser1.DocumentTitle + + End Sub + ' + + ' Exits the application. + Private Sub exitToolStripMenuItem_Click( _ + ByVal sender As Object, ByVal e As EventArgs) _ + Handles exitToolStripMenuItem.Click + + Application.Exit() + + End Sub + + ' The remaining code in this file provides basic form initialization and + ' includes a Main method. If you use the Visual Studio designer to create + ' your form, you can use the designer generated code instead of this code, + ' but be sure to use the names shown in the variable declarations here. + + Private WithEvents webBrowser1 As WebBrowser + + Private menuStrip1 As MenuStrip + Private WithEvents fileToolStripMenuItem, saveAsToolStripMenuItem, _ + printToolStripMenuItem, printPreviewToolStripMenuItem, _ + exitToolStripMenuItem, pageSetupToolStripMenuItem, _ + propertiesToolStripMenuItem As ToolStripMenuItem + Private toolStripSeparator1, toolStripSeparator2 As ToolStripSeparator + + Private toolStrip1, toolStrip2 As ToolStrip + Private WithEvents toolStripTextBox1 As ToolStripTextBox + Private WithEvents goButton, backButton, forwardButton, _ + stopButton, refreshButton, homeButton, _ + searchButton, printButton As ToolStripButton + + Private statusStrip1 As StatusStrip + Private toolStripStatusLabel1 As ToolStripStatusLabel + + Private Sub InitializeForm() + + webBrowser1 = New WebBrowser() + + menuStrip1 = New MenuStrip() + fileToolStripMenuItem = New ToolStripMenuItem() + saveAsToolStripMenuItem = New ToolStripMenuItem() + toolStripSeparator1 = New ToolStripSeparator() + printToolStripMenuItem = New ToolStripMenuItem() + printPreviewToolStripMenuItem = New ToolStripMenuItem() + toolStripSeparator2 = New ToolStripSeparator() + exitToolStripMenuItem = New ToolStripMenuItem() + pageSetupToolStripMenuItem = New ToolStripMenuItem() + propertiesToolStripMenuItem = New ToolStripMenuItem() + + toolStrip1 = New ToolStrip() + goButton = New ToolStripButton() + backButton = New ToolStripButton() + forwardButton = New ToolStripButton() + stopButton = New ToolStripButton() + refreshButton = New ToolStripButton() + homeButton = New ToolStripButton() + searchButton = New ToolStripButton() + printButton = New ToolStripButton() + + toolStrip2 = New ToolStrip() + toolStripTextBox1 = New ToolStripTextBox() + + statusStrip1 = New StatusStrip() + toolStripStatusLabel1 = New ToolStripStatusLabel() + + webBrowser1.Dock = DockStyle.Fill + + menuStrip1.Items.Add(fileToolStripMenuItem) + + fileToolStripMenuItem.DropDownItems.AddRange( _ + New ToolStripItem() { _ + saveAsToolStripMenuItem, toolStripSeparator1, _ + pageSetupToolStripMenuItem, printToolStripMenuItem, _ + printPreviewToolStripMenuItem, toolStripSeparator2, _ + propertiesToolStripMenuItem, exitToolStripMenuItem _ + }) + + fileToolStripMenuItem.Text = "&File" + saveAsToolStripMenuItem.Text = "Save &As..." + pageSetupToolStripMenuItem.Text = "Page Set&up..." + printToolStripMenuItem.Text = "&Print..." + printPreviewToolStripMenuItem.Text = "Print Pre&view..." + propertiesToolStripMenuItem.Text = "Properties" + exitToolStripMenuItem.Text = "E&xit" + + ' + printToolStripMenuItem.ShortcutKeys = Keys.Control Or Keys.P + ' + + toolStrip1.Items.AddRange(New ToolStripItem() { _ + goButton, backButton, forwardButton, stopButton, _ + refreshButton, homeButton, searchButton, printButton}) + + goButton.Text = "Go" + backButton.Text = "Back" + forwardButton.Text = "Forward" + stopButton.Text = "Stop" + refreshButton.Text = "Refresh" + homeButton.Text = "Home" + searchButton.Text = "Search" + printButton.Text = "Print" + + backButton.Enabled = False + forwardButton.Enabled = False + + toolStrip2.Items.Add(toolStripTextBox1) + toolStripTextBox1.Size = New System.Drawing.Size(250, 25) + + statusStrip1.Items.Add(toolStripStatusLabel1) + + Controls.AddRange(New Control() { _ + webBrowser1, toolStrip2, toolStrip1, _ + menuStrip1, statusStrip1, menuStrip1}) + End Sub + + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/VB/form1.vb new file mode 100644 index 0000000000..b27b8d593f --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/System.Windows.Forms_ControlRenderer/VB/form1.vb @@ -0,0 +1,49 @@ +' +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.VisualStyles + +Namespace SimpleControlRenderingSample + + Class Form1 + Inherits Form + + Public Sub New() + Me.Size = New Size(300, 300) + Dim ComboBox1 As New CustomComboBoxArrow() + Controls.Add(ComboBox1) + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + End Class + + Public Class CustomComboBoxArrow + Inherits Control + + Public Sub New() + Me.Location = New Point(50, 50) + Me.Size = New Size(40, 40) + End Sub + + ' + ' Render the drop-down arrow with or without visual styles. + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + MyBase.OnPaint(e) + + If Not ComboBoxRenderer.IsSupported Then + ControlPaint.DrawComboButton(e.Graphics, _ + Me.ClientRectangle, ButtonState.Normal) + Else + ComboBoxRenderer.DrawDropDownButton(e.Graphics, _ + Me.ClientRectangle, ComboBoxState.Normal) + End If + End Sub + ' + + End Class +End Namespace +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.Designer.vb new file mode 100644 index 0000000000..465910026a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.Designer.vb @@ -0,0 +1,80 @@ + _ +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) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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.TabControl1 = New System.Windows.Forms.TabControl + Me.TabPage1 = New System.Windows.Forms.TabPage + Me.TabPage2 = New System.Windows.Forms.TabPage + Me.TabControl1.SuspendLayout() + Me.SuspendLayout() + ' + 'TabControl1 + ' + Me.TabControl1.Alignment = System.Windows.Forms.TabAlignment.Right + Me.TabControl1.Controls.Add(Me.TabPage1) + Me.TabControl1.Controls.Add(Me.TabPage2) + Me.TabControl1.Dock = System.Windows.Forms.DockStyle.Fill + Me.TabControl1.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed + Me.TabControl1.ItemSize = New System.Drawing.Size(25, 150) + Me.TabControl1.Location = New System.Drawing.Point(0, 0) + Me.TabControl1.Multiline = True + Me.TabControl1.Name = "TabControl1" + Me.TabControl1.SelectedIndex = 0 + Me.TabControl1.Size = New System.Drawing.Size(639, 424) + Me.TabControl1.SizeMode = System.Windows.Forms.TabSizeMode.Fixed + Me.TabControl1.TabIndex = 0 + ' + 'TabPage1 + ' + Me.TabPage1.Location = New System.Drawing.Point(4, 4) + Me.TabPage1.Name = "TabPage1" + Me.TabPage1.Padding = New System.Windows.Forms.Padding(3) + Me.TabPage1.Size = New System.Drawing.Size(481, 416) + Me.TabPage1.TabIndex = 0 + Me.TabPage1.Text = "TabPage1" + Me.TabPage1.UseVisualStyleBackColor = True + ' + 'TabPage2 + ' + Me.TabPage2.Location = New System.Drawing.Point(4, 4) + Me.TabPage2.Name = "TabPage2" + Me.TabPage2.Padding = New System.Windows.Forms.Padding(3) + Me.TabPage2.Size = New System.Drawing.Size(481, 416) + Me.TabPage2.TabIndex = 1 + Me.TabPage2.Text = "TabPage2" + Me.TabPage2.UseVisualStyleBackColor = True + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(639, 424) + Me.Controls.Add(Me.TabControl1) + Me.Name = "Form1" + Me.Text = "Form1" + Me.TabControl1.ResumeLayout(False) + Me.ResumeLayout(False) + + End Sub + Friend WithEvents TabControl1 As System.Windows.Forms.TabControl + Friend WithEvents TabPage1 As System.Windows.Forms.TabPage + Friend WithEvents TabPage2 As System.Windows.Forms.TabPage + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.resx new file mode 100644 index 0000000000..19dc0dd8b3 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.vb new file mode 100644 index 0000000000..828d8f06fe --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/Form1.vb @@ -0,0 +1,33 @@ +Public Class Form1 + + ' + Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem + Dim g As Graphics = e.Graphics + Dim _TextBrush As Brush + + ' Get the item from the collection. + Dim _TabPage As TabPage = TabControl1.TabPages(e.Index) + + ' Get the real bounds for the tab rectangle. + Dim _TabBounds As Rectangle = TabControl1.GetTabRect(e.Index) + + If (e.State = DrawItemState.Selected) Then + ' Draw a different background color, and don't paint a focus rectangle. + _TextBrush = New SolidBrush(Color.Red) + g.FillRectangle(Brushes.Gray, e.Bounds) + Else + _TextBrush = New System.Drawing.SolidBrush(e.ForeColor) + e.DrawBackground() + End If + + ' Use our own font. + Dim _TabFont As New Font("Arial", 10.0, FontStyle.Bold, GraphicsUnit.Pixel) + + ' Draw string. Center the text. + Dim _StringFlags As New StringFormat() + _StringFlags.Alignment = StringAlignment.Center + _StringFlags.LineAlignment = StringAlignment.Center + g.DrawString(_TabPage.Text, _TabFont, _TextBrush, _TabBounds, New StringFormat(_StringFlags)) + End Sub + ' +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Application.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Application.Designer.vb new file mode 100644 index 0000000000..670f084dfe --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Application.Designer.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.TestVerticalTabs.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Application.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Application.myapp new file mode 100644 index 0000000000..1243847fd9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Application.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..7b09998408 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,34 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Resources.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Resources.Designer.vb new file mode 100644 index 0000000000..437f06d870 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("TestVerticalTabs.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Resources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Settings.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Settings.Designer.vb new file mode 100644 index 0000000000..d7c04cf6bf --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.TestVerticalTabs.My.MySettings + Get + Return Global.TestVerticalTabs.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Settings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Settings.settings new file mode 100644 index 0000000000..85b890b3c6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/TestVerticalTabs.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/TestVerticalTabs.vbproj new file mode 100644 index 0000000000..1bc9cf582e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabControl.RightAlignedTabs/VB/TestVerticalTabs.vbproj @@ -0,0 +1,106 @@ + + + + Debug + AnyCPU + 8.0.50727 + 2.0 + {F61EB8CE-4C71-400E-B6E8-07717610A61E} + WinExe + TestVerticalTabs.My.MyApplication + TestVerticalTabs + TestVerticalTabs + WindowsForms + + + true + full + true + true + bin\Debug\ + TestVerticalTabs.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + pdbonly + false + true + true + bin\Release\ + TestVerticalTabs.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + + + + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + Designer + Form1.vb + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabPage/VB/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabPage/VB/form1.vb new file mode 100644 index 0000000000..cf21cc6570 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/TabPage/VB/form1.vb @@ -0,0 +1,34 @@ +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + Private tabControl1 As TabControl + + ' Declares tabPage1 as a TabPage type. + Private tabPage1 As System.Windows.Forms.TabPage + + Private Sub MyTabs() + Me.tabControl1 = New TabControl() + + ' Invokes the TabPage() constructor to create the tabPage1. + Me.tabPage1 = New System.Windows.Forms.TabPage() + + Me.tabControl1.Controls.AddRange(New Control() {Me.tabPage1}) + Me.tabControl1.Location = New Point(25, 25) + Me.tabControl1.Size = New Size(250, 250) + + Me.ClientSize = New Size(300, 300) + Me.Controls.AddRange(New Control() {Me.tabControl1}) + End Sub + + Public Sub New() + MyTabs() + End Sub + + Shared Sub Main() + Application.Run(New Form1()) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb new file mode 100644 index 0000000000..a8c1a614e5 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripRadioButtonMenuItem/vb/ToolStripRadioButtonMenuItem.vb @@ -0,0 +1,307 @@ +' +' +Imports System.Drawing +Imports System.Windows.Forms +Imports System.Windows.Forms.VisualStyles + +Public Class ToolStripRadioButtonMenuItem + Inherits ToolStripMenuItem + + Public Sub New() + MyBase.New() + Initialize() + End Sub + + Public Sub New(ByVal text As String) + MyBase.New(text, Nothing, CType(Nothing, EventHandler)) + Initialize() + End Sub + + Public Sub New(ByVal image As Image) + MyBase.New(Nothing, image, CType(Nothing, EventHandler)) + Initialize() + End Sub + + Public Sub New(ByVal text As String, ByVal image As Image) + MyBase.New(text, image, CType(Nothing, EventHandler)) + Initialize() + End Sub + + Public Sub New(ByVal text As String, _ + ByVal image As Image, ByVal onClick As EventHandler) + MyBase.New(text, image, onClick) + Initialize() + End Sub + + Public Sub New(ByVal text As String, ByVal image As Image, _ + ByVal onClick As EventHandler, ByVal name As String) + MyBase.New(text, image, onClick, name) + Initialize() + End Sub + + Public Sub New(ByVal text As String, ByVal image As Image, _ + ByVal ParamArray dropDownItems() As ToolStripItem) + MyBase.New(text, image, dropDownItems) + Initialize() + End Sub + + Public Sub New(ByVal text As String, ByVal image As Image, _ + ByVal onClick As EventHandler, ByVal shortcutKeys As Keys) + MyBase.New(text, image, onClick) + Initialize() + Me.ShortcutKeys = shortcutKeys + End Sub + + ' + ' Called by all constructors to initialize CheckOnClick. + Private Sub Initialize() + CheckOnClick = True + End Sub + ' + + ' + Protected Overrides Sub OnCheckedChanged(ByVal e As EventArgs) + + MyBase.OnCheckedChanged(e) + + ' If this item is no longer in the checked state or if its + ' parent has not yet been initialized, do nothing. + If Not Checked OrElse Me.Parent Is Nothing Then Return + + ' Clear the checked state for all siblings. + For Each item As ToolStripItem In Parent.Items + + Dim radioItem As ToolStripRadioButtonMenuItem = _ + TryCast(item, ToolStripRadioButtonMenuItem) + If radioItem IsNot Nothing AndAlso _ + radioItem IsNot Me AndAlso _ + radioItem.Checked Then + + radioItem.Checked = False + + ' Only one item can be selected at a time, + ' so there is no need to continue. + Return + + End If + Next + + End Sub + ' + + ' + Protected Overrides Sub OnClick(ByVal e As EventArgs) + + ' If the item is already in the checked state, do not call + ' the base method, which would toggle the value. + If Checked Then Return + + MyBase.OnClick(e) + End Sub + ' + + ' + ' Let the item paint itself, and then paint the RadioButton + ' where the check mark is normally displayed. + Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) + + If Image IsNot Nothing Then + ' If the client sets the Image property, the selection behavior + ' remains unchanged, but the RadioButton is not displayed and the + ' selection is indicated only by the selection rectangle. + MyBase.OnPaint(e) + Return + Else + ' If the Image property is not set, call the base OnPaint method + ' with the CheckState property temporarily cleared to prevent + ' the check mark from being painted. + Dim currentState As CheckState = Me.CheckState + Me.CheckState = CheckState.Unchecked + MyBase.OnPaint(e) + Me.CheckState = currentState + End If + + ' Determine the correct state of the RadioButton. + Dim buttonState As RadioButtonState = RadioButtonState.UncheckedNormal + If Enabled Then + If mouseDownState Then + If Checked Then + buttonState = RadioButtonState.CheckedPressed + Else + buttonState = RadioButtonState.UncheckedPressed + End If + ElseIf mouseHoverState Then + If Checked Then + buttonState = RadioButtonState.CheckedHot + Else + buttonState = RadioButtonState.UncheckedHot + End If + Else + If Checked Then buttonState = RadioButtonState.CheckedNormal + End If + Else + If Checked Then + buttonState = RadioButtonState.CheckedDisabled + Else + buttonState = RadioButtonState.UncheckedDisabled + End If + End If + + ' Calculate the position at which to display the RadioButton. + Dim offset As Int32 = CInt((ContentRectangle.Height - _ + RadioButtonRenderer.GetGlyphSize( _ + e.Graphics, buttonState).Height) / 2) + Dim imageLocation As Point = New Point( _ + ContentRectangle.Location.X + 4, _ + ContentRectangle.Location.Y + offset) + + ' Paint the RadioButton. + RadioButtonRenderer.DrawRadioButton( _ + e.Graphics, imageLocation, buttonState) + + End Sub + ' + + ' + Private mouseHoverState As Boolean = False + + Protected Overrides Sub OnMouseEnter(ByVal e As EventArgs) + mouseHoverState = True + + ' Force the item to repaint with the new RadioButton state. + Invalidate() + + MyBase.OnMouseEnter(e) + End Sub + + Protected Overrides Sub OnMouseLeave(ByVal e As EventArgs) + mouseHoverState = False + MyBase.OnMouseLeave(e) + End Sub + + Private mouseDownState As Boolean = False + + Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs) + mouseDownState = True + + ' Force the item to repaint with the new RadioButton state. + Invalidate() + + MyBase.OnMouseDown(e) + End Sub + + Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs) + mouseDownState = False + MyBase.OnMouseUp(e) + End Sub + ' + + ' + ' Enable the item only if its parent item is in the checked state + ' and its Enabled property has not been explicitly set to false. + Public Overrides Property Enabled() As Boolean + Get + Dim ownerMenuItem As ToolStripMenuItem = _ + TryCast(OwnerItem, ToolStripMenuItem) + + ' Use the base value in design mode to prevent the designer + ' from setting the base value to the calculated value. + If Not DesignMode AndAlso ownerMenuItem IsNot Nothing AndAlso _ + ownerMenuItem.CheckOnClick Then + Return MyBase.Enabled AndAlso ownerMenuItem.Checked + Else + Return MyBase.Enabled + End If + End Get + + Set(ByVal value As Boolean) + MyBase.Enabled = value + End Set + End Property + ' + + ' + ' When OwnerItem becomes available, if it is a ToolStripMenuItem + ' with a CheckOnClick property value of true, subscribe to its + ' CheckedChanged event. + Protected Overrides Sub OnOwnerChanged(ByVal e As EventArgs) + + Dim ownerMenuItem As ToolStripMenuItem = _ + TryCast(OwnerItem, ToolStripMenuItem) + + If ownerMenuItem IsNot Nothing AndAlso _ + ownerMenuItem.CheckOnClick Then + AddHandler ownerMenuItem.CheckedChanged, New _ + EventHandler(AddressOf OwnerMenuItem_CheckedChanged) + End If + + MyBase.OnOwnerChanged(e) + + End Sub + ' + + ' + ' When the checked state of the parent item changes, + ' repaint the item so that the new Enabled state is displayed. + Private Sub OwnerMenuItem_CheckedChanged( _ + ByVal sender As Object, ByVal e As EventArgs) + Invalidate() + End Sub + ' + +End Class +' + +' +Public Class Form1 + Inherits Form + + Private menuStrip1 As New MenuStrip() + Private mainToolStripMenuItem As New ToolStripMenuItem() + Private toolStripMenuItem1 As New ToolStripMenuItem() + Private toolStripRadioButtonMenuItem1 As New ToolStripRadioButtonMenuItem() + Private toolStripRadioButtonMenuItem2 As New ToolStripRadioButtonMenuItem() + Private toolStripRadioButtonMenuItem3 As New ToolStripRadioButtonMenuItem() + Private toolStripRadioButtonMenuItem4 As New ToolStripRadioButtonMenuItem() + Private toolStripRadioButtonMenuItem5 As New ToolStripRadioButtonMenuItem() + Private toolStripRadioButtonMenuItem6 As New ToolStripRadioButtonMenuItem() + + Public Sub New() + + Me.mainToolStripMenuItem.Text = "main" + toolStripRadioButtonMenuItem1.Text = "option 1" + toolStripRadioButtonMenuItem2.Text = "option 2" + toolStripRadioButtonMenuItem3.Text = "option 2-1" + toolStripRadioButtonMenuItem4.Text = "option 2-2" + toolStripRadioButtonMenuItem5.Text = "option 3-1" + toolStripRadioButtonMenuItem6.Text = "option 3-2" + toolStripMenuItem1.Text = "toggle" + toolStripMenuItem1.CheckOnClick = True + + mainToolStripMenuItem.DropDownItems.AddRange(New ToolStripItem() { _ + toolStripRadioButtonMenuItem1, toolStripRadioButtonMenuItem2, _ + toolStripMenuItem1}) + toolStripRadioButtonMenuItem2.DropDownItems.AddRange( _ + New ToolStripItem() {toolStripRadioButtonMenuItem3, _ + toolStripRadioButtonMenuItem4}) + toolStripMenuItem1.DropDownItems.AddRange(New ToolStripItem() { _ + toolStripRadioButtonMenuItem5, toolStripRadioButtonMenuItem6}) + + menuStrip1.Items.AddRange(New ToolStripItem() {mainToolStripMenuItem}) + Controls.Add(menuStrip1) + MainMenuStrip = menuStrip1 + Text = "ToolStripRadioButtonMenuItem demo" + End Sub +End Class + +Public Class Program + + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripSpringTextBox/vb/ToolStripSpringTextBox.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripSpringTextBox/vb/ToolStripSpringTextBox.vb new file mode 100644 index 0000000000..abed81df9b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/ToolStripSpringTextBox/vb/ToolStripSpringTextBox.vb @@ -0,0 +1,96 @@ +' +' +Imports System.Drawing +Imports System.Windows.Forms + +Public Class ToolStripSpringTextBox + Inherits ToolStripTextBox + + Public Overrides Function GetPreferredSize( _ + ByVal constrainingSize As Size) As Size + + ' Use the default size if the text box is on the overflow menu + ' or is on a vertical ToolStrip. + If IsOnOverflow Or Owner.Orientation = Orientation.Vertical Then + Return DefaultSize + End If + + ' Declare a variable to store the total available width as + ' it is calculated, starting with the display width of the + ' owning ToolStrip. + Dim width As Int32 = Owner.DisplayRectangle.Width + + ' Subtract the width of the overflow button if it is displayed. + If Owner.OverflowButton.Visible Then + width = width - Owner.OverflowButton.Width - _ + Owner.OverflowButton.Margin.Horizontal() + End If + + ' Declare a variable to maintain a count of ToolStripSpringTextBox + ' items currently displayed in the owning ToolStrip. + Dim springBoxCount As Int32 = 0 + + For Each item As ToolStripItem In Owner.Items + + ' Ignore items on the overflow menu. + If item.IsOnOverflow Then Continue For + + If TypeOf item Is ToolStripSpringTextBox Then + ' For ToolStripSpringTextBox items, increment the count and + ' subtract the margin width from the total available width. + springBoxCount += 1 + width -= item.Margin.Horizontal + Else + ' For all other items, subtract the full width from the total + ' available width. + width = width - item.Width - item.Margin.Horizontal + End If + Next + + ' If there are multiple ToolStripSpringTextBox items in the owning + ' ToolStrip, divide the total available width between them. + If springBoxCount > 1 Then width = CInt(width / springBoxCount) + + ' If the available width is less than the default width, use the + ' default width, forcing one or more items onto the overflow menu. + If width < DefaultSize.Width Then width = DefaultSize.Width + + ' Retrieve the preferred size from the base class, but change the + ' width to the calculated width. + Dim preferredSize As Size = MyBase.GetPreferredSize(constrainingSize) + preferredSize.Width = width + Return preferredSize + + End Function +End Class +' + +' +Public Class Form1 + Inherits Form + + Public Sub New() + Dim toolStrip1 As New ToolStrip() + With toolStrip1 + .Dock = DockStyle.Top + .Items.Add(New ToolStripLabel("Address")) + .Items.Add(New ToolStripSpringTextBox()) + .Items.Add(New ToolStripButton("Go")) + End With + Controls.Add(toolStrip1) + Text = "ToolStripSpringTextBox demo" + End Sub + +End Class + +Public Class Program + + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + End Sub + +End Class +' +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb new file mode 100644 index 0000000000..3bb9fee60e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/UsingImageEncodersDecoders/VB/Form1.vb @@ -0,0 +1,221 @@ + +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Drawing.Drawing2D +Imports System.Text +Imports System.Windows.Forms +Imports System.Drawing.Imaging + + + +Public Class Form1 + Inherits Form + + Public Sub New() + + End Sub + + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.SetCompatibleTextRenderingDefault(False) + Application.Run(New Form1()) + + End Sub + + + ' + Private Sub GetImageEncodersExample(ByVal e As PaintEventArgs) + ' Get an array of available encoders. + Dim myCodecs() As ImageCodecInfo + myCodecs = ImageCodecInfo.GetImageEncoders() + Dim numCodecs As Integer = myCodecs.GetLength(0) + + ' Set up display variables. + Dim foreColor As Color = Color.Black + Dim font As New Font("Arial", 8) + Dim i As Integer = 0 + + ' Check to determine whether any codecs were found. + If numCodecs > 0 Then + + ' Set up an array to hold codec information. There are 9 + ' information elements plus 1 space for each codec, so 10 times + ' the number of codecs found is allocated. + Dim myCodecInfo(numCodecs * 10) As String + + ' Write all the codec information to the array. + For i = 0 To numCodecs - 1 + myCodecInfo((i * 10)) = "Codec Name = " + myCodecs(i).CodecName + myCodecInfo((i * 10 + 1)) = "Class ID = " + myCodecs(i).Clsid.ToString() + myCodecInfo((i * 10 + 2)) = "DLL Name = " + myCodecs(i).DllName + myCodecInfo((i * 10 + 3)) = "Filename Ext. = " + myCodecs(i).FilenameExtension + myCodecInfo((i * 10 + 4)) = "Flags = " + myCodecs(i).Flags.ToString() + myCodecInfo((i * 10 + 5)) = "Format Descrip. = " + myCodecs(i).FormatDescription + myCodecInfo((i * 10 + 6)) = "Format ID = " + myCodecs(i).FormatID.ToString() + myCodecInfo((i * 10 + 7)) = "MimeType = " + myCodecs(i).MimeType + myCodecInfo((i * 10 + 8)) = "Version = " + myCodecs(i).Version.ToString() + myCodecInfo((i * 10 + 9)) = " " + Next i + Dim numMyCodecInfo As Integer = myCodecInfo.GetLength(0) + + ' Render all of the information to the screen. + Dim j As Integer = 20 + For i = 0 To numMyCodecInfo - 1 + e.Graphics.DrawString(myCodecInfo(i), _ + font, New SolidBrush(foreColor), 20, j) + j += 12 + Next i + Else + e.Graphics.DrawString("No Codecs Found", _ + font, New SolidBrush(foreColor), 20, 20) + End If + + End Sub + ' + + ' + Private Sub GetImageDecodersExample(ByVal e As PaintEventArgs) + ' Get an array of available decoders. + Dim myCodecs() As ImageCodecInfo + myCodecs = ImageCodecInfo.GetImageDecoders() + Dim numCodecs As Integer = myCodecs.GetLength(0) + + ' Set up display variables. + Dim foreColor As Color = Color.Black + Dim font As New Font("Arial", 8) + Dim i As Integer = 0 + + ' Check to determine whether any codecs were found. + If numCodecs > 0 Then + ' Set up an array to hold codec information. There are 9 + ' information elements plus 1 space for each codec, so 10 times + ' the number of codecs found is allocated. + Dim myCodecInfo(numCodecs * 10) As String + + ' Write all the codec information to the array. + For i = 0 To numCodecs - 1 + myCodecInfo((i * 10)) = "Codec Name = " + myCodecs(i).CodecName + myCodecInfo((i * 10 + 1)) = "Class ID = " + myCodecs(i).Clsid.ToString() + myCodecInfo((i * 10 + 2)) = "DLL Name = " + myCodecs(i).DllName + myCodecInfo((i * 10 + 3)) = "Filename Ext. = " + myCodecs(i).FilenameExtension + myCodecInfo((i * 10 + 4)) = "Flags = " + myCodecs(i).Flags.ToString() + myCodecInfo((i * 10 + 5)) = "Format Descrip. = " + myCodecs(i).FormatDescription + myCodecInfo((i * 10 + 6)) = "Format ID = " + myCodecs(i).FormatID.ToString() + myCodecInfo((i * 10 + 7)) = "MimeType = " + myCodecs(i).MimeType + myCodecInfo((i * 10 + 8)) = "Version = " + myCodecs(i).Version.ToString() + myCodecInfo((i * 10 + 9)) = " " + Next i + Dim numMyCodecInfo As Integer = myCodecInfo.GetLength(0) + + ' Render all of the information to the screen. + Dim j As Integer = 20 + For i = 0 To numMyCodecInfo - 1 + e.Graphics.DrawString(myCodecInfo(i), _ + font, New SolidBrush(foreColor), 20, j) + j += 12 + Next i + Else + e.Graphics.DrawString("No Codecs Found", _ + font, New SolidBrush(foreColor), 20, 20) + End If + End Sub + ' + + ' + Private Sub GetSupportedParameters(ByVal e As PaintEventArgs) + Dim bitmap1 As New Bitmap(1, 1) + Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg) + Dim paramList As EncoderParameters = _ + bitmap1.GetEncoderParameterList(jpgEncoder.Clsid) + Dim encParams As EncoderParameter() = paramList.Param + Dim paramInfo As New StringBuilder() + + Dim i As Integer + For i = 0 To encParams.Length - 1 + paramInfo.Append("Param " & i & " holds " & _ + encParams(i).NumberOfValues & " items of type " & _ + encParams(i).Type.ToString() & vbCr & vbLf & "Guid category: " & _ + encParams(i).Encoder.Guid.ToString() & vbCr & vbLf) + Next i + + e.Graphics.DrawString(paramInfo.ToString(), _ + Me.Font, Brushes.Red, 10.0F, 10.0F) + End Sub + + ' + Private Function GetEncoder(ByVal format As ImageFormat) As ImageCodecInfo + + Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders() + + Dim codec As ImageCodecInfo + For Each codec In codecs + If codec.FormatID = format.Guid Then + Return codec + End If + Next codec + Return Nothing + + End Function + ' + ' + + ' + Private Sub SaveBmpAsPNG() + Dim bmp1 As New Bitmap(GetType(Button), "Button.bmp") + bmp1.Save("c:\button.png", ImageFormat.Png) + + End Sub + ' + + ' + Private Sub VaryQualityLevel() + ' Get a bitmap. + Dim bmp1 As New Bitmap("c:\TestPhoto.jpg") + Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg) + + ' Create an Encoder object based on the GUID + ' for the Quality parameter category. + Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality + + ' Create an EncoderParameters object. + ' An EncoderParameters object has an array of EncoderParameter + ' objects. In this case, there is only one + ' EncoderParameter object in the array. + Dim myEncoderParameters As New EncoderParameters(1) + + Dim myEncoderParameter As New EncoderParameter(myEncoder, 50&) + myEncoderParameters.Param(0) = myEncoderParameter + bmp1.Save("c:\TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters) + + myEncoderParameter = New EncoderParameter(myEncoder, 100&) + myEncoderParameters.Param(0) = myEncoderParameter + bmp1.Save("c:\TestPhotoQualityHundred.jpg", jpgEncoder, myEncoderParameters) + + ' Save the bitmap as a JPG file with zero quality level compression. + myEncoderParameter = New EncoderParameter(myEncoder, 0&) + myEncoderParameters.Param(0) = myEncoderParameter + bmp1.Save("c:\TestPhotoQualityZero.jpg", jpgEncoder, myEncoderParameters) + + End Sub + + ' + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) + + End Sub + 'SaveBmpAsPng(); + + Private Sub Form1_Paint(ByVal sender As Object, _ + ByVal e As PaintEventArgs) Handles Me.Paint + 'GetSupportedParameters(e) + 'GetImageDecodersExample(e) + GetImageEncodersExample(e) + SaveBmpAsPNG() + VaryQualityLevel() + + End Sub +End Class + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WebBrowserMisc/vb/WebBrowserMisc.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WebBrowserMisc/vb/WebBrowserMisc.vb new file mode 100644 index 0000000000..85bbd5f791 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WebBrowserMisc/vb/WebBrowserMisc.vb @@ -0,0 +1,136 @@ +Imports System.Windows.Forms +Imports System.Security.Permissions + + _ +Public Class Form1 + Inherits Form + + _ + Public Shared Sub Main() + + Application.Run(New Form1()) + + End Sub + + Private WithEvents button As New Button() + + Public Sub New() + + Me.Controls.Add(button) + Me.Controls.Add(webBrowser1) + + End Sub + + Private Sub button_Click(ByVal sender As Object, ByVal e As EventArgs) _ + Handles button.Click + + PrintHelpPage() + + End Sub + + ' + Private Sub PrintHelpPage() + + ' Create a WebBrowser instance. + Dim webBrowserForPrinting As New WebBrowser() + + ' Add an event handler that prints the document after it loads. + AddHandler webBrowserForPrinting.DocumentCompleted, New _ + WebBrowserDocumentCompletedEventHandler(AddressOf PrintDocument) + + ' Set the Url property to load the document. + webBrowserForPrinting.Url = New Uri("\\myshare\help.html") + + End Sub + + Private Sub PrintDocument(ByVal sender As Object, _ + ByVal e As WebBrowserDocumentCompletedEventArgs) + + Dim webBrowserForPrinting As WebBrowser = CType(sender, WebBrowser) + + ' Print the document now that it is fully loaded. + webBrowserForPrinting.Print() + MessageBox.Show("print") + + ' Dispose the WebBrowser now that the task is complete. + webBrowserForPrinting.Dispose() + + End Sub + ' + + Private WithEvents webBrowser1 As New WebBrowser() + + Private Sub InitializeHtmlViewer() + + ' + webBrowser1.AllowWebBrowserDrop = False + ' + + ' + webBrowser1.Url = New Uri("http://www.contoso.com/") + ' + + End Sub + + ' + Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _ + Handles Me.Load + + webBrowser1.DocumentText = _ + "Please enter your name:
" & _ + "
" & _ + "continue" & _ + "" + + End Sub + + Private Sub webBrowser1_Navigating( _ + ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs) _ + Handles webBrowser1.Navigating + + Dim document As System.Windows.Forms.HtmlDocument = _ + webBrowser1.Document + If document IsNot Nothing And _ + document.All("userName") IsNot Nothing And _ + String.IsNullOrEmpty( _ + document.All("userName").GetAttribute("value")) Then + + e.Cancel = True + MsgBox("You must enter your name before you can navigate to " & _ + e.Url.ToString()) + End If + + End Sub + '
+ + ' + ' Hides script errors without hiding other dialog boxes. + Private Sub SuppressScriptErrorsOnly(ByVal browser As WebBrowser) + + ' Ensure that ScriptErrorsSuppressed is set to false. + browser.ScriptErrorsSuppressed = False + + ' Handle DocumentCompleted to gain access to the Document object. + AddHandler browser.DocumentCompleted, _ + AddressOf browser_DocumentCompleted + + End Sub + + Private Sub browser_DocumentCompleted(ByVal sender As Object, _ + ByVal e As WebBrowserDocumentCompletedEventArgs) + + AddHandler CType(sender, WebBrowser).Document.Window.Error, _ + AddressOf Window_Error + + End Sub + + Private Sub Window_Error(ByVal sender As Object, _ + ByVal e As HtmlElementErrorEventArgs) + + ' Ignore the error and suppress the error dialog box. + e.Handled = True + + End Sub + ' + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.Designer.vb new file mode 100644 index 0000000000..aa7d61cb98 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.Designer.vb @@ -0,0 +1,27 @@ + _ +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) + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + MyBase.Dispose(disposing) + 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 + Me.Text = "Form1" + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb new file mode 100644 index 0000000000..d8953f2547 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/Form1.vb @@ -0,0 +1,31 @@ +' +' +Imports Microsoft.Win32 +' + +Public Class Form1 + ' + Public Sub New() + ' This call is required by the Windows Form Designer. + InitializeComponent() + + ' Add any initialization after the InitializeComponent() call. + AddHandler SystemEvents.UserPreferenceChanged, New UserPreferenceChangedEventHandler(AddressOf SystemEvents_UserPreferenceChangesEventHandler) + End Sub + ' + + ' + Private Sub SystemEvents_UserPreferenceChangesEventHandler(ByVal sender As Object, ByVal e As UserPreferenceChangedEventArgs) + If (e.Category = UserPreferenceCategory.Window) Then + Me.Font = SystemFonts.IconTitleFont + End If + End Sub + ' + + ' + Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing + RemoveHandler SystemEvents.UserPreferenceChanged, New UserPreferenceChangedEventHandler(AddressOf SystemEvents_UserPreferenceChangesEventHandler) + End Sub + ' +End Class +' diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Application.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Application.Designer.vb new file mode 100644 index 0000000000..ceada9ff9b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Application.Designer.vb @@ -0,0 +1,38 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.WinFormsAutoScalingVB.Form1 + End Sub + End Class +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Application.myapp b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Application.myapp new file mode 100644 index 0000000000..1243847fd9 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Application.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/AssemblyInfo.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/AssemblyInfo.vb new file mode 100644 index 0000000000..d88fd2b25c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/AssemblyInfo.vb @@ -0,0 +1,34 @@ +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Resources.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Resources.Designer.vb new file mode 100644 index 0000000000..775f18f62b --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("WinFormsAutoScalingVB.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Resources.resx b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Settings.Designer.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Settings.Designer.vb new file mode 100644 index 0000000000..4404d4058e --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.42 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.WinFormsAutoScalingVB.My.MySettings + Get + Return Global.WinFormsAutoScalingVB.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Settings.settings b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Settings.settings new file mode 100644 index 0000000000..85b890b3c6 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/WinFormsAutoScalingVB.vbproj b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/WinFormsAutoScalingVB.vbproj new file mode 100644 index 0000000000..046a54a767 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/WinFormsAutoScaling/VB/WinFormsAutoScalingVB.vbproj @@ -0,0 +1,112 @@ + + + + Debug + AnyCPU + + 2.0 + {eb0aff19-a41b-418c-bf5c-b969110a981a} + WinExe + WinFormsAutoScalingVB.My.MyApplication + WinFormsAutoScalingVB + WinFormsAutoScalingVB + WindowsForms + + + + true + full + true + true + bin\Debug\ + WinFormsAutoScalingVB.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + + pdbonly + false + true + true + bin\Release\ + WinFormsAutoScalingVB.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + + + + + + + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + + + + diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/powermode/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/powermode/vb/form1.vb new file mode 100644 index 0000000000..88c543fa0c --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/powermode/vb/form1.vb @@ -0,0 +1,36 @@ +Public Class Form1 + ' + Public Sub New() + InitializeComponent() + AddHandler Microsoft.Win32.SystemEvents.PowerModeChanged, AddressOf PowerModeChanged + End Sub + + Private Sub PowerModeChanged(ByVal Sender As System.Object, ByVal e As Microsoft.Win32.PowerModeChangedEventArgs) + Select Case SystemInformation.PowerStatus.BatteryChargeStatus + Case BatteryChargeStatus.Low + MessageBox.Show("Battery is running low.", "Low Battery", MessageBoxButtons.OK, _ + System.Windows.Forms.MessageBoxIcon.Exclamation) + Case BatteryChargeStatus.Critical + MessageBox.Show("Battery is critically low.", "Critical Battery", MessageBoxButtons.OK, _ + System.Windows.Forms.MessageBoxIcon.Stop) + Case Else + ' Battery is okay. + Exit Select + End Select + End Sub + ' + + Private Sub Hibernate() + ' + If SystemInformation.PowerStatus.BatteryChargeStatus = System.Windows.Forms.BatteryChargeStatus.Critical Then + Application.SetSuspendState(PowerState.Hibernate, False, False) + End If + ' + End Sub + + _ + Shared Sub Main() + Application.Run(New Form1()) + End Sub + +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/VB/Form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/VB/Form1.vb new file mode 100644 index 0000000000..512572467d --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.TreeNodeContextMenuStrip/VB/Form1.vb @@ -0,0 +1,85 @@ + +Imports System.Windows.Forms +Imports System.Drawing +Imports System.Collections + + +'Create a Class that inherits from System.Windows.Forms.Form. + +Class myForm + Inherits Form + + Public Sub New() + InitializeComponent() + InitializeMenuTreeView() + + End Sub + + ' + ' Declare the TreeView and ContextMenuStrip + Private menuTreeView As TreeView + Private docMenu As ContextMenuStrip + + + Public Sub InitializeMenuTreeView() + + ' Create the TreeView. + menuTreeView = New TreeView() + menuTreeView.Size = New Size(200, 200) + + ' Create the root node. + Dim docNode As New TreeNode("Documents") + + ' Add some additional nodes. + docNode.Nodes.Add("phoneList.doc") + docNode.Nodes.Add("resume.doc") + + ' Add the root nodes to the TreeView. + menuTreeView.Nodes.Add(docNode) + + ' Create the ContextMenuStrip. + docMenu = New ContextMenuStrip() + + 'Create some menu items. + Dim openLabel As New ToolStripMenuItem() + openLabel.Text = "Open" + Dim deleteLabel As New ToolStripMenuItem() + deleteLabel.Text = "Delete" + Dim renameLabel As New ToolStripMenuItem() + renameLabel.Text = "Rename" + + 'Add the menu items to the menu. + docMenu.Items.AddRange(New ToolStripMenuItem() _ + {openLabel, deleteLabel, renameLabel}) + + ' Set the ContextMenuStrip property to the ContextMenuStrip. + docNode.ContextMenuStrip = docMenu + + ' Add the TreeView to the form. + Me.Controls.Add(menuTreeView) + + End Sub + + + ' + _ + Public Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New myForm()) + + End Sub + + + Private Sub InitializeComponent() + + Me.SuspendLayout() + + ' + ' myForm + ' + Me.ClientSize = New System.Drawing.Size(292, 266) + Me.Name = "myForm" + Me.ResumeLayout(False) + + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/vb/form1.vb new file mode 100644 index 0000000000..2285e1e6b1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/system.windows.forms.toolstripcontainer2/vb/form1.vb @@ -0,0 +1,42 @@ + ' +Imports System.Collections.Generic +Imports System.ComponentModel +Imports System.Data +Imports System.Drawing +Imports System.Text +Imports System.Windows.Forms + + + + +Public Class Form1 + Inherits Form + Private toolStripContainer1 As ToolStripContainer + Private toolStrip1 As ToolStrip + + + Public Sub New() + InitializeComponent() + End Sub + + _ + Shared Sub Main() + Application.EnableVisualStyles() + Application.Run(New Form1()) + End Sub + + + Private Sub InitializeComponent() + toolStripContainer1 = New System.Windows.Forms.ToolStripContainer() + toolStrip1 = New System.Windows.Forms.ToolStrip() + ' Add items to the ToolStrip. + toolStrip1.Items.Add("One") + toolStrip1.Items.Add("Two") + toolStrip1.Items.Add("Three") + ' Add the ToolStrip to the top panel of the ToolStripContainer. + toolStripContainer1.TopToolStripPanel.Controls.Add(toolStrip1) + ' Add the ToolStripContainer to the form. + Controls.Add(toolStripContainer1) + End Sub +End Class +' \ No newline at end of file diff --git a/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/vb/add.vb b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/vb/add.vb new file mode 100644 index 0000000000..f81177d8a1 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/visualbasic/VS_Snippets_Winforms/tabpagecontrolcollectionhowtoadd/vb/add.vb @@ -0,0 +1,20 @@ + +Imports System.Drawing +Imports System.Windows.Forms + +Public Class Form1 + Inherits Form + + Public Sub New() + Dim tabPage1 As TabPage = New TabPage() + + ' + tabPage1.Controls.Add(New Button()) + ' + + End Sub + + Shared Sub Main() + Application.Run(New Form1()) + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/winforms/open-files/example1/cs/Form1.cs b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example1/cs/Form1.cs new file mode 100644 index 0000000000..4f978a6470 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example1/cs/Form1.cs @@ -0,0 +1,62 @@ +using System; +using System.Drawing; +using System.IO; +using System.Security; +using System.Windows.Forms; + +public class OpenFileDialogForm : Form +{ + [STAThread] + public static void Main() + { + Application.SetCompatibleTextRenderingDefault(false); + Application.EnableVisualStyles(); + Application.Run(new OpenFileDialogForm()); + } + + private Button selectButton; + private OpenFileDialog openFileDialog1; + private TextBox textBox1; + + public OpenFileDialogForm() + { + openFileDialog1 = new OpenFileDialog(); + selectButton = new Button + { + Size = new Size(100, 20), + Location = new Point(15, 15), + Text = "Select file" + }; + selectButton.Click += new EventHandler(SelectButton_Click); + textBox1 = new TextBox + { + Size = new Size(300, 300), + Location = new Point(15, 40), + Multiline = true, + ScrollBars = ScrollBars.Vertical + }; + ClientSize = new Size(330, 360); + Controls.Add(selectButton); + Controls.Add(textBox1); + } + private void SetText(string text) + { + textBox1.Text = text; + } + private void SelectButton_Click(object sender, EventArgs e) + { + if (openFileDialog1.ShowDialog() == DialogResult.OK) + { + try + { + var sr = new StreamReader(openFileDialog1.FileName); + SetText(sr.ReadToEnd()); + } + catch (SecurityException ex) + { + MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" + + $"Details:\n\n{ex.StackTrace}"); + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/winforms/open-files/example1/vb/Form1.vb b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example1/vb/Form1.vb new file mode 100644 index 0000000000..174e5c8564 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example1/vb/Form1.vb @@ -0,0 +1,55 @@ +Imports System.Drawing +Imports System.IO +Imports System.Security +Imports System.Windows.Forms + +Public Class OpenFileDialogForm : Inherits Form + + Public Shared Sub Main() + Application.SetCompatibleTextRenderingDefault(False) + Application.EnableVisualStyles() + Dim frm As New OpenFileDialogForm() + Application.Run(frm) + End Sub + + Dim WithEvents SelectButton As Button + Dim openFileDialog1 As OpenFileDialog + Dim TextBox1 As TextBox + + Private Sub New() + ClientSize = New Size(400, 400) + openFileDialog1 = New OpenFileDialog() + SelectButton = New Button() + With SelectButton + .Text = "Select file" + .Location = New Point(15, 15) + .Size = New Size(100, 25) + End With + TextBox1 = New TextBox() + With TextBox1 + .Size = New Size(300, 300) + .Location = New Point(15, 50) + .Multiline = True + .ScrollBars = ScrollBars.Vertical + End With + Controls.Add(SelectButton) + Controls.Add(TextBox1) + End Sub + + Private Sub SetText(text) + TextBox1.Text = text + End Sub + + Public Sub SelectButton_Click(sender As Object, e As EventArgs) _ + Handles SelectButton.Click + If openFileDialog1.ShowDialog() = DialogResult.OK Then + Try + Dim sr As New StreamReader(openFileDialog1.FileName) + SetText(sr.ReadToEnd()) + Catch SecEx As SecurityException + MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" & + $"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}") + End Try + End If + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/winforms/open-files/example2/cs/Form1.cs b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example2/cs/Form1.cs new file mode 100644 index 0000000000..42d3f69970 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example2/cs/Form1.cs @@ -0,0 +1,60 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Security; +using System.Windows.Forms; + +public class OpenFileDialogForm : Form +{ + [STAThread] + public static void Main() + { + Application.SetCompatibleTextRenderingDefault(false); + Application.EnableVisualStyles(); + Application.Run(new OpenFileDialogForm()); + } + + private Button selectButton; + private OpenFileDialog openFileDialog1; + + public OpenFileDialogForm() + { + openFileDialog1 = new OpenFileDialog() + { + FileName = "Select a text file", + Filter = "Text files (*.txt)|*.txt", + Title = "Open text file" + }; + + selectButton = new Button() + { + Size = new Size(100, 20), + Location = new Point(15, 15), + Text = "Select file" + }; + selectButton.Click += new EventHandler(selectButton_Click); + Controls.Add(selectButton); + } + + private void selectButton_Click(object sender, EventArgs e) + { + if (openFileDialog1.ShowDialog() == DialogResult.OK) + { + try + { + var filePath = openFileDialog1.FileName; + using (Stream str = openFileDialog1.OpenFile()) + { + Process.Start("notepad.exe", filePath); + } + } + catch (SecurityException ex) + { + MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" + + $"Details:\n\n{ex.StackTrace}"); + } + } + } +} diff --git a/dotnet-desktop-guide/samples/snippets/winforms/open-files/example2/vb/Form1.vb b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example2/vb/Form1.vb new file mode 100644 index 0000000000..5860a59c6a --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/open-files/example2/vb/Form1.vb @@ -0,0 +1,44 @@ +Imports System.ComponentModel +Imports System.Diagnostics +Imports System.IO +Imports System.Security +Imports System.Windows.Forms + +Public Class OpenFileDialogForm : Inherits Form + Dim WithEvents selectButton As Button + Dim openFileDialog1 As OpenFileDialog + + Public Shared Sub Main() + Application.SetCompatibleTextRenderingDefault(false) + Application.EnableVisualStyles() + Dim frm As New OpenFileDialogForm() + Application.Run(frm) + End Sub + + Private Sub New() + openFileDialog1 = New OpenFileDialog() With + { + .FileName = "Select a text file", + .Filter = "Text files (*.txt)|*.txt", + .Title = "Open text file" + } + + selectButton = New Button() With {.Text = "Select file"} + Controls.Add(selectButton) + End Sub + + Public Sub selectButton_Click(sender As Object, e As EventArgs) _ + Handles selectButton.Click + If OpenFileDialog1.ShowDialog() = DialogResult.OK Then + Try + Dim filePath = OpenFileDialog1.FileName + Using str = openFileDialog1.OpenFile() + Process.Start("notepad.exe", filePath) + End Using + Catch SecEx As SecurityException + MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" & + $"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}") + End Try + End If + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example1/cs/form1.cs b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example1/cs/form1.cs new file mode 100644 index 0000000000..83ba99c951 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example1/cs/form1.cs @@ -0,0 +1,62 @@ +using System; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; + +public class InvokeThreadSafeForm : Form +{ + private delegate void SafeCallDelegate(string text); + private Button button1; + private TextBox textBox1; + private Thread thread2 = null; + + [STAThread] + static void Main() + { + Application.SetCompatibleTextRenderingDefault(false); + Application.EnableVisualStyles(); + Application.Run(new InvokeThreadSafeForm()); + } + public InvokeThreadSafeForm() + { + button1 = new Button + { + Location = new Point(15, 55), + Size = new Size(240, 20), + Text = "Set text safely" + }; + button1.Click += new EventHandler(Button1_Click); + textBox1 = new TextBox + { + Location = new Point(15, 15), + Size = new Size(240, 20) + }; + Controls.Add(button1); + Controls.Add(textBox1); + } + + private void Button1_Click(object sender, EventArgs e) + { + thread2 = new Thread(new ThreadStart(SetText)); + thread2.Start(); + Thread.Sleep(1000); + } + + private void WriteTextSafe(string text) + { + if (textBox1.InvokeRequired) + { + var d = new SafeCallDelegate(WriteTextSafe); + textBox1.Invoke(d, new object[] { text }); + } + else + { + textBox1.Text = text; + } + } + + private void SetText() + { + WriteTextSafe("This text was set safely."); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example1/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example1/vb/form1.vb new file mode 100644 index 0000000000..4c42c256f8 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example1/vb/form1.vb @@ -0,0 +1,54 @@ +Imports System.Drawing +Imports System.Threading +Imports System.Windows.Forms + +Public Class InvokeThreadSafeForm : Inherits Form + + Public Shared Sub Main() + Application.SetCompatibleTextRenderingDefault(False) + Application.EnableVisualStyles() + Dim frm As New InvokeThreadSafeForm() + Application.Run(frm) + End Sub + + Dim WithEvents Button1 As Button + Dim TextBox1 As TextBox + Dim Thread2 as Thread = Nothing + + Delegate Sub SafeCallDelegate(text As String) + + Private Sub New() + Button1 = New Button() + With Button1 + .Location = New Point(15, 55) + .Size = New Size(240, 20) + .Text = "Set text safely" + End With + TextBox1 = New TextBox() + With TextBox1 + .Location = New Point(15, 15) + .Size = New Size(240, 20) + End With + Controls.Add(Button1) + Controls.Add(TextBox1) + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click + Thread2 = New Thread(New ThreadStart(AddressOf SetText)) + Thread2.Start() + Thread.Sleep(1000) + End Sub + + Private Sub WriteTextSafe(text As String) + If TextBox1.InvokeRequired Then + Dim d As New SafeCallDelegate(AddressOf SetText) + TextBox1.Invoke(d, New Object() {text}) + Else + TextBox1.Text = text + End If + End Sub + + Private Sub SetText() + WriteTextSafe("This text was set safely.") + End Sub +End Class diff --git a/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example2/cs/form1.cs b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example2/cs/form1.cs new file mode 100644 index 0000000000..3b2cb95247 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example2/cs/form1.cs @@ -0,0 +1,56 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Threading; +using System.Windows.Forms; + +public class BackgroundWorkerForm : Form +{ + private BackgroundWorker backgroundWorker1; + private Button button1; + private TextBox textBox1; + + [STAThread] + static void Main() + { + Application.SetCompatibleTextRenderingDefault(false); + Application.EnableVisualStyles(); + Application.Run(new BackgroundWorkerForm()); + } + public BackgroundWorkerForm() + { + backgroundWorker1 = new BackgroundWorker(); + backgroundWorker1.DoWork += new DoWorkEventHandler(BackgroundWorker1_DoWork); + backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker1_RunWorkerCompleted); + button1 = new Button + { + Location = new Point(15, 55), + Size = new Size(240, 20), + Text = "Set text safely with BackgroundWorker" + }; + button1.Click += new EventHandler(Button1_Click); + textBox1 = new TextBox + { + Location = new Point(15, 15), + Size = new Size(240, 20) + }; + Controls.Add(button1); + Controls.Add(textBox1); + } + private void Button1_Click(object sender, EventArgs e) + { + backgroundWorker1.RunWorkerAsync(); + } + + private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e) + { + // Sleep 2 seconds to emulate getting data. + Thread.Sleep(2000); + e.Result = "This text was set safely by BackgroundWorker."; + } + + private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + textBox1.Text = e.Result.ToString(); + } +} diff --git a/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example2/vb/form1.vb b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example2/vb/form1.vb new file mode 100644 index 0000000000..9f45f0fa69 --- /dev/null +++ b/dotnet-desktop-guide/samples/snippets/winforms/thread-safe/example2/vb/form1.vb @@ -0,0 +1,51 @@ +Imports System.ComponentModel +Imports System.Drawing +Imports System.Threading +Imports System.Windows.Forms + +Public Class BackgroundWorkerForm : Inherits Form + + Public Shared Sub Main() + Application.SetCompatibleTextRenderingDefault(False) + Application.EnableVisualStyles() + Dim frm As New BackgroundWorkerForm() + Application.Run(frm) + End Sub + + Dim WithEvents BackgroundWorker1 As BackgroundWorker + Dim WithEvents Button1 As Button + Dim TextBox1 As TextBox + + Private Sub New() + BackgroundWorker1 = New BackgroundWorker() + Button1 = New Button() + With Button1 + .Text = "Set text safely with BackgroundWorker" + .Location = New Point(15, 55) + .Size = New Size(240, 20) + End With + TextBox1 = New TextBox() + With TextBox1 + .Location = New Point(15, 15) + .Size = New Size(240, 20) + End With + Controls.Add(Button1) + Controls.Add(TextBox1) + End Sub + + Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click + BackgroundWorker1.RunWorkerAsync() + End Sub + + Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) _ + Handles BackgroundWorker1.DoWork + ' Sleep 2 seconds to emulate getting data. + Thread.Sleep(2000) + e.Result = "This text was set safely by BackgroundWorker." + End Sub + + Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) _ + Handles BackgroundWorker1.RunWorkerCompleted + textBox1.Text = e.Result.ToString() + End Sub +End Class