
以前はPySide6で作りました。
touch-sp.hatenablog.com
今回は以前のものをWindowsフォームアプリケーションに移植しました。
方法
Claude 3.5 Sonnetを使っています。以下のPythonスクリプトをC#を使ったWindowsフォームアプリケーションに移植して下さい。 ``` (以前書いたPythonスクリプトをコピー) ```
これだけです(笑)
ただし以下は手動で行っています。
- フォームの名前を変える
- フォームにリストボックスを配置する
- リストボックスのフォントを変える
- リストボックスにKeyDownとMouseDoubleClickのイベントを追加する
コード
using System; using System.Diagnostics; using System.Text; using System.Windows.Forms; namespace startWSL { public partial class Form1: Form { public Form1() { InitializeComponent(); LoadWSLDistributions(); } private void LoadWSLDistributions() { var distributions = GetWSLDistributions(); if (distributions != null) { string[] distributionLines = distributions .Replace("*", " ") .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Skip the header line and add distribution names for (int i = 1; i < distributionLines.Length; i++) { string distName = distributionLines[i].Trim().Split()[0]; listBox1.Items.Add(distName); } } else { MessageBox.Show("Unable to retrieve WSL distributions.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } private string GetWSLDistributions() { try { ProcessStartInfo startInfo = new ProcessStartInfo { FileName = "wsl", Arguments = "-l -v", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, StandardOutputEncoding = Encoding.Unicode }; using (Process process = Process.Start(startInfo)) { string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return output; } } catch (Exception ex) { MessageBox.Show($"Error executing command: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } } private void listBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { start_wsl(); Close(); } } private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) { start_wsl(); Close(); } private void start_wsl() { if (listBox1.SelectedItem == null) { MessageBox.Show("Please select a distribution.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { ProcessStartInfo startInfo = new ProcessStartInfo { FileName = "wsl", Arguments = $"-d {listBox1.SelectedItem} -u hoge", UseShellExecute = true }; Process.Start(startInfo); Application.Exit(); } catch(Exception ex) { MessageBox.Show($"Error starting WSL: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }