问题
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