【发布时间】:2021-03-14 19:36:11
【问题描述】:
我在 WinForm 中弹出了一个 WinForm。如果我关闭内部 Winform 并重新打开它,则文本框中的文本不会突出显示。但是,如果我关闭两个 WinForm 并重新打开第一个然后再打开内部 WinForm,文本框中的文本将突出显示。
如何让内部 WinForm 文本每次都突出显示?
我尝试了两种我知道/最常见的突出显示文本的方法,但它们似乎只在第一次工作。
感谢任何和所有帮助/指导。
正在从外部 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;
}
}
}
【问题讨论】:
-
表单只加载一次,除非你销毁它。您可能还想在处理程序中处理表单的
Enter或GotFocus事件和 inovketitleTextBox.Focus()。 -
@Marshal 也许您的意思是在 Form.Activated 上设置 ActiveControl。在焦点事件中移动焦点是一件非常糟糕的事情。备注部分,例如 Control.Enter
-
@Jimi:好电话。在这种情况下它将是
Form.Activated -
投反对票可能是因为您没有显示表单是如何关闭然后重新打开的。您需要展示一个可重现的示例来演示该问题。当您说
SelectAll第二次不起作用时,您是否设置了断点并验证它是否被第二次调用?Load事件本身似乎很可能没有第二次运行,因为正在重复使用相同的表单。 -
@Marshal,Form.activated 的想法奏效了。它现在每次都有效。如果您想将其发布为答案,我会将其标记为正确。
标签: c# winforms highlight selectall