在Excel App中将焦点从表单更改为输入框

时间:2015-09-16 15:59:33

标签: c# excel excel-interop inputbox

我在Excel中编写了一个范围选择输入框,但我无法将Excel应用程序变为焦点,因此用户必须手动单击excel工作簿才能看到输入框,然后进行选择,点击确定并手动返回表格。有没有办法以编程方式改变焦点?我试过了

xlapp.Application.Activate();
和p读了一堆但找不到多少。以下是我的工作内容:

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

如果需要,我可以提供更多代码,但此按钮是自包含的,不会引用和其他代码。

1 个答案:

答案 0 :(得分:1)

昨天我找到了this

我将此添加到程序的开头:

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

然后使用我在任务管理器中找到的应用程序名称调用它并删除扩展名。所以在我的情况下,我需要在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"所以它只是应用程序的名称,但在调试中这是有效的。我希望这有助于其他人寻找答案。