确定文档是否确实具有焦点

Determine if document ACTUALLY has focus

VSTO 中是否有 属性 或函数可用于确定文档是否具有实际的键盘焦点?当文档是 current 但不是 focused 时,属性 或函数应该 return false,例如显示模态对话框或警报时。请注意 ActiveWindowActiveDocument 无法做到这一点,另外 Application.WindowDeactivate 似乎不会在警报获得焦点时触发。

这是 Word 2013(桌面版)+ VSTO 4 + C# + .NET Fx 4.5。

只能使用 WinAPI。

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();

bool WordHasFocus {
    get {
        IntPtr wordHandle = Process.GetCurrentProcess().MainWindowHandle;
        IntPtr focusedWindow = GetForegroundWindow() ;
        return wordHandle == focusedWindow;
    }
}

它告诉你只有那个词有焦点。如果要检查给定文档,还需要确保给定文档是活动文档。