问题描述
现在的问题是,一个WPF窗口只需要system.form.window,所以我不能设置Excel的是在我的VSTO的应用程序所有者对象,因为VSTO插件只公开Excel的HWND,或它的活动窗口作为本地窗口因为它是COM。这意味着,当WindowStartUpLoadation设定为中心雇主它不起作用。所以,我不得不努力解决这个问题。
The problem is that a WPF window only takes a system.form.window so I cannot set Excel to be the owner object in my VSTO application, because the VSTO addin only exposes Excel's hwnd, or its active window as a Native Window since it is COM. That means when WindowStartUpLoadation is set to be center owner it doesn't work. So I am forced to work around this.
我想出迄今看完后this网站是尝试手动中心的窗口,但即使与他简单的例子,我的窗口永远不会出现居中。
What I have come up with so far after reading this site is to try and manually center the window, but even with his simple example my window never appears centered.
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;
}
任何想法?
推荐答案
我是能够解决这个由得到越来越主Excel窗口的矩形使用user23
I was able to solve this by get getting the Rect of the Main Excel Window using user23
[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没有给我回我的预期尺寸。我认为这是给我的丝带加载项的尺寸,而不是Excel的主窗口。
It appears that Globals.ExcelAddin.Application.ActiveWindow was not giving me back the dimension I expected. I think it was giving me the Ribbon Addin's dimensions and not Excel's Main Window.
这篇关于如何在Excel中VSTO插件中心WPF窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!