LoginSignup
1
0

More than 1 year has passed since last update.

.NET 5.0 でSystem.Windows.Formを使うコンソールアプリ --メモ--

Last updated at Posted at 2021-08-27

以前、.NET framework 4.xでコンソールアプリを作ったのだが、その中で System.Windows.Forms.Clipboardクラス を使っている。
これを.NET5.0 (旧称 .NET Core)で作り直したいと思ったら、予想外に大変だった。参照の追加で.NET Frameworkにはあったはずのアセンブリの項目がどこにもない。
また、.NET5.0ではマルチプラットフォームを意識したものになった分、Windowsで従来通りシンプルに使いたいだけの者には敷居が高くなっている気がするが、こちらが正式な.NET Frameworkの後継であるようなので乗り換えてみたい。

以下、メモ。

新規で.NET 5.0のコンソールアプリのプロジェクト作成。
ソリューションエクスプローラ > プロジェクトファイルの編集

すると、デフォルトで以下の通り。

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

</Project>

OutPutTypeだけを残して、これを以下のように修正。

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <!-- ここから -->
    <TargetFramework>net5.0-windows</TargetFramework>
    <DisableWinExeOutputInference>true</DisableWinExeOutputInference>
    <UseWindowsForms>true</UseWindowsForms>
    <!-- ここまで -->
  </PropertyGroup>

</Project>

<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
<UseWindowsForms>true</UseWindowsForms>

は2つ揃ってはじめてコンソールのウィンドウが出てくるようだ。

これで準備完了。

using System;
using System.Windows.Forms;

namespace ConsoleApp7
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Console.WriteLine("コピーしてあるテキストを表示。");
            if (Clipboard.ContainsText())
            {
                Console.WriteLine(Clipboard.GetText());
            }
        }
    }
}

[参考]
WPF/Windowsフォームに関する.NET 5の大きな変更
.NET 5 プロジェクトの TargetFramework

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0