gpt4 book ai didi

c# - 从 System.Runtime.InteropServices.Marshal C# 中找不到 GetActiveObject 的定义

转载 作者:行者123 更新时间:2023-12-04 19:45:19 26 4
gpt4 key购买 nike

我正在尝试连接到正在运行的 Excel 实例,但是当我尝试使用以下代码片段时:

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

public Application StartExcel()
{
Application instance = null;
try
{
instance = (Application)Marshal.GetActiveObject("Excel.Application");
}
catch (COMException ex)
{
instance = new ApplicationClass();
}

return instance;
}

我在互联网上找到了类似的片段,但是当我编译这段代码时,我得到了以下错误:

error CS0117: 'Marshal' does not contain a definition for 'GetActiveObject'.



我不知道为什么,因为我有以下 NuGet 包:
- Microsoft.Office.Interop.Excel
- System.Runtime.InteropServices

最佳答案

我们需要从源代码 GitHub.Microsoft 中提取 GetActiveObject(String ProgID) 函数
创建自己的类,例如 - Marshal2
并像以前一样使用

Marshal2.GetActiveObject(progID);
源代码
public static class Marshal2
{
internal const String OLEAUT32 = "oleaut32.dll";
internal const String OLE32 = "ole32.dll";

[System.Security.SecurityCritical] // auto-generated_required
public static Object GetActiveObject(String progID)
{
Object obj = null;
Guid clsid;

// Call CLSIDFromProgIDEx first then fall back on CLSIDFromProgID if
// CLSIDFromProgIDEx doesn't exist.
try
{
CLSIDFromProgIDEx(progID, out clsid);
}
// catch
catch (Exception)
{
CLSIDFromProgID(progID, out clsid);
}

GetActiveObject(ref clsid, IntPtr.Zero, out obj);
return obj;
}

//[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[DllImport(OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);

//[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[DllImport(OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);

//[DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)]
[DllImport(OLEAUT32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);

}

关于c# - 从 System.Runtime.InteropServices.Marshal C# 中找不到 GetActiveObject 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010510/

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