Windows窗体:设置窗体可见性基于启用外部窗口的焦点

时间:2009-09-21 14:33:27

标签: c# winforms forms

我想创建一个Windows窗体应用程序,只有在启用/聚焦另一个外部窗口(notepad.exe)后才能看到它。任何提示,我都不知道从哪里开始。

如果我的表单正在运行,我希望它在启用记事本时弹出,并在记事本失去焦点时消失。

2 个答案:

答案 0 :(得分:0)

您可以尝试查看适用于C#的Windows自动化API。有了这些,您应该能够查看所有打开的窗口并找到记事本。我没有看过API的一堆,但最好的基本情况是你可以处理的窗口会有一个activate / lostfocus事件。最糟糕的情况是,你可以每100毫秒左右轮询一次,看看记事本窗口是否有焦点。

答案 1 :(得分:0)

您只需使用API​​调用和计时器即可完成此操作。将此行添加到表单的使用语句中:

using System.Runtime.InteropServices;

接下来,将这些声明添加到表单中:

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, 
    string lpWindowName); 

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

最后,在表单上放置一个Timer,并将其Enabled属性设置为true。在其Tick事件中,输入以下代码:

IntPtr hWndNotepad = FindWindow(null, "Whatever.txt - Notepad");
IntPtr hWndForegroundWindow = GetForegroundWindow();
if (this.Handle != hWndForegroundWindow)
{
    this.Visible = (hWndNotepad == hWndForegroundWindow);
}

我没有测试过这段代码,但它应该可行。代码正在查找要在记事本中打开的特定文件;一个不同的文件会导致标题栏中的文本不同,所以这段代码不起作用。我认为如果你将FindWindow调用更改为FindWindow("notepad", null),它将适用于任何打开的记事本实例(它可能是“notepad.exe” - 不确定)。

更新:如果您希望在任何记事本实例打开时显示您的表单,您可以将此代码放入Timer的Tick事件中:

IntPtr hWndForegroundWindow = GetForegroundWindow();
bool NotepadIsForeground = false;
Process[] procs = Process.GetProcessesByName("notepad");
foreach (Process proc in procs)
{
    if (proc.MainWindowHandle == hWndForegroundWindow)
    {
        NotepadIsForeground = true;
        break;
    }
}
if (this.Handle != hWndForegroundWindow)
{
    this.Visible = NotepadIsForeground;
}

你在使用指令中需要这个:

using System.Diagnostics;

也没有经过测试,但我今天做得很好,所以为什么要这么麻烦?