Make it easier to reference WinForms and other libraries in .NET 5/Core console and library projects

Brandon Stewart 136 Reputation points
2021-04-04T19:31:10.653+00:00

Would the Visual Basic development team at Microsoft please, please, please make it easier to reference WinForms (and other libraries) when creating .NET 5/Core console program and DLL library projects? I very often need to use message boxes in both types of projects, and other user forms within libraries. Currently, we must manually type in the reference within the MyApp.vbproj project file because WinForms is not available in the project references tab. Yes, I know that console apps and WinForms apps are two separate entities, but it is very convenient to be able to mix the two.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,897 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,431 Reputation points
    2021-04-05T10:57:42.383+00:00

    Hello,

    A decent alternative to what you are doing now is

    1. Create a new project e.g. class project
    2. Alter the project file as you are doing now
    3. From Visual Studio's menu select Project,
    4. Select Export Template
    5. Follow the prompts to export a project
    6. Select the project
    7. Fill in the default name for a project
    8. Fill in a description
    9. Finish up
    10. Restart Visual Studio
    11. Type in the name of the template e.g. my template for a class project for .NET 5 is PayneClassProject
    12. Give a name for the project, done,

    Once done a folder opens, if you need to share the template this is where other developers place the .zip file

    84483-f1.png

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Ken Tucker 5,851 Reputation points
    2021-04-04T21:37:52.033+00:00

    Try this. Change the TFM (Target Framework Monitor) from .net 5 to .net-windows in the console apps project file and add UseWindowsForms

    <Project Sdk="Microsoft.NET.Sdk">
    
        <PropertyGroup>
           <OutputType>Exe</OutputType>
          <TargetFramework>net5.0-windows</TargetFramework>
          <UseWindowsForms>true</UseWindowsForms>
       </PropertyGroup>
     </Project>
    

    Then you could try something like this in your code

    using System;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsInConsole
    {
         class Program
        {
              static void Main(string[] args)
             {
                    Console.WriteLine("Hello World!");
                   MessageBox.Show("Test");
             }
        }
    }
    

    Sample on GitHub


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.