概要
ボタンを押したらコンソールアプリを実行し、結果を画面に表示します。
プロジェクトの作成
新しいプロジェクトの作成でWPFアプリケーション
を、プロジェクト名:ConsoleGUI_1
、フレームワーク:.NET 6.0
で作成してください。
画面の作成
App.xaml
に以下のスタイルを定義します。
<!-- 標準的なウィンドウのスタイル -->
<Style x:Key="StandardWindowStyle"
TargetType="Window">
<Setter Property="Background"
Value="WhiteSmoke" />
<Setter Property="ResizeMode"
Value="CanResizeWithGrip" />
</Style>
MainWindow.xaml
のWindow
に
Style="{StaticResource StandardWindowStyle}"
を追加します。
Window.Resources
にボタンの既定スタイルを定義します。
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Margin"
Value="10,10,0,10" />
<Setter Property="Padding"
Value="20,5" />
</Style>
</Window.Resources>
Grid
の中身を書きます。
Grid
を2行に分割し、上の行にはボタンを並べ、下の行は実行結果を表示するテキストボックスを配置します。
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button x:Name="IpConfigButton"
Content="ipconfig" />
<Button Content="Button" />
<Button Content="Button" />
</StackPanel>
<!-- コマンド実行結果 -->
<TextBox x:Name="CmdResult"
Grid.Row="1"
Background="#333333"
Foreground="LightGray"
Margin="10,0,10,10"
Padding="5"
IsReadOnly="True"
VerticalScrollBarVisibility="Auto"
FontFamily="BIZ UDGothic" />
Window
に
FocusManager.FocusedElement="{Binding ElementName=IpConfigButton}"
を追加して初期フォーカスをipconfig
ボタンに設定します。
ロジックの作成
ipconfig
ボタンのClick
イベントハンドラを作成し、以下を入力します。
try
{
IsEnabled = false;
var psi = new ProcessStartInfo()
{
// 起動するアプリケーション
FileName = "ipconfig.exe",
// コマンドライン引数
Arguments = "/all",
// プロセス用の新しいウィンドウを作成せずにプロセスを起動するか
CreateNoWindow = true,
// プロセスの起動にOSのシェルを使用するかどうか
UseShellExecute = false,
// アプリケーションのテキスト出力を StandardOutput ストリームに書き込むか
RedirectStandardOutput = true,
};
// コマンド実行
Process? cmdProcess = Process.Start(psi);
// 標準出力読み取り
string? output = cmdProcess?.StandardOutput?.ReadToEnd();
CmdResult.Text = output;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
IsEnabled = true;
}
エラー部分を解消して完成です。
実行
実行してみます。
ipconfig
ボタンを押します。
実行結果が下に表示されました。