在Excel应用程序中将焦点从表单更改为input框

我已经在Excel中编写了一个范围selectinput框,但是我不能让Excel应用程序成为焦点,因此用户必须手动点击Excel工作簿才能看到input框,然后进行select,点击确定手动返回到表单。 有没有一种方法来编程改变焦点? 我试过了

xlapp.Application.Activate(); 

并读了一堆,但找不到多less。 以下是我正在处理的内容:

  private void btnExcel_Click(object sender, EventArgs e) { Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); Excel.Workbook wkbk = null; wkbk = xlApp.ActiveWorkbook; Excel.Range address = xlApp.Application.InputBox("Select a Range", "Model Cutter 64", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 8); txtWkshtName.Text = address.Parent.Name; txtRange.Text = address.get_Address(address); } 

我可以提供更多的代码,如果需要的话,但这个button是自包含的,不参考和其他代码。

我昨天发现了这个 :

我将这添加到程序的开始:

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

然后使用我在任务pipe理器中为应用程序find的名称进行调用,并删除了扩展名。 所以在我的情况下,我需要在EXCEL.exe和我的程序Model Cutter 64.vshost.exe之间来回跳动。 我这样做了:

 private void btnExcel_Click(object sender, EventArgs e) { Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); Excel.Workbook wkbk = null; wkbk = xlApp.ActiveWorkbook; FocusProcess("Excel"); try { Excel.Range address = xlApp.Application.InputBox("Select a Range", "Model Cutter 64", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 8); txtWkshtName.Text = address.Parent.Name; txtRange.Text = address.get_Address(address); } catch { errorMessage("A valid range was not selected., please try again."); FocusProcess("Model Cutter 64.vshost"); } FocusProcess("Model Cutter 64.vshost"); } 

最后,当我产生这个时,我将不得不删除“.vshost”,以便它只是应用程序的名称,但在debugging这个工程。 我希望这可以帮助别人寻找答案。