2

Windowsフォームでプロンプトを使用するときにテキストボックスを自動選択するにはどうすればよいか疑問に思いました。以下の私のコードは私が試したことを示していますが、それでもテキストボックスではなくボタンに焦点を当てています。よろしくお願いします。

            Form prompt = new Form();
            prompt.Width = 500;
            prompt.Height = 200;
            prompt.Text = caption;
            Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
            TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
            Button confirmation = new Button() { Text = "Ok", Left = 50, Width = 100, Top = 90 };
            confirmation.Click += (sender, e) => { prompt.Close(); };
            textBox.Select();
            textBox.Focus();
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.Controls.Add(textBox);
            prompt.ShowDialog();
            return textBox.Text;
4

1 に答える 1

5

フォームが表示されるまで、テキストボックスにフォーカスを合わせるのを待つ必要があります。フォームが初めて表示される前は、何にも焦点を合わせることができません。フォームが最初に表示された後、イベントを使用しShownてコードを実行できます。

string text = "Text";
string caption = "caption";
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 200;
prompt.Text = caption;
Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
Button confirmation = new Button() { Text = "Ok", Left = 50, Width = 100, Top = 90 };
confirmation.Click += (s, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Shown += (s, e) => textBox.Focus();
prompt.ShowDialog();
return textBox.Text;
于 2013-02-15T20:14:34.203 に答える