C# Get progID from COM object

2020-02-05 20:17发布

问题:

i would like to know if there is a way to get the progId of a com object in c#. eg - i have a webBrowser object that exposes a document object which is COM. is there a way to figure out what the progID of that document object is?

I know you can get the object from progID, just not sure how to do the other way around.

回答1:

You could query for IPersist, and GetClassID on it.

That gets you the CLSID. Then call ProgIDFromCLSID:

The pinvoke declaration is here.

That gets you the ProgID.

EDIT:

To query for an interface, you just do a cast in C#:

IPersist p = myObj as IPersist;
if (p != null)
{
    // phew, it worked...
}

Behind the scenes, this is what is actually happening, as shown here in C++:

IUnknown *pUnk = // ... get object from somewhere

IPersist *pPersist = 0;
if (SUCCEEDED(pUnk->QueryInterface(IID_IPersist, (void **)&pPersist)))
{
    // phew, it worked...
}

(But no one bothers with writing that stuff by hand these days, as a smart pointer can pretty much simulate the C# experience.)