簡體   English   中英

有沒有一種方法可以在c#winform中的文本框中單擊一次全部選擇?

[英]Is there a way to select all with one click in a textbox in c# winform?

我正在做一個數字猜謎游戲,為方便起見,我想在程序中添加一行代碼,只需單擊一下即可選擇文本框中的所有文本。 我已經嘗試過在這里找到的所有內容以及在Google上找到的其他故障排除網站,但似乎都沒有用,甚至試圖將精力集中在文本框上。 該文本框仍然像普通文本框一樣運行,即必須雙擊以全選。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace randomNumberGuessingGameFourthTry
{
     public partial class Form1 : Form
     {
         public Form1()
         {
          InitializeComponent();
         }

    private void startGame_Click(object sender, EventArgs e)
    {
        if (min.Text == "" || min.Text == " " || min.Text == "Min")
        {
            MessageBox.Show("You didn't enter a minimum value of zero or greater so the default value of 0 was set.");
            min.Text = "0";
        }

        if (max.Text == "" || max.Text == " " || max.Text == "Max")
        {
            MessageBox.Show("You didn't enter a maximum value so the default value of 10 was set.");
            max.Text = "11";
        }

        startGuessing startGame = new startGuessing(min.Text, max.Text);
        this.Hide();
        startGame.ShowDialog();
    }

   private void exitGame_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void min_TextChanged(object sender, EventArgs e)
    {
        min.Focus();
        min.SelectAll();
        min.SelectionLength = min.Text.Length;

        int userInput1 = Convert.ToInt32(min.Text);
        if (!(userInput1 >= 0))
        {
            MessageBox.Show("Your min range must be at least 0 or higher", "Invalid range found");
        }
    }

    private void max_TextChanged(object sender, EventArgs e)
    {


        int userInput1 = Convert.ToInt32(min.Text);
        int userInput2 = Convert.ToInt32(max.Text);
        if (!(userInput2 <= userInput1 + 9))
        {
            MessageBox.Show("Your max range must be at least 10 digits higher than " + userInput1, "Invalid range found");
        }
    }
}

}

上面是我的form1.cs的代碼,我認為如果可以在這里運行,可以在此程序的第二個窗體上運行。

您應該先調用SelectAll()方法,然后調用Focus() ,而不是相反。 這個最小的例子對我有用:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox1.Click += TextBoxOnClick;
    }

    private void TextBoxOnClick(object sender, EventArgs eventArgs)
    {
        var textBox = (TextBox) sender;
        textBox.SelectAll();
        textBox.Focus();
    }
}

你嘗試了什么?

以下對我有用:

private void textBox1_Click(object sender, EventArgs e)
{
    TextBox textBox = (TextBox)sender;

    textBox.SelectAll();
}

自然,您需要將textBox1_Click()添加為TextBoxClick事件的事件處理程序。

請注意,以上內容將導致始終在控件中單擊鼠標即可完全選擇文本。 這樣將無法使用鼠標選擇部分文本。 如果您想要更復雜的行為,則可以使用此處找到的答案:

使WinForms TextBox的行為類似於瀏覽器的地址欄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM