VSTO Excel AddIn:当Excelinput框从模态窗口窗体调用时,焦点转到Visual Studio

我在Excel AddIn应用程序中有一个窗体窗体。 我使用ShowDialog()将窗体显示为模式窗口。 我需要在我的应用程序中指定一个范围地址。 所以,我添加了一个调用Application.InputBox的button。 button单击事件包含以下代码

private void button1_Click(object sender, EventArgs e) { Excel.Range myRng; Excel.Application app = Globals.ThisAddIn.Application; myRng = app.InputBox("Prompt", "Title", Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, 8); label1.Text = myRng.Address.ToString(); this.Focus(); } 

它工作正常。 但是,当input框处于活动状态时,我需要隐藏窗体窗体。 所以我稍微修改了一下代码

  private void button1_Click(object sender, EventArgs e) { Excel.Range myRng; Excel.Application app = Globals.ThisAddIn.Application; this.Visible = false; myRng = app.InputBox("Prompt", "Title", Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, 8); label1.Text = myRng.Address.ToString(); this.Visible = true; this.Focus(); } 

不幸的是,这提出了一个问题。 当我点击button焦点移动到Visual Studio。 我究竟做错了什么? InputBox打开的时候如何保留Excel应用程序的焦点?

最后我find了解决办法。 我改变了表单类中的代码,如下所示

  [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); private void button1_Click(object sender, EventArgs e) { Excel.Range myRng; Excel.Application app = Globals.ThisAddIn.Application; string fileName; fileName = app.ActiveWorkbook.Name; Process[] processes = Process.GetProcessesByName("excel"); foreach (Process p in processes) { if (p.MainWindowTitle.Contains(fileName.Substring(fileName.LastIndexOf("/") + 1))) { SetForegroundWindow(p.MainWindowHandle); } } this.Visible = false; try { myRng = app.InputBox("Prompt", "Title", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 8); } catch { myRng = null; } if (myRng != null) { label1.Text = myRng.Address.ToString(); } this.Visible = true; this.Activate(); } 

现在它按要求工作。 不过,我仍然想知道为什么会出现问题,是否有更简单的解决办法。 请让我知道,如果你有任何想法。

PS这个链接是有帮助的: 设置专注于Excel应用程序