Set Focus on Excel Application

一曲冷凌霜 提交于 2019-12-11 06:27:55

问题


How to set focus on Excel Application object in vsto C# i have been searching for it but didn't have any success


回答1:


Try this code

 Process[] processes = Process.GetProcessesByName("excel");
 foreach (Process p in processes)
 {
     if (p.MainWindowTitle.Contains(fileName.Substring(fileName.LastIndexOf("/") + 1)))
     {
         SetForegroundWindow(p.MainWindowHandle);
     }
 } 



回答2:


The solution in my VSTO application is:

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool BringWindowToTop(IntPtr hWnd);

    /// <summary>
    /// Gets the main excel window.
    /// </summary>
    /// <returns>An ArbitraryWindow that represents the main excel window.</returns>
    public static ArbitraryWindow GetMainExcelWindow()
    {
        var excelHwnd_IntPtr = new IntPtr(Globals.ThisAddIn.Application.Hwnd);
        var excelWindow = new ArbitraryWindow(excelHwnd_IntPtr);

        return excelWindow;
    }

    /// <summary>
    /// Activates the excel window.
    /// </summary>
    public static void ActivateExcelWindow()
    {
        var currentlyActiveForm = Form.ActiveForm;
        //if (currentlyActiveForm != null && currentlyActiveForm.GetType() == typeof(FormProgress)) return;

        var handle = GetMainExcelWindow().Handle;
        BringWindowToTop(handle);
    }

Just call "ActivateExcelWindow()" to activate the excel main window.

Regards, Jörg



来源:https://stackoverflow.com/questions/11643037/set-focus-on-excel-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!