如何关注表单C#

时间:2017-02-03 16:07:03

标签: c# .net windows

由于某种原因,即使它在最顶层和Activate()上打开,我的表单也不会始终聚焦;和焦点();和BringToFront();都被称为。

程序和源代码: sites.google.com/site/windowsprogramfortranslation /

我在所有这些地方添加了所有这些内容,但Google翻译的形式和文本框仍未被选中

void FormMain_Shown(object sender, EventArgs e)
{
    BringToFront();
    webBrowserMain.Focus();
    panelMain.Enabled = false;
    Focus();
    panelMain.Enabled = true;
    Activate();
    webBrowserMain.Select();
    webBrowserMain.Focus();
}

void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (webBrowserMain.ReadyState == WebBrowserReadyState.Complete)
    {
        this.Activate();
        webBrowserMain.Select();
        webBrowserMain.Focus();

        int numOfTries = 0;
        repeat:
        if (numOfTries < 10)
        {
            try
            {
                webBrowserMain.Document.Window.ScrollTo(0, 0);
                webBrowserMain.Document.GetElementById("source").Focus();
                //webBrowserMain.Document.GetElementById("source").InvokeMember("click");
            }
            catch
            {//if the document hasn't loaded yet
                numOfTries++;
                System.Threading.Thread.Sleep(40);
                goto repeat;
            }
        }
    }
}

public static void openTranslateWindow()
{
    formMain.Show();
    formMain.TopMost = true;
    formMain.WindowState = FormWindowState.Minimized;
    formMain.Show();
    formMain.WindowState = FormWindowState.Normal;
    formMain.BringToFront();

    formMain.webBrowserMain.Focus();

    formMain.panelMain.Enabled = false;
    formMain.Focus();
    formMain.panelMain.Enabled = true;
    formMain.Activate();
    formMain.webBrowserMain.Select();
    formMain.webBrowserMain.Focus();
}

1 个答案:

答案 0 :(得分:1)

尝试在显示主窗体时设置文本框焦点,而不是在文档完成时设置。

private void FormMain_Shown(object sender, EventArgs e)
{
    BringToFront();
    HtmlElement textArea = webBrowserMain.Document.GetElementById("source");
    if (textArea != null)
    {
        textArea.Focus();
    }
}