Sunday, March 16, 2014

让窗体图标和exe图标一致

你可以用这代码来让你软件窗体图标和你exe的一致,只需要在Form Load事件里插入:
Me.Icon = IconLoader.GetIconOf(Application.ExecutablePath, True)
Imports System.Runtime.InteropServices

Public Class IconLoader
    Private Declare Unicode Function SHGetFileInfoW Lib "shell32.dll" Alias "SHGetFileInfoW" (ByVal pszPath As String, _
      ByVal dwFileAttributes As Integer, _
      ByRef psfi As SHFILEINFOW, _
      ByVal cbFileInfo As Integer, _
      ByVal uFlags As UInt32) As IntPtr

    Private Const SHGFI_ICON As UInt32 = &H100
    Private Const SHGFI_LARGEICON As UInt32 = &H0
    Private Const SHGFI_SMALLICON As UInt32 = &H1

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Private Structure SHFILEINFOW
        Public hIcon As IntPtr
        Public iIcon As Int32
        Public dwAttributes As UInt32
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

    Public Shared Function GetIconOf(ByVal StuffPath As String, ByVal LargeIcon As Boolean) As Icon
        Dim info As New SHFILEINFOW
        Dim cbFileInfo As Integer = Marshal.SizeOf(info)
        Dim flags As UInt32
        If LargeIcon Then
            flags = SHGFI_ICON Or SHGFI_LARGEICON
        Else
            flags = SHGFI_ICON Or SHGFI_SMALLICON
        End If
        SHGetFileInfoW(StuffPath, 256, info, cbFileInfo, flags)
        Return Icon.FromHandle(info.hIcon)
    End Function

End Class

No comments:

Post a Comment