VSTO: Application Focus

VSTO: Application Focus

坏尐絯 发布于 2021-11-29 字数 178 浏览 832 回复 2 原文

Anyone know of a way to see if the Excel window of a VSTO project is active/in focus?

I'm looking for an equivalent of System.Windows.Window.IsActive.

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随波逐流 2022-06-07 2 楼

this.ActiveWindow.Activate() is the method that activates the window.

this.ActiveWindow.Active is the property that tell you the state of the window.

苦行僧 2022-06-07 1 楼

I've been frustrated with this as well. Are you using a dialog in the VSTO app? If so, what I have done is add an event to the closing of a Windows Form/Dialog to activate the Office application as follows (example is with Word, so there may be differences in Excel):

//... VSTO Startup Event
WindowsForm form = new WindowsForm();
form.FormClosed += new FormClosedEventHandler(form_FormClosed);
form.Show();


void form_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Application.Activate();         
    this.Application.ActiveWindow.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateNormal;

}

I have found this line always lies/returns true:

this.ActiveWindow.Active()

But this works better (global bool variable "AppActive" to keep track of active window):

//... VSTO Startup Event    
this.Application.WindowDeactivate += new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowDeactivateEventHandler(Application_WindowDeactivate);
this.Application.WindowActivate += new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowActivateEventHandler(Application_WindowActivate);

    void Application_WindowActivate(Microsoft.Office.Interop.Word.Document Doc, Microsoft.Office.Interop.Word.Window Wn)
    {
        AppActive = true;
    }

    void Application_WindowDeactivate(Microsoft.Office.Interop.Word.Document Doc, Microsoft.Office.Interop.Word.Window Wn)
    {
        AppActive = false;
    }