1

I'm using VB.NET and obtain an icon from a System-DLL. Therefore, I use ExtractIconEx. As mentioned in the remarks, I'm using DestroyIcon to free the resources again.

So far, I used the line

Private Declare Auto Function DestroyIcon Lib "user32.dll" (
  ByVal hIcon As IntPtr) As Boolean

to declare that method.

From this example for Icon.FromHandle, I see they use

<System.Runtime.InteropServices.DllImportAttribute("user32.dll")> _
Private Shared Function DestroyIcon(
  ByVal hIcon As IntPtr) As Boolean
End Function

What is the difference?

I'm especially riddled by that DllImportAttribute doesn't seem to work with the same ease as Declare. I made the following test:

I use GetPrivateProfileString to obtain a String from an ini file.

Private Declare Auto Function GetPrivateProfileString Lib "kernel32" (
  ByVal lpApplicationName As String, 
  ByVal lpKeyName As String, 
  ByVal lpDefault As String, 
  ByVal lpReturnedString As String, 
  ByVal nSize As Integer, 
  ByVal lpFileName As String) As Integer

works; it writes the entry in the lpReturnedString buffer and returns 41.

<System.Runtime.InteropServices.DllImportAttribute("kernel32.dll")> _
Private Shared Function GetPrivateProfileString(
  ByVal lpApplicationName As String,
  ByVal lpKeyName As String,
  ByVal lpDefault As String,
  ByVal lpReturnedString As String,
  ByVal nSize As Integer,
  ByVal lpFileName As String) As Integer
End Function

leaves lpReturnedString untouched, but returns the correct string length of 41.

LWChris
  • 3,320
  • 1
  • 22
  • 39
  • 1
    The Declare keyword is legacy from earlier VB versions. Does the exact same thing for simple winapi functions like DestroyIcon, but the DllImport attribute has more capabilities. Do note that your declaration for GetPrivateProfileString() is dangerously wrong, strings are immutable, the pinvoke.net website can get you a better one. – Hans Passant Dec 27 '14 at 13:42
  • Why don't you just use [Icon.ExtractAssociatedIcon](http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon%28v=vs.110%29.aspx) and let the framework do the work instead of messing around with all those APIs? – The Blue Dog Dec 27 '14 at 13:43
  • @Plutonix What is that comment supposed to say? There is no answer to rate or accept here. – LWChris Dec 27 '14 at 13:53
  • @HansPassant I know Strings are immutable and actually I have no idea why the declare version works. For future reference, the declaration from [pinvoke.net](http://pinvoke.net/) can be found [here](http://pinvoke.net/default.aspx/kernel32.GetPrivateProfileString). It uses a `StringBuilder`, which I initialize with a capacity of my buffer size. With that modification, `DllImportAttribute` works as well. – LWChris Dec 27 '14 at 14:03
  • @TheBlueDog Because it is actually a resource DLL and not an image file. The DLL contains hundreds of icons, and all I know is that I want the one with the index XYZ. – LWChris Dec 27 '14 at 14:06

0 Answers0