【问题标题】:C#: Referencing a windows shell interfaceC#:引用 Windows shell 接口
【发布时间】:2009-12-17 22:14:47
【问题描述】:

我是 C# 的新手,我正在尝试完成我一直在从事的一个小项目,该项目使用少量 C# 代码来协助开发 Windows 桌面小工具。基本上,我正在尝试实现IDesktopGadget 接口,以便我可以使用RunGadget 方法。

这是我从阅读有关类似接口的信息中得到的:

[ComImport]
[Guid("C1646BC4-F298-4F91-A204-EB2DD1709D1A")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IDesktopGadget
{
    uint RunGadget([MarshalAs(UnmanagedType.LPWStr)] string gadgetPath);
}

不幸的是,当我尝试从中创建对象时出现错误:"Cannot create an instance of the abstract class or interface 'GadgetTask.IDesktopGadget'"

有人能指出我正确的方向,或许可以同时帮助我了解我做错了什么吗?

【问题讨论】:

    标签: c# winapi windows-desktop-gadgets


    【解决方案1】:

    您实际上需要一个 DesktopGadget 对象的实现才能使用该接口。 MS 提供了一个标准的 COM 对象来在 Windows 7 上执行此操作。您可以通过执行以下操作来创建一个实例:

    Type t = Type.GetTypeFromCLSID(new Guid("924ccc1b-6562-4c85-8657-d177925222b6"));
    IDesktopGadget dg = (IDesktopGadget)Activator.CreateInstance(t);

    【讨论】:

    • 感谢您的回答。我应该用接口的类 id 替换那里的 Guid 吗?
    • 我得到一个“类未注册错误”,我不知道为什么。我直接从注册表中提取了接口的类 ID。
    • 不,Guid 是对象的 CLSID,而不是接口。我从 SDK 标头中的 CLSID_DesktopGadget 定义中获得了该 Guid。
    • 谢谢,我会再检查一下!
    • 感谢您到目前为止的帮助...我现在收到一个新错误:System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'IDesktopGadget'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{924CCC1B-6562-4C85-8657-D177925222B6}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
    【解决方案2】:

    感谢您的指导。对于更直接的帮助,这对我有用:

    IDesktopGadget.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace GadgetActivator
    {
        [ComImport]
        [Guid("C1646BC4-F298-4F91-A204-EB2DD1709D1A")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    
        interface IDesktopGadget
        {
            uint RunGadget([MarshalAs(UnmanagedType.LPWStr)] string gadgetPath);
        }
    }
    

    程序.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    
    namespace GadgetActivator
    {
        class Program
        {
            static void Main(string[] args)
            {
                Type t = Type.GetTypeFromCLSID(new Guid("924ccc1b-6562-4c85-8657-d177925222b6"));
                IDesktopGadget dg = (IDesktopGadget)Activator.CreateInstance(t);
                dg.RunGadget(@"C:\Program Files\Windows Sidebar\Gadgets\xxxxxxxxx.Gadget");
            }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2012-11-28
      • 2023-01-11
      相关资源
      最近更新 更多