Reputation: 430
I'm developing .net core console application. I want to alert to user when want to exit application. Like below;
MessageBox.Show("Contiue or not", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1) == DialogResult.No)
Application.Exit();
But I can't add System.Windows.Forms referance to the my project. I'm getting this error.
Error CS0234 The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)
Is that possible to show Message Box on .net core Console Application?
Upvotes: 6
Views: 6899
Reputation: 61
Some console apps need this line added to the project as well...
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
Adding this to the example in Daniil's post would give you this...
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<!--Insert DisableWinExeOutputInference here -->
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
</PropertyGroup>
</Project>
Upvotes: 1
Reputation: 1220
In order to use Windows Forms you need to modify .csproj
:
UseWindowsForms
to true
-windows
to TargetFramework
(e.g. net6.0-windows
)ConsoleApp.csproj
:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
</Project>
Program.cs
:
System.Console.WriteLine("Hello, Console!");
System.Windows.Forms.MessageBox.Show("Hello, Popup!");
Result:
Notes:
OutputType
in .csproj
to WinExe
instead of Exe
.Cross-platform ConsoleApp.csproj
:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Configurations>Debug;Release;WindowsDebug;WindowsRelease</Configurations>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'WindowsDebug' Or '$(Configuration)' == 'WindowsRelease'">
<DefineConstants>WindowsRuntime</DefineConstants>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
</Project>
Cross-platform Program.cs
System.Console.WriteLine("Hello, Console!");
#if WindowsRuntime
System.Windows.Forms.MessageBox.Show("Hello, Popup!");
#endif
Upvotes: 7