If you are playing with C++/CLI you are probably already familiar with the C# or VB.NET way of doing WinForms, so there's nothing to be afraid of in CLI -- it is just a bit of pain in the ass at first.
Assuming that you have C++/CLI installed, fire up Visual Studio and create an empty CLR project. Once the project is created, we need to let Visual Studio know what type of project (WinForms in this case) this is, as well as set an entry point for the application.
Open the project's Properties dialog (Alt+Enter) and select All Platforms from the Platform combo box. After that, you need to:
- Navigate to
Configuration Properties >> Linker >> System
in the tree-view control on the left side. - Select the SubSystem setting and choose "Windows (/SUBSYSTEM:WINDOWS)" from the drop-down list.
- Navigate to
Configuration Properties >> Linker >> Advanced
. - Select the Entry Point setting and type "Main".
That's it with the Properties dialog. Press "Apply" and close it.
This is both the fun and annoying part.
- Open the Add New Item dialog (Ctrl+Shift+A) and select UI in the tree-view on the left side.
- Select Windows Form; name it whatever you want then press "Add".
Yes, you will be greeted with an error -- HRESULT: 0x8000000A. Remember when I said there's an annoying part to this? Well, according to a Microsoft employee on the Visual Studio development team, this error is by design. However, the fix is rather easy:
- Close the tab showing the error.
- Open the Add New Item dialog (Ctrl+Shift+A) and select C++ File (.cpp). Name it (it can be anything, but preferably, the name of your project) and press "Add".
- In your new empty source file, paste the following code:
// Change 'ProjectName' and 'FormName' to your correct project and form names #include "FormName.h" using namespace ProjectName; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] void Main() { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); Application::Run(gcnew ProjectName::FormName); }
- Back to the Solution Explorer panel, right-click on the project then select Unload Project. Now repeat the step but select Reload Project.
Voila! Your form can now be seen in all of its glory.
- This guide applies to Visual Studio 2017 and up. Behaviour may be different on earlier versions of the software.
- Keep in mind that C++/CLI was invented for the purpose of bridging native code to .NET. It's not meant to be an alternative or replacement for C#/VB.