。C#/。NET:文本框是不是'集中'后,进程启动文本框、进程、NET

2023-09-04 06:36:57 作者:滚伱媽的虚情假意

我打开记事本后,有一个问题,当我点击按钮btnSearch。

I am having a problem after opening the notepad once I click the button "btnSearch".

我们的想法是,一​​旦我点击按钮btnSearch,在文本框txtSearch'应该是'集中',即使一个进程启动/主窗口外面打开。

The idea is that once I clicked the button 'btnSearch', the textbox 'txtSearch' should be 'focused' even after a process was initiated/opened outside the main window.

下面是我的code:

    private void btnSearch_Click(object sender, RoutedEventArgs e)
    {
        System.Diagnostics.Process.Start("notepad");
        txtSearch.Focus(); // not working
    }

有什么建议?

推荐答案

下面是code,你将需要。这可以通过互操作的服务来完成

The below is the code you would need. This could be done through interop services

    private void setwind()
    {

        System.Diagnostics.Process.Start("notepad");

        System.Threading.Thread.Sleep(2000);  //  To give time for the notepad to open

        if (GetForegroundWindow() != this.Handle)
        {
            SetForegroundWindow(this.Handle);
        }
    }


    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();