gpt4 book ai didi

.net - 如何在 Excel VSTO 插件中将 WPF 窗口居中

转载 作者:行者123 更新时间:2023-12-02 01:38:56 26 4
gpt4 key购买 nike

问题是 WPF 窗口仅采用 system.form.window,因此我无法将 Excel 设置为 VSTO 应用程序中的所有者对象,因为 VSTO 插件仅公开 Excel 的 hwnd 或其事件窗口作为 native 窗口因为它是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;
}

有什么想法吗?

最佳答案

我能够通过使用user32.dll获取主Excel窗口的矩形来解决这个问题

[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 Addin 的尺寸,而不是 Excel 的主窗口。

关于.net - 如何在 Excel VSTO 插件中将 WPF 窗口居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18135634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com