使用COM组件失败作为管理员

时间:2014-10-29 15:01:29

标签: c# com registry registrykey

我在原生dll上有一个.NET包装器。 我尝试仅针对当前用户注册该组件:link 运行正常,除非我右键单击可执行文件并说"以管理员身份运行..."该工具将无法找到该类。

这是我使用的代码,是否有我遗漏的东西,我认为它可能与以下内容有关: link

谢谢!

public int Register(ServerAction Action, string ServerName)
    {
        int hr = 0;
        string szFunction = (Action == ServerAction.Register) ? "DllRegisterServer" : "DllUnregisterServer";

        logger.Info("FileReader->Try to " + szFunction + " " + ServerName);
        try
        {
            IntPtr hMod = LoadLibrary(ServerName);

            if (hMod.ToInt32() != 0)
            {
                IntPtr registerDllServer_ProcAddress = GetProcAddress(hMod, szFunction);
                DllRegisterServerInvoker pfnDllProc = (DllRegisterServerInvoker)Marshal.GetDelegateForFunctionPointer(registerDllServer_ProcAddress, typeof(DllRegisterServerInvoker));
                if (pfnDllProc != null)
                {
                    if (isUserAdminAndProcessElevated())
                    {
                        logger.Info("User is admin and process is elevated!");
                    }
                    else
                    {
                        logger.Info("User is not admin!");
                        hr = OverrideClassesRoot(HKEY_CURRENT_USER, "Software\\Classes");
                    }

                }


                hr = pfnDllProc();

                pfnDllProc = null;

                FreeLibrary(hMod);
            }
            else
            {
                hr = this.GetHresultFromWin32();
            }
        }
        catch
        {
            Console.WriteLine("FileReader->" + szFunction + " " + ServerName + " FAILED!");
        }

        string errorMessage = new Win32Exception(hr).Message;
        logger.Fatal(errorMessage);
        return hr;
    }

    private Int32 OverrideClassesRoot(UIntPtr hKeyBase, string OverrideKey)
    {
        UIntPtr hkey = new UIntPtr();
        int l = RegOpenKeyA(hKeyBase, OverrideKey, ref hkey);

        if (l == 0)
        {
            l = RegOverridePredefKey(HKEY_CLASSES_ROOT, hkey);
            RegCloseKey(hkey);
        }

        return this.GetHresultFromWin32();
    }

仍然无法解决这个问题,但我修复了:MSDN link

0 个答案:

没有答案