Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-7-sonnet-20250219· AnthropicHugging Face LMArena Human Preference 140K

C#でmutexを使用して、モーダレスの子画面が1つしか表示できないようにして

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-haiku-20241022’s answer.
  1. User

    C#でmutexを使用して、モーダレスの子画面が1つしか表示できないようにして

  2. Claude Assistant

    C#でMutexを使用して、モーダレスの子画面を1つだけ表示できるようにするコードの例です:

    using System;
    using System.Threading;
    using System.Windows.Forms;
    
    public class MainForm : Form
    {
        private Mutex _mutex;
        private const string MutexName = "UniqueChildFormMutex";
        
        public MainForm()
        {
            Button openButton = new Button
            {
                Text = "子画面を開く",
                Location = new System.Drawing.Point(50, 50)
            };
            
            openButton.Click += OpenChildForm;
            Controls.Add(openButton);
        }
        
        private void OpenChildForm(object sender, EventArgs e)
        {
            bool createdNew;
            
            // Mutexを取得しようとする
            _mutex = new Mutex(true, MutexName, out createdNew);
            
            // 新しいMutexが作成された場合は、子画面がまだ開かれていない
            if (createdNew)
            {
                ChildForm childForm = new ChildForm();
                childForm.FormClosed += ChildForm_FormClosed;
                childForm.Show(); // モーダレスで表示
            }
            else
            {
                // すでに子画面が開かれている場合は、Mutexを解放
                if (_mutex != null)
                {
                    _mutex.ReleaseMutex();
                    _mutex.Dispose();
                    _mutex = null;
                }
                
                MessageBox.Show("子画面はすでに開かれています。");
            }
        }
        
        private void ChildForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 子画面が閉じられたらMutexを解放
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
                _mutex = null;
            }
        }
    }
    
    public class ChildForm : Form
    {
        public ChildForm()
        {
            Text = "子画面";
            Size = new System.Drawing.Size(300, 200);
        }
    }
    
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
    

    このコードについて説明や詳細が必要ですか?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.