P/Invoke with Shell32, bypass Interop.Shell32.dll generation

雨燕双飞 提交于 2019-12-04 13:00:34

Most of the Windows Shell API features have P/Invoke entry points that return COM interfaces, so you should rarely need to explicitly create a ShellClass CoClass instance. (The objects you are using, Folder and FolderItem, are mostly meant for use by late-bound clients such as script languages; with C# you can do much better.)

To avoid having to generate the interop assembly, you just need to declare the appropriate types in your C# code that match the P/Invoke functions and COM interfaces that the shell already implements. In your case, what you're looking for is the IShellFolder2 interface (which is essentially identical to the Folder object).

Typically, to do what you're asking, you would:

  1. Call SHGetDesktopFolder to return an IShellFolder interface pointing to the desktop folder.
  2. Call IShellFolder::ParseDisplayName on the folder you want, which gives you a "pointer to an Identifier list" (a PIDL) representing that folder's internal shell identifier.
  3. Cast your IShellFolder to an IShellFolder2 (using as, like any other interfaces).
  4. Call IShellFolder2::GetDetailsOf(), passing the PIDL from step 2 and the column you want.

You will need to translate the two COM interfaces, plus one structure and one P/Invoke function, and put the C# code in your project. You can get away with IntPtr for a lot of this (like the PIDL) since you only need to pass them around between COM methods. (The MSDN articles will tell you that you are responsible for freeing memory after you are done; the CLR's interop code will take care of that stuff for you in almost all cases.)

pinvoke.net will help you out here, as will this fascinatingly well written series of blog posts on doing COM interop translations from the MSDN articles.

In my experience, the most effective way to use the shell API from managed code is to use the Windows API Code Pack. This wraps up all the useful parts of the shell API and makes it trivially accessible from managed code. The download includes lots of examples to get you on the way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!