我运行另一个进程后如何激活我的应用程序 - C#

时间:2013-07-05 06:41:23

标签: c# .net process activation

当文本框获得焦点时,我正在运行虚拟键盘,但键盘应用程序会被聚焦,并且不会将键传输到文本框。 如果我单击文本框以激活它,一切都很好,但我希望我的应用程序在vKeyboard进程运行后被激活。 这是我到目前为止所尝试的:

        [DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    [DllImport("user32.dll")]
    internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

...

        vKeyboard = Process.Start(keyboardPath);
        SetFocusToApplication(handle);

...

        private static void SetFocusToApplication(IntPtr handle)
    {
        Process currentProcess = Process.GetCurrentProcess();
        IntPtr hWnd = currentProcess.MainWindowHandle;
        if (hWnd != IntPtr.Zero)
        {
            SetForegroundWindow(handle);
            ShowWindow(hWnd,3);
        }
    }

我也尝试将Alt + Tab发送到键盘进程,但它不起作用:

        private static void AltTab(IntPtr handle)
    {
             vKeyboard.WaitForInputIdle(); 

       int WM_SYSCOMMAND = 0x0112;
        int SC_PREVWINDOW = 0xF050;
        PostMessage(vKeyboard.MainWindowHandle, WM_SYSCOMMAND, (IntPtr)SC_PREVWINDOW, (IntPtr)0);
    }

PS:我有虚拟键盘的源代码,如果我可以从那里做任何事情来停用它自己,仍然很好。让我知道。 键盘最顶层属性也设置为true,不确定是否有任何不同。

这是我在按钮点击中尝试并执行的代码:

           Process vKeyboard;
      string keyboardPath = Application.StartupPath + "\\vKeyboard.exe";
        vKeyboard = Process.Start(keyboardPath);

3 个答案:

答案 0 :(得分:1)

要将表格放在前面,请使用:

this.Activate();

我尝试了以下代码,并且每件事情都完美无缺(我在Timer.Tick事件中编写了此代码):

System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("osk");
if (proc.Length > 0)
{
    this.Activate();
    textBox1.Focus(); //i focused it so i can write in it using on-screen keyboard
}

答案 1 :(得分:1)

更改屏幕键盘的源代码,以便表单具有WS_EX_NOACTIVATE标志:

public partial class OnScreenKeyboard : Form
{

    private const int WS_EX_NOACTIVATE = 0x08000000;

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams p = base.CreateParams;
            p.ExStyle |= WS_EX_NOACTIVATE;
            return p;
        }
    }

}

这将阻止OSK获得焦点,从而允许键以当前活动的应用程序为目标。

有关详细信息,请参阅this上一个问题中的示例。

答案 2 :(得分:0)

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

private void ActivateWindow()
{
    SetForegroundWindow(this.Handle);
}

使用此代码,它应该位于主应用程序窗口中。如果没有,则需要通过主窗口的“句柄”更改“ this.Handle”。