如何给回焦点从控制台窗口在C#中? [英] How To Give Back Focus From Console Window in C#?

查看:1033
本文介绍了如何给回焦点从控制台窗口在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用黑色的窗户控制台打开一个C#控制台应用程序(A)。有时在启动时从另一个程序(B)中的窃取重点需要焦点



问:如何我可以给重点从 A.exe时 B.EXE

  A  - >焦点 - >乙





详细内容:




  • b计划是不是我的,我不能做任何事情。它有一个图形用户界面,多个窗口,其中1需要重点(这可能是一个模式对话框窗口)。

  • 程序一个不需要任何的焦点,它不会在交互任何方式与b方案。

  • 程序A通过启动快捷方式启动并在后台基本运行(这是释放,但仍处于开发阶段,虽然,这就是为什么控制台窗口)

  • 我有一些时间/最多分钟检查并给予重点回来。


解决方案

  //这应该做的伎俩...... 

函数[DllImport(user32.dll中)]
公共静态外部布尔ShowWindowAsync(HandleRef的hWnd,诠释的nCmdShow);
函数[DllImport(user32.dll中)]
公共静态的extern BOOL SetForegroundWindow(IntPtr的WindowHandle);

公共const int的SW_RESTORE = 9;

私人无效FocusProcess(字符串PROCNAME)
{
过程[] = objProcesses System.Diagnostics.Process.GetProcessesByName(PROCNAME);
如果(objProcesses.Length大于0)
{
的IntPtr的HWND = IntPtr.Zero;
的hWnd = objProcesses [0] .MainWindowHandle;
ShowWindowAsync(新HandleRef(NULL,的hWnd),SW_RESTORE);
SetForegroundWindow(objProcesses [0] .MainWindowHandle);
}
}


I have a C# console application (A) that opens with the black windows console. Sometimes at startup it steals the focus from another program (B) that needs the focus.

Question: How can I give focus back from A.exe to B.exe ?

A -> Focus -> B


Details:

  • Program B is not mine and I can't do anything about it. It has a GUI, multiple windows and 1 of them needs the focus (it might be a modal dialog window).
  • Program A doesn't need any focus and it doesn't interact in any way with program B.
  • Program A starts via Startup shortcut and runs basically in background (it is released but still in development though, that's why console window)
  • I have a few moments/up to minutes to check and give the focus back.

解决方案

// 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);
    }
}

这篇关于如何给回焦点从控制台窗口在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆