如何在C#中从控制台窗口回放焦点?

时间:2014-04-01 08:00:35

标签: c# winapi user-interface console focus

我有一个用黑色Windows控制台打开的C#控制台应用程序(A)。有时在创业时它会从另一个需要焦点的程序(B)中窃取焦点。

问题:如何将焦点从A.exe反馈回B.exe

A -> Focus -> B

<小时/> 的详细说明:

  • B计划不是我的,我无能为力。它有一个GUI,多个窗口,其中一个需要焦点(它可能是一个模态对话框窗口)。
  • 程序A不需要任何关注,也不会以任何方式与程序B进行交互。
  • 程序A通过启动快捷方式启动,基本上在后台运行(它已发布但仍在开发中,这就是控制台窗口的原因)
  • 我有一些时间/最多几分钟检查并重点关注。

2 个答案:

答案 0 :(得分:4)

// this should do the trick....

[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr WindowHandle);

public const int SW_RESTORE = 9;

private void FocusProcess(string procName)
{
    Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName);
    if (objProcesses.Length > 0)
    {
        IntPtr hWnd = IntPtr.Zero;
        hWnd = objProcesses[0].MainWindowHandle;
        ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
        SetForegroundWindow(objProcesses[0].MainWindowHandle);
    }
}

答案 1 :(得分:0)

要针对当前正在运行的C#控制台应用程序执行此操作...

[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
public const int SW_RESTORE = 9;
static void FocusMe()
{
    string originalTitle = Console.Title;
    string uniqueTitle = Guid.NewGuid().ToString();
    Console.Title = uniqueTitle;
    Thread.Sleep(50);
    IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);

    Console.Title = originalTitle;

    ShowWindowAsync(new HandleRef(null, handle), SW_RESTORE);
    SetForegroundWindow(handle);
}