using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace OfficeAppHelp.Help
{
    public static class DllImportHelp
    {
        /// <summary>
        /// net core 没有GetActiveObject()方法 所以调用dll
        /// </summary>
        /// <param name="progId"></param>
        /// <returns></returns>
        public static object GetActiveObject(string progId)
        {
            if (progId == null)
                return null;

            var hr = CLSIDFromProgIDEx(progId, out var clsid);
            if (hr < 0)
                return null;

            hr = GetActiveObject(clsid, IntPtr.Zero, out var obj);
            if (hr < 0)
                return null;
            return obj;
        }

        [DllImport("ole32")]
        private static extern int CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid lpclsid);

        [DllImport("oleaut32")]
        private static extern int GetActiveObject([MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, IntPtr pvReserved, [MarshalAs(UnmanagedType.IUnknown)] out object ppunk);
    }
}
