How to center a WPF window in Excel VSTO addin

The problem is that the WPF window accepts only system.form.window, so I cannot set Excel as the owner object in the VSTO application, because adding VSTO provides only Excel hwnd or its active window as its own window since it is COM . This means that if WindowStartUpLoadation is set as the owner of the center, it does not work. Therefore, I have to get around this.

What I still read after reading this site to try to manually center the window, but even with its simple example, my window will never be 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; } 

Any ideas?

+7
wpf vsto
source share
1 answer

I was able to solve this problem by getting the "Excel Main Window Rectangle" 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; } 

It seems that Globals.ExcelAddin.Application.ActiveWindow did not return the dimension I was expecting. I think this gave me the dimensions of the tape, not the main Excel window.

+6
source share

All Articles