问题是WPF窗口只占用system.form.window,所以我不能将Excel设置为我的VSTO应用程序中的所有者对象,因为VSTO插件只显示Excel的hwnd或其活动窗口作为本机窗口,因为它是COM。这意味着当WindowStartUpLoadation设置为中心所有者时,它不起作用。所以我被迫解决这个问题。
我在阅读this site后到目前为止所提出的是尝试手动居中窗口,但即使用他的简单示例,我的窗口也不会出现居中。
private static void CenterWpfWindowInExcel(WpfParameterDialog wpfDialog)
{
WindowInteropHelper helper = new WindowInteropHelper(wpfDialog);
helper.Owner = new IntPtr(Globals.ExcelAddin.Application.Hwnd);
// Manually calculate Top/Left to appear centered
double nonWpfOwnerLeft = Globals.ExcelAddin.Application.ActiveWindow.Left; // Get non-WPF owner’s Left
double nonWpfOwnerWidth = Globals.ExcelAddin.Application.ActiveWindow.Width; // Get non-WPF owner’s Width
double nonWpfOwnerTop = Globals.ExcelAddin.Application.ActiveWindow.Top; // Get non-WPF owner’s Top
double nonWpfOwnerHeight = Globals.ExcelAddin.Application.ActiveWindow.Height; // Get non-WPF owner’s Height
wpfDialog.WindowStartupLocation = WindowStartupLocation.Manual;
wpfDialog.Left = nonWpfOwnerLeft + (nonWpfOwnerWidth - wpfDialog.Width)/2;
wpfDialog.Top = nonWpfOwnerTop + (nonWpfOwnerHeight - wpfDialog.Height)/2;
}
有什么想法吗?
答案 0 :(得分:6)
我能够通过使用user23
获取主Excel窗口的Rect来解决这个问题 [DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
看来Globals.ExcelAddin.Application.ActiveWindow没有给我回复我预期的维度。我认为它给了我Ribbon Ribbon的尺寸,而不是Excel的主窗口。