Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enable the console in a WPF .NET Core application?

Tags:

c#

.net-core

wpf

I'm trying out WPF .NET Core for the first time, and one of the things I always do in a new WPF .NET Framework project is turn on the console, but I receive an error when I try to do this in .NET Core.

In traditional WPF, targeting .NET Framework, this was fairly simple;

  • Set the Build Action for App.xaml to Page
  • Define a Main method somewhere, and tag it with the STAThreadAttribute
  • In the project settings, set the output type to Console Application, and set the Startup object to wherever you put the Main method

I replicated these steps in the WPF .NET Core, but I get an error when I try to change the Build Action for App.xaml

The error (it occurs immediately after selecting Page in the dropdown in the Properties window):

An error has occurred while saving the edited properties listed below:
    Build Action
One or more values are invalid. 
Cannot add 'App.xaml' to the project, because the path is explicitly excluded from the project 
(C:\Program Files\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.NET.Sdk.WindowsDesktop.targets (45,5)).

Does anyone know a way around this, or another way to enable the console in WPF .NET Core?

like image 625
Sef Avatar asked Jan 26 '23 18:01

Sef


2 Answers

Setting the following properties will make your WPF application a "Console Application"

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <DisableWinExeOutputInference>true</DisableWinExeOutputInference>
</PropertyGroup>

The SDK automatically change OutputType from Exe to WinExe for WPF and WinForms apps. See https://learn.microsoft.com/en-us/dotnet/core/compatibility/windows-forms/5.0/automatically-infer-winexe-output-type

like image 186
fjch1997 Avatar answered Jan 29 '23 22:01

fjch1997


After some trial and error, I figured out that the .csproj file got messed up. I don't know how exactly it went wrong, I suspect it had to do with editing the project through its Properties window in that version of VS2019.

I edited the .csproj by hand, and it works if it looks as follows:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
    <ApplicationIcon />
    <StartupObject>ProjectName.App</StartupObject>
  </PropertyGroup>

  <ItemGroup>
    <Page Include="App.xaml"></Page>
  </ItemGroup>

  <ItemGroup>
    <ApplicationDefinition Remove="App.xaml"></ApplicationDefinition>      <--- key part
  </ItemGroup>

</Project>

I checked the .csproj file for a working .NET Framework project, and the key seems to be removing App.xaml as ApplicationDefinition by hand, as the .NET Framework .csproj did not have that section in it.

like image 36
Sef Avatar answered Jan 29 '23 20:01

Sef