如果你将 Excel 嵌入到 WinForms 窗体中,并且 Excel 不是激活的窗体,那么你可以通过以下代码获取 Excel 父窗体的名称:
IntPtr excelHwnd = excelApp.Hwnd;
string parentWindowName = Win32API.GetParentWindowName(excelHwnd);
// 定义 Win32API 类
public static class Win32API
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string GetParentWindowName(IntPtr hWnd)
{
IntPtr parentHwnd = GetParent(hWnd);
StringBuilder sb = new StringBuilder(256);
GetWindowText(parentHwnd, sb, sb.Capacity);
return sb.ToString();
}
}
上述代码中,我们使用了 excelApp.Hwnd
属性获取 Excel 应用程序的句柄(HWND),然后使用 Win32 API GetParent
函数获取父窗体的句柄,最后使用 GetWindowText
函数获取父窗体的名称。
确保在使用上述代码之前,你已经将 Excel 成功嵌入到 WinForms 窗体中,并且 excelApp
是有效的 Excel 应用程序对象。
请注意,上述代码使用了平台调用(Platform Invoke)来调用 Win32 API 函数,因此需要添加 using System.Runtime.InteropServices;
命名空间,并且确保你的代码与目标平台兼容。