c# - Winforms - SelectAll() 不能始终在内部 Winforms 文本框上工作

c# - Winforms - SelectAll() not working on inner Winforms textbox consistently

我在 WinForm 中弹出了一个 WinForm。如果我关闭内部 Winform 并重新打开它,文本框中的文本不会突出显示。但是,如果我关闭两个 WinForm,然后重新打开第一个 WinForm,然后重新打开内部 WinForm,文本框中的文本将突出显示。

如何让内部 WinForm 文本每次都高亮显示?

我已经尝试了两种我知道的/最常用的突出显示文本的方法,但它们似乎只在第一次使用时有效。

感谢所有help/direction。

正在从外部 Winforms 中的 .ShowDialog(); 调用内部 Winforms。

portalTitleEntryForm.ShowDialog();

这是我的内部 Winform 代码和我尝试过的代码:


public partial class PortalTitleEntryForm : Form
    {
        public string portalEntryTitle;
        public string dialogResult;

        public PortalTitleEntryForm()
        {
            InitializeComponent();
        }

    private void Form1_Load(object sender, EventArgs e)
        {
            titleTextBox.TabIndex = 0;
            continueButton.TabIndex = 1;
            cancelButton.TabIndex = 2;

            this.CancelButton = cancelButton;
            this.AcceptButton = continueButton;

            titleTextBox.Focus();
            if (portalEntryTitle != null || !portalEntryTitle.Equals(""))
            {
                titleTextBox.Focus();
                titleTextBox.Text = portalEntryTitle;
                /*titleTextBox.SelectionStart = 0; // doesn't work the second time
                titleTextBox.SelectionLength = titleTextBox.Text.Length;*/ // doesn't work the second time
                titleTextBox.SelectAll();  // doesn't work the second time
                bool focusStatus = titleTextBox.Focused; // bool equals false the second
                //titleTextBox.Focus(); // doesn't work the second time around

            }

    private void continueButton_Click(object sender, EventArgs e)
        {

            if (!titleTextBox.Text.Equals(""))
            {
                portalEntryTitle = titleTextBox.Text;
                dialogResult = DialogResult.OK.ToString();
                continueButton.DialogResult = DialogResult.OK;
                Close();
                return;
            }
            else if (titleTextBox.Text.Equals(""))
            {
                MessageBox.Show("Please give your entry a title.", "M3dida", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
        }
    private void cancelButton_Click(object sender, EventArgs e)
        {
            dialogResult = DialogResult.Cancel.ToString();
            Debug.WriteLine("Cancel button was clicked");
            Close();
            return;
        }
    }
}

表单只加载一次,除非它被销毁。

您可能想要处理 Form.Activated 事件并在处理程序中调用 titleTextBox.Focus()