elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Microsoft Shell Controls And Automation
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Microsoft Shell Controls And Automation  (Leído 3,073 veces)
.:Weeds:.

Desconectado Desconectado

Mensajes: 122



Ver Perfil
Microsoft Shell Controls And Automation
« en: 17 Noviembre 2013, 22:34 pm »

Estoy creando una aplicación que requiere de esa referencia COM. Lo que hace es leer la informacion de un archivo .lnk. Mi pregunta es si esa referencia la tienen todos los sistemas windows(de xp para arriba). Eso de las referencias COM nunca lo e entendido muy bien  :-[ .

Alguien que me ilumine. De paso os dejo os dejo el code por si lo quereis.

Código
  1. Public Function GetLnkInfo(lnkPath As String, ByVal i As Integer) As String
  2.        Dim shl = New Shell32.Shell()
  3.        lnkPath = System.IO.Path.GetFullPath(lnkPath)
  4.        Dim dir = shl.[NameSpace](System.IO.Path.GetDirectoryName(lnkPath))
  5.        Dim itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath))
  6.        Dim lnk = DirectCast(itm.GetLink, Shell32.ShellLinkObject)
  7.  
  8.        If i = 0 Then
  9.            'Si es 0 devolvemos la ruta
  10.            Return lnk.Target.Path
  11.        ElseIf i = 1 Then
  12.            'Si es 1 devolvemos el directorio de inicio
  13.            Return lnk.WorkingDirectory
  14.        ElseIf i = 2 Then
  15.            'Si es 2 devolvemos la descripcion
  16.            Return lnk.Description
  17.        Else
  18.            Return Nothing
  19.        End If
  20.    End Function

Saludos y gracias.


En línea


Eleкtro
Ex-Staff
*
Conectado Conectado

Mensajes: 9.878



Ver Perfil
Re: Microsoft Shell Controls And Automation
« Respuesta #1 en: 18 Noviembre 2013, 11:53 am »

Mi pregunta es si esa referencia la tienen todos los sistemas windows(de xp para arriba).

Claro que si, es la dll Shell32.dll.

Sobre el Component Object Modal -> http://en.wikipedia.org/wiki/Component_Object_Model

Yo tampoco he profundizado mucho en el tema del IPC y COM, pero realicé varios proyectos donde debía manejar accesos directos, y bueno, antes de llevarlo a cabo me puse a investigar cual podría ser la mejor manera de hacerlo, e investigando leí muchos, pero muchos errores sobre códigos parecidos al que has mostrado usando dicha referencia, a algunos le daban problemas porque primero debían registrar dicha dll, a otros por la compatibilidad del tipo de interface en distinto Windows (COM 4, COM 5) obligando a compilar una versión distinta para XP y otra para Win7, y distintos errores más que ahora no recuerdo.

En fín, al final yo lo que hice fue buscar un código de alquien que ya se haya molestado en crear una Class de ayuda para esta tarea con dicha interface (IShellLink), tomé el código original que solo servia para resolver shortcuts dañados, y extendí dicha Class para mis requisitos (obtener información del shortcut),
no se cuan fiable será este método, a mi parecer no debe ser casi nada distinto a la referencia ya que parece que se basa en lo mismo, pero no estoy 100% seguro porque como te digo no se casi nada sobre COM, pero el caso es que esto funciona tanto en XP, Vista, Win7 y Win8 sin ningún tipo de errores (al menos hasta dia de hoy no he experimentado ningún error), y además tiene la ventaja de poder customizarlo como yo hice para tus requisitos, y la ventaja de resolver shortcuts, que esa era su función original.

El funcionamiento lo hice muy sencillo, te muestro un ejemplo:

código eliminado


A pesar de no haber podido "iluminarte", imagino que el código te será de gran ayuda :).

Saludos.



EDITO:
Le he dado otro repaso a la Class, aquí tienes.
he añadido un método para crear shortcuts, he añadido más propiedades y he facilitado el uso de las hotkeys.

Ejemplo de uso:
Código
  1.        ' Tries to resolve a shortcut which has changed their Target location.
  2.        ShortcutManager.Resolve_Ui("C:\Truncated Shortcut.lnk", New IntPtr(1))
  3.        ShortcutManager.Resolve_NoUi("C:\Truncated Shortcut.lnk")
  4.  
  5.        ' Creates a new Shortcut file
  6.        ShortcutManager.Create("C:\Shortcut.lnk",
  7.                               "C:\TargetFile.ext",
  8.                               "C:\",
  9.                               "Description",
  10.                               "-Arguments",
  11.                               "C:\Icon.ico", 0,
  12.                               ShortcutManager.HotkeyModifiers.ALT Or ShortcutManager.HotkeyModifiers.CONTROL,
  13.                               Keys.F1,
  14.                               ShortcutManager.ShortcutWindowState.Normal)
  15.  
  16.        ' Gets Shortcut file information
  17.        Dim ShortcutInfo As ShortcutManager.ShortcutInfo =
  18.            ShortcutManager.GetInfo("C:\Shortcut.lnk")
  19.  
  20.        Dim sb As New System.Text.StringBuilder
  21.  
  22.        With ShortcutInfo
  23.  
  24.            sb.AppendLine(String.Format(" ""{0}"" ", .ShortcutFile))
  25.            sb.AppendLine(String.Format("------------------------"))
  26.            sb.AppendLine(String.Format("Description: {0}", .Description))
  27.            sb.AppendLine(String.Format("Target: {0}", .Target))
  28.            sb.AppendLine(String.Format("Arguments: {0}", .Arguments))
  29.            sb.AppendLine(String.Format("Target Is Directory?: {0}", CStr(.IsDirectory)))
  30.            sb.AppendLine(String.Format("Target Is File?: {0}", CStr(.IsFile)))
  31.            sb.AppendLine(String.Format("WorkingDir: {0}", .WorkingDir))
  32.            sb.AppendLine(String.Format("DirectoryName: {0}", .DirectoryName))
  33.            sb.AppendLine(String.Format("FileName: {0}", .FileName))
  34.            sb.AppendLine(String.Format("FileExtension: {0}", .FileExtension))
  35.            sb.AppendLine(String.Format("DriveLetter: {0}", .DriveLetter))
  36.            sb.AppendLine(String.Format("Icon: {0}", .Icon))
  37.            sb.AppendLine(String.Format("Icon Index: {0}", CStr(.IconIndex)))
  38.            sb.AppendLine(String.Format("Hotkey (Hex): {0}", CStr(.Hotkey)))
  39.            sb.AppendLine(String.Format("Hotkey (Str): {0} + {1}", .Hotkey_Modifier.ToString, .Hotkey_Key.ToString))
  40.            sb.AppendLine(String.Format("Window State: {0}", .WindowState.ToString))
  41.  
  42.        End With
  43.  
  44.        MsgBox(sb.ToString)

la class:
Código
  1. Imports System.Runtime.InteropServices
  2. Imports System.Text
  3. Imports System.IO
  4.  
  5. #Region " ShortcutManager "
  6.  
  7. ' [ ShortcutManager ]
  8. '
  9. ' // By Elektro H@cker
  10.  
  11. #Region " Usage Examples "
  12.  
  13. 'Private Sub Test()
  14.  
  15. '    ' Tries to resolve a shortcut which has changed their Target location.
  16. '    ShortcutManager.Resolve_Ui("C:\Truncated Shortcut.lnk", New IntPtr(1))
  17. '    ShortcutManager.Resolve_NoUi("C:\Truncated Shortcut.lnk")
  18.  
  19. '    ' Creates a new Shortcut file
  20. '    ShortcutManager.Create("C:\Shortcut.lnk",
  21. '                           "C:\TargetFile.ext",
  22. '                           "C:\",
  23. '                           "Description",
  24. '                           "-Arguments",
  25. '                           "C:\Icon.ico", 0,
  26. '                           ShortcutManager.HotkeyModifiers.ALT Or ShortcutManager.HotkeyModifiers.CONTROL,
  27. '                           Keys.F1,
  28. '                           ShortcutManager.ShortcutWindowState.Normal)
  29.  
  30. '    ' Gets Shortcut file information
  31. '    Dim ShortcutInfo As ShortcutManager.ShortcutInfo =
  32. '        ShortcutManager.GetInfo("C:\Shortcut.lnk")
  33.  
  34. '    Dim sb As New System.Text.StringBuilder
  35.  
  36. '    With ShortcutInfo
  37.  
  38. '        sb.AppendLine(String.Format(" ""{0}"" ", .ShortcutFile))
  39. '        sb.AppendLine(String.Format("------------------------"))
  40. '        sb.AppendLine(String.Format("Description: {0}", .Description))
  41. '        sb.AppendLine(String.Format("Target: {0}", .Target))
  42. '        sb.AppendLine(String.Format("Arguments: {0}", .Arguments))
  43. '        sb.AppendLine(String.Format("Target Is Directory?: {0}", CStr(.IsDirectory)))
  44. '        sb.AppendLine(String.Format("Target Is File?: {0}", CStr(.IsFile)))
  45. '        sb.AppendLine(String.Format("WorkingDir: {0}", .WorkingDir))
  46. '        sb.AppendLine(String.Format("DirectoryName: {0}", .DirectoryName))
  47. '        sb.AppendLine(String.Format("FileName: {0}", .FileName))
  48. '        sb.AppendLine(String.Format("FileExtension: {0}", .FileExtension))
  49. '        sb.AppendLine(String.Format("DriveLetter: {0}", .DriveLetter))
  50. '        sb.AppendLine(String.Format("Icon: {0}", .Icon))
  51. '        sb.AppendLine(String.Format("Icon Index: {0}", CStr(.IconIndex)))
  52. '        sb.AppendLine(String.Format("Hotkey (Hex): {0}", CStr(.Hotkey)))
  53. '        sb.AppendLine(String.Format("Hotkey (Str): {0} + {1}", .Hotkey_Modifier.ToString, .Hotkey_Key.ToString))
  54. '        sb.AppendLine(String.Format("Window State: {0}", .WindowState.ToString))
  55.  
  56. '    End With
  57.  
  58. '    MsgBox(sb.ToString)
  59.  
  60. 'End Sub
  61.  
  62. #End Region
  63.  
  64. Public Class ShortcutManager
  65.  
  66. #Region " Variables "
  67.  
  68.    Private Shared lnk As New ShellLink()
  69.    Private Shared lnk_data As New WIN32_FIND_DATAW()
  70.  
  71.    Private Shared lnk_arguments As New StringBuilder(260)
  72.    Private Shared lnk_description As New StringBuilder(260)
  73.    Private Shared lnk_target As New StringBuilder(260)
  74.    Private Shared lnk_workingdir As New StringBuilder(260)
  75.    Private Shared lnk_iconpath As New StringBuilder(260)
  76.    Private Shared lnk_iconindex As Integer = -1
  77.    Private Shared lnk_hotkey As Short = -1
  78.    Private Shared lnk_windowstate As ShortcutWindowState = ShortcutWindowState.Normal
  79.  
  80. #End Region
  81.  
  82. #Region " API, Interfaces, Enumerations "
  83.  
  84.    <DllImport("shfolder.dll",
  85.    CharSet:=CharSet.Auto)>
  86.    Friend Shared Function SHGetFolderPath(ByVal hwndOwner As IntPtr,
  87.                                           ByVal nFolder As Integer,
  88.                                           ByVal hToken As IntPtr,
  89.                                           ByVal dwFlags As Integer,
  90.                                           ByVal lpszPath As StringBuilder
  91.    ) As Integer
  92.    End Function
  93.  
  94.    <Flags()>
  95.    Private Enum SLGP_FLAGS
  96.  
  97.        ''' <summary>
  98.        ''' Retrieves the standard short (8.3 format) file name.
  99.        ''' </summary>
  100.        SLGP_SHORTPATH = &H1
  101.  
  102.        ''' <summary>
  103.        ''' Retrieves the Universal Naming Convention (UNC) path name of the file.
  104.        ''' </summary>
  105.        SLGP_UNCPRIORITY = &H2
  106.  
  107.        ''' <summary>
  108.        ''' Retrieves the raw path name.
  109.        ''' A raw path is something that might not exist and may include environment variables that need to be expanded.
  110.        ''' </summary>
  111.        SLGP_RAWPATH = &H4
  112.  
  113.    End Enum
  114.  
  115.    <Flags()>
  116.    Private Enum SLR_FLAGS
  117.  
  118.        ''' <summary>
  119.        ''' Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
  120.        ''' the high-order word of fFlags can be set to a time-out value that specifies the
  121.        ''' maximum amount of time to be spent resolving the link. The function returns if the
  122.        ''' link cannot be resolved within the time-out duration. If the high-order word is set
  123.        ''' to zero, the time-out duration will be set to the default value of 3,000 milliseconds
  124.        ''' (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
  125.        ''' duration, in milliseconds.
  126.        ''' </summary>
  127.        SLR_NO_UI = &H1
  128.  
  129.        ''' <summary>
  130.        ''' If the link object has changed, update its path and list of identifiers.
  131.        ''' If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine,
  132.        ''' whether or not the link object has changed.
  133.        ''' </summary>
  134.        SLR_UPDATE = &H4
  135.  
  136.        ''' <summary>
  137.        ''' Do not update the link information
  138.        ''' </summary>
  139.        SLR_NOUPDATE = &H8
  140.  
  141.        ''' <summary>
  142.        ''' Do not execute the search heuristics
  143.        ''' </summary>
  144.        SLR_NOSEARCH = &H10
  145.  
  146.        ''' <summary>
  147.        ''' Do not use distributed link tracking
  148.        ''' </summary>
  149.        SLR_NOTRACK = &H20
  150.  
  151.        ''' <summary>
  152.        ''' Disable distributed link tracking.
  153.        ''' By default, distributed link tracking tracks removable media,
  154.        ''' across multiple devices based on the volume name.
  155.        ''' It also uses the Universal Naming Convention (UNC) path to track remote file systems,
  156.        ''' whose drive letter has changed.
  157.        ''' Setting SLR_NOLINKINFO disables both types of tracking.
  158.        ''' </summary>
  159.        SLR_NOLINKINFO = &H40
  160.  
  161.        ''' <summary>
  162.        ''' Call the Microsoft Windows Installer
  163.        ''' </summary>
  164.        SLR_INVOKE_MSI = &H80
  165.  
  166.    End Enum
  167.  
  168.    ''' <summary>
  169.    ''' Stores information about a shortcut file.
  170.    ''' </summary>
  171.    Public Class ShortcutInfo
  172.  
  173.        ''' <summary>
  174.        ''' Shortcut file full path.
  175.        ''' </summary>
  176.        Public Property ShortcutFile As String
  177.  
  178.        ''' <summary>
  179.        ''' Shortcut Comment/Description.
  180.        ''' </summary>
  181.        Public Property Description As String
  182.  
  183.        ''' <summary>
  184.        ''' Shortcut Target Arguments.
  185.        ''' </summary>
  186.        Public Property Arguments As String
  187.  
  188.        ''' <summary>
  189.        ''' Shortcut Target.
  190.        ''' </summary>
  191.        Public Property Target As String
  192.  
  193.        ''' <summary>
  194.        ''' Shortcut Working Directory.
  195.        ''' </summary>
  196.        Public Property WorkingDir As String
  197.  
  198.        ''' <summary>
  199.        ''' Shortcut Icon Location.
  200.        ''' </summary>
  201.        Public Property Icon As String
  202.  
  203.        ''' <summary>
  204.        ''' Shortcut Icon Index.
  205.        ''' </summary>
  206.        Public Property IconIndex As Integer
  207.  
  208.        ''' <summary>
  209.        ''' Shortcut Hotkey combination.
  210.        ''' Is represented as Hexadecimal.
  211.        ''' </summary>
  212.        Public Property Hotkey As Short
  213.  
  214.        ''' <summary>
  215.        ''' Shortcut Hotkey modifiers.
  216.        ''' </summary>
  217.        Public Property Hotkey_Modifier As HotkeyModifiers
  218.  
  219.        ''' <summary>
  220.        ''' Shortcut Hotkey Combination.
  221.        ''' </summary>
  222.        Public Property Hotkey_Key As Keys
  223.  
  224.        ''' <summary>
  225.        ''' Shortcut Window State.
  226.        ''' </summary>
  227.        Public Property WindowState As ShortcutWindowState
  228.  
  229.        ''' <summary>
  230.        ''' Indicates if the target is a file.
  231.        ''' </summary>
  232.        Public Property IsFile As Boolean
  233.  
  234.        ''' <summary>
  235.        ''' Indicates if the target is a directory.
  236.        ''' </summary>
  237.        Public Property IsDirectory As Boolean
  238.  
  239.        ''' <summary>
  240.        ''' Shortcut target drive letter.
  241.        ''' </summary>
  242.        Public Property DriveLetter As String
  243.  
  244.        ''' <summary>
  245.        ''' Shortcut target directory name.
  246.        ''' </summary>
  247.        Public Property DirectoryName As String
  248.  
  249.        ''' <summary>
  250.        ''' Shortcut target filename.
  251.        ''' (File extension is not included in name)
  252.        ''' </summary>
  253.        Public Property FileName As String
  254.  
  255.        ''' <summary>
  256.        ''' Shortcut target file extension.
  257.        ''' </summary>
  258.        Public Property FileExtension As String
  259.  
  260.    End Class
  261.  
  262.    ''' <summary>
  263.    ''' Hotkey modifiers for a shortcut file.
  264.    ''' </summary>
  265.    <FlagsAttribute()>
  266.    Public Enum HotkeyModifiers As Short
  267.  
  268.        ''' <summary>
  269.        ''' The SHIFT key.
  270.        ''' </summary>
  271.        SHIFT = 1
  272.  
  273.        ''' <summary>
  274.        ''' The CTRL key.
  275.        ''' </summary>
  276.        CONTROL = 2
  277.  
  278.        ''' <summary>
  279.        ''' The ALT key.
  280.        ''' </summary>
  281.        ALT = 4
  282.  
  283.        ''' <summary>
  284.        ''' None.
  285.        ''' Specifies any hotkey modificator.
  286.        ''' </summary>
  287.        NONE = 0
  288.  
  289.    End Enum
  290.  
  291.    ''' <summary>
  292.    ''' The Window States for a shortcut file.
  293.    ''' </summary>
  294.    Public Enum ShortcutWindowState As Integer
  295.  
  296.        ''' <summary>
  297.        ''' Shortcut Window is at normal state.
  298.        ''' </summary>
  299.        Normal = 1
  300.  
  301.        ''' <summary>
  302.        ''' Shortcut Window is Maximized.
  303.        ''' </summary>
  304.        Maximized = 3
  305.  
  306.        ''' <summary>
  307.        ''' Shortcut Window is Minimized.
  308.        ''' </summary>
  309.        Minimized = 7
  310.  
  311.    End Enum
  312.  
  313.    <StructLayout(LayoutKind.Sequential,
  314.    CharSet:=CharSet.Auto)>
  315.    Private Structure WIN32_FIND_DATAW
  316.        Public dwFileAttributes As UInteger
  317.        Public ftCreationTime As Long
  318.        Public ftLastAccessTime As Long
  319.        Public ftLastWriteTime As Long
  320.        Public nFileSizeHigh As UInteger
  321.        Public nFileSizeLow As UInteger
  322.        Public dwReserved0 As UInteger
  323.        Public dwReserved1 As UInteger
  324.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
  325.        Public cFileName As String
  326.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)>
  327.        Public cAlternateFileName As String
  328.    End Structure
  329.  
  330.    ''' <summary>
  331.    ''' The IShellLink interface allows Shell links to be created, modified, and resolved
  332.    ''' </summary>
  333.    <ComImport(),
  334.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
  335.    Guid("000214F9-0000-0000-C000-000000000046")>
  336.    Private Interface IShellLinkW
  337.  
  338.        ''' <summary>
  339.        ''' Retrieves the path and file name of a Shell link object.
  340.        ''' </summary>
  341.        Sub GetPath(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  342.                    ByVal pszFile As StringBuilder,
  343.                    ByVal cchMaxPath As Integer,
  344.                    ByRef pfd As WIN32_FIND_DATAW,
  345.                    ByVal fFlags As SLGP_FLAGS)
  346.  
  347.        ''' <summary>
  348.        ''' Retrieves the list of item identifiers for a Shell link object.
  349.        ''' </summary>
  350.        Sub GetIDList(ByRef ppidl As IntPtr)
  351.  
  352.        ''' <summary>
  353.        ''' Sets the pointer to an item identifier list (PIDL) for a Shell link object.
  354.        ''' </summary>
  355.        Sub SetIDList(ByVal pidl As IntPtr)
  356.  
  357.        ''' <summary>
  358.        ''' Retrieves the description string for a Shell link object.
  359.        ''' </summary>
  360.        Sub GetDescription(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  361.                           ByVal pszName As StringBuilder,
  362.                           ByVal cchMaxName As Integer)
  363.  
  364.        ''' <summary>
  365.        ''' Sets the description for a Shell link object.
  366.        ''' The description can be any application-defined string.
  367.        ''' </summary>
  368.        Sub SetDescription(<MarshalAs(UnmanagedType.LPWStr)>
  369.                           ByVal pszName As String)
  370.  
  371.        ''' <summary>
  372.        ''' Retrieves the name of the working directory for a Shell link object.
  373.        ''' </summary>
  374.        Sub GetWorkingDirectory(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  375.                                ByVal pszDir As StringBuilder,
  376.                                ByVal cchMaxPath As Integer)
  377.  
  378.        ''' <summary>
  379.        ''' Sets the name of the working directory for a Shell link object.
  380.        ''' </summary>
  381.        Sub SetWorkingDirectory(<MarshalAs(UnmanagedType.LPWStr)>
  382.                                ByVal pszDir As String)
  383.  
  384.        ''' <summary>
  385.        ''' Retrieves the command-line arguments associated with a Shell link object.
  386.        ''' </summary>
  387.        Sub GetArguments(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  388.                         ByVal pszArgs As StringBuilder,
  389.                         ByVal cchMaxPath As Integer)
  390.  
  391.        ''' <summary>
  392.        ''' Sets the command-line arguments for a Shell link object.
  393.        ''' </summary>
  394.        Sub SetArguments(<MarshalAs(UnmanagedType.LPWStr)>
  395.                         ByVal pszArgs As String)
  396.  
  397.        ''' <summary>
  398.        ''' Retrieves the hot key for a Shell link object.
  399.        ''' </summary>
  400.        Sub GetHotkey(ByRef pwHotkey As Short)
  401.  
  402.        ''' <summary>
  403.        ''' Sets a hot key for a Shell link object.
  404.        ''' </summary>
  405.        Sub SetHotkey(ByVal wHotkey As Short)
  406.  
  407.        ''' <summary>
  408.        ''' Retrieves the show command for a Shell link object.
  409.        ''' </summary>
  410.        Sub GetShowCmd(ByRef piShowCmd As Integer)
  411.  
  412.        ''' <summary>
  413.        ''' Sets the show command for a Shell link object.
  414.        ''' The show command sets the initial show state of the window.
  415.        ''' </summary>
  416.        Sub SetShowCmd(ByVal iShowCmd As ShortcutWindowState)
  417.  
  418.        ''' <summary>
  419.        ''' Retrieves the location (path and index) of the icon for a Shell link object.
  420.        ''' </summary>
  421.        Sub GetIconLocation(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  422.                            ByVal pszIconPath As StringBuilder,
  423.                            ByVal cchIconPath As Integer,
  424.                            ByRef piIcon As Integer)
  425.  
  426.        ''' <summary>
  427.        ''' Sets the location (path and index) of the icon for a Shell link object.
  428.        ''' </summary>
  429.        Sub SetIconLocation(<MarshalAs(UnmanagedType.LPWStr)>
  430.                            ByVal pszIconPath As String,
  431.                            ByVal iIcon As Integer)
  432.  
  433.        ''' <summary>
  434.        ''' Sets the relative path to the Shell link object.
  435.        ''' </summary>
  436.        Sub SetRelativePath(<MarshalAs(UnmanagedType.LPWStr)>
  437.                            ByVal pszPathRel As String,
  438.                            ByVal dwReserved As Integer)
  439.  
  440.        ''' <summary>
  441.        ''' Attempts to find the target of a Shell link,
  442.        ''' even if it has been moved or renamed.
  443.        ''' </summary>
  444.        Sub Resolve(ByVal hwnd As IntPtr,
  445.                    ByVal fFlags As SLR_FLAGS)
  446.  
  447.        ''' <summary>
  448.        ''' Sets the path and file name of a Shell link object
  449.        ''' </summary>
  450.        Sub SetPath(ByVal pszFile As String)
  451.  
  452.    End Interface
  453.  
  454.    <ComImport(), Guid("0000010c-0000-0000-c000-000000000046"),
  455.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
  456.    Public Interface IPersist
  457.  
  458.        <PreserveSig()>
  459.        Sub GetClassID(ByRef pClassID As Guid)
  460.  
  461.    End Interface
  462.  
  463.    <ComImport(), Guid("0000010b-0000-0000-C000-000000000046"),
  464.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
  465.    Public Interface IPersistFile
  466.        Inherits IPersist
  467.  
  468.        Shadows Sub GetClassID(ByRef pClassID As Guid)
  469.  
  470.        <PreserveSig()>
  471.        Function IsDirty() As Integer
  472.  
  473.        <PreserveSig()>
  474.        Sub Load(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  475.                 pszFileName As String,
  476.                 dwMode As UInteger)
  477.  
  478.        <PreserveSig()>
  479.        Sub Save(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  480.                 pszFileName As String,
  481.                 <[In](), MarshalAs(UnmanagedType.Bool)>
  482.                 fRemember As Boolean)
  483.  
  484.        <PreserveSig()>
  485.        Sub SaveCompleted(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  486.                          pszFileName As String)
  487.  
  488.        <PreserveSig()>
  489.        Sub GetCurFile(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  490.                       ppszFileName As String)
  491.  
  492.    End Interface
  493.  
  494.    ' "CLSID_ShellLink" from "ShlGuid.h"
  495.    <ComImport(),
  496.    Guid("00021401-0000-0000-C000-000000000046")>
  497.    Public Class ShellLink
  498.    End Class
  499.  
  500. #End Region
  501.  
  502. #Region " Public Methods "
  503.  
  504.    ''' <summary>
  505.    ''' Resolves the target of a shortcut.
  506.    ''' If shortcut can't be resolved, an error message would be displayed.
  507.    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
  508.    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
  509.    ''' </summary>
  510.    ''' <param name="ShortcutFile">
  511.    ''' The shortcut file to resolve.
  512.    ''' </param>
  513.    ''' <param name="hwnd">
  514.    ''' The new handle pointer that would be generated
  515.    ''' for the window which should display the error message (if any).
  516.    ''' </param>
  517.    Public Shared Sub Resolve_Ui(ShortcutFile As String, hwnd As IntPtr)
  518.        LoadShortcut(ShortcutFile)
  519.        DirectCast(lnk, IShellLinkW).Resolve(hwnd, SLR_FLAGS.SLR_UPDATE)
  520.    End Sub
  521.  
  522.    ''' <summary>
  523.    ''' Resolves the target of a shortcut.
  524.    ''' If shortcut can't be resolved, any error message would be displayed.
  525.    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
  526.    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
  527.    ''' </summary>
  528.    ''' <param name="ShortcutFile">
  529.    ''' The shortcut file to resolve.
  530.    ''' </param>
  531.    Public Shared Sub Resolve_NoUi(ByVal ShortcutFile As String)
  532.        LoadShortcut(ShortcutFile)
  533.        DirectCast(lnk, IShellLinkW).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_UPDATE Or SLR_FLAGS.SLR_NO_UI)
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Returns the description of a shortcut file.
  538.    ''' </summary>
  539.    ''' <param name="ShortcutFile">
  540.    ''' The shortcut file to retrieve the info.
  541.    ''' </param>
  542.    Public Shared Function Get_Description(ByVal ShortcutFile As String) As String
  543.        LoadShortcut(ShortcutFile)
  544.        lnk_description.Clear()
  545.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  546.        Return lnk_description.ToString()
  547.    End Function
  548.  
  549.    ''' <summary>
  550.    ''' Returns the Arguments of a shortcut file.
  551.    ''' </summary>
  552.    ''' <param name="ShortcutFile">
  553.    ''' The shortcut file to retrieve the info.
  554.    ''' </param>
  555.    Public Shared Function Get_Arguments(ByVal ShortcutFile As String) As String
  556.        LoadShortcut(ShortcutFile)
  557.        lnk_arguments.Clear()
  558.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  559.        Return lnk_arguments.ToString()
  560.    End Function
  561.  
  562.    ''' <summary>
  563.    ''' Returns the path and filename of a shortcut file.
  564.    ''' </summary>
  565.    ''' <param name="ShortcutFile">
  566.    ''' The shortcut file to retrieve the info.
  567.    ''' </param>
  568.    Public Shared Function Get_FullPath(ByVal ShortcutFile As String) As String
  569.        LoadShortcut(ShortcutFile)
  570.        lnk_target.Clear()
  571.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  572.        Return lnk_target.ToString()
  573.    End Function
  574.  
  575.    ''' <summary>
  576.    ''' Returns the working directory of a shortcut file.
  577.    ''' </summary>
  578.    ''' <param name="ShortcutFile">
  579.    ''' The shortcut file to retrieve the info.
  580.    ''' </param>
  581.    Public Shared Function Get_WorkingDir(ByVal ShortcutFile As String) As String
  582.        LoadShortcut(ShortcutFile)
  583.        lnk_workingdir.Clear()
  584.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  585.        Return lnk_workingdir.ToString()
  586.    End Function
  587.  
  588.    ''' <summary>
  589.    ''' Returns the Hotkey of a shortcut file.
  590.    ''' </summary>
  591.    ''' <param name="ShortcutFile">
  592.    ''' The shortcut file to retrieve the info.
  593.    ''' </param>
  594.    Public Shared Function Get_Hotkey(ByVal ShortcutFile As String) As Short
  595.        LoadShortcut(ShortcutFile)
  596.        lnk_hotkey = -1
  597.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  598.        Return lnk_hotkey
  599.    End Function
  600.  
  601.    ''' <summary>
  602.    ''' Returns the Window State of a shortcut file.
  603.    ''' </summary>
  604.    ''' <param name="ShortcutFile">
  605.    ''' The shortcut file to retrieve the info.
  606.    ''' </param>
  607.    Public Shared Function Get_WindowStyle(ByVal ShortcutFile As String) As ShortcutWindowState
  608.        LoadShortcut(ShortcutFile)
  609.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  610.        Return lnk_windowstate
  611.    End Function
  612.  
  613.    ''' <summary>
  614.    ''' Returns the Icon location of a shortcut file.
  615.    ''' </summary>
  616.    ''' <param name="ShortcutFile">
  617.    ''' The shortcut file to retrieve the info.
  618.    ''' </param>
  619.    ''' <param name="IconIndex">
  620.    ''' Optional Integer type variable to store the IconIndex.
  621.    ''' </param>
  622.    Public Shared Function Get_IconLocation(ByVal ShortcutFile As String,
  623.                                            Optional ByRef IconIndex As Integer = 0) As String
  624.        LoadShortcut(ShortcutFile)
  625.        lnk_iconpath.Clear()
  626.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, IconIndex)
  627.        Return lnk_iconpath.ToString()
  628.    End Function
  629.  
  630.    ''' <summary>
  631.    ''' Retrieves all the information about a shortcut file.
  632.    ''' </summary>
  633.    ''' <param name="ShortcutFile">
  634.    ''' The shortcut file to retrieve the info.
  635.    ''' </param>
  636.    Public Shared Function GetInfo(ByVal ShortcutFile As String) As ShortcutInfo
  637.  
  638.        ' Load Shortcut
  639.        LoadShortcut(ShortcutFile)
  640.  
  641.        ' Reset variables
  642.        lnk_description.Clear()
  643.        lnk_arguments.Clear()
  644.        lnk_target.Clear()
  645.        lnk_workingdir.Clear()
  646.        lnk_iconpath.Clear()
  647.        lnk_hotkey = -1
  648.        lnk_iconindex = -1
  649.  
  650.        ' Retrieve Info
  651.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  652.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  653.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  654.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  655.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, lnk_iconindex)
  656.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  657.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  658.  
  659.        ' Return Info
  660.        Return New ShortcutInfo With {
  661.            .ShortcutFile = ShortcutFile,
  662.            .Description = lnk_description.ToString,
  663.            .Arguments = lnk_arguments.ToString,
  664.            .Target = lnk_target.ToString,
  665.            .Icon = lnk_iconpath.ToString,
  666.            .IconIndex = lnk_iconindex,
  667.            .WorkingDir = lnk_workingdir.ToString,
  668.            .Hotkey = Hex(lnk_hotkey),
  669.            .Hotkey_Modifier = [Enum].Parse(GetType(HotkeyModifiers), GetHiByte(lnk_hotkey)),
  670.            .Hotkey_Key = [Enum].Parse(GetType(Keys), GetLoByte(lnk_hotkey)),
  671.            .WindowState = lnk_windowstate,
  672.            .IsFile = File.Exists(lnk_target.ToString),
  673.            .IsDirectory = Directory.Exists(lnk_target.ToString),
  674.            .DriveLetter = lnk_target.ToString.Substring(0, 1),
  675.            .DirectoryName = lnk_target.ToString.Substring(0, lnk_target.ToString.LastIndexOf("\")),
  676.            .FileName = lnk_target.ToString.Split("\").LastOrDefault.Split(".").FirstOrDefault,
  677.            .FileExtension = lnk_target.ToString.Split(".").LastOrDefault
  678.        }
  679.  
  680.    End Function
  681.  
  682.    ''' <summary>
  683.    ''' Creates a shortcut file.
  684.    ''' </summary>
  685.    ''' <param name="FilePath">
  686.    ''' The filepath to create the shortcut.
  687.    ''' </param>
  688.    ''' <param name="Target">
  689.    ''' The target file or directory.
  690.    ''' </param>
  691.    ''' <param name="WorkingDirectory">
  692.    ''' The working directory os the shortcut.
  693.    ''' </param>
  694.    ''' <param name="Description">
  695.    ''' The shortcut description.
  696.    ''' </param>
  697.    ''' <param name="Arguments">
  698.    ''' The target file arguments.
  699.    ''' This value only should be set when target is an executable file.
  700.    ''' </param>
  701.    ''' <param name="Icon">
  702.    ''' The icon location of the shortcut.
  703.    ''' </param>
  704.    ''' <param name="IconIndex">
  705.    ''' The icon index of the icon file.
  706.    ''' </param>
  707.    ''' <param name="HotKey_Modifier">
  708.    ''' The hotkey modifier(s) which should be used for the hotkey combination.
  709.    ''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
  710.    ''' </param>
  711.    ''' <param name="HotKey_Key">
  712.    ''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
  713.    ''' </param>
  714.    ''' <param name="WindowState">
  715.    ''' The Window state for the target.
  716.    ''' </param>
  717.    Public Shared Sub Create(ByVal FilePath As String,
  718.                             ByVal Target As String,
  719.                             Optional ByVal WorkingDirectory As String = Nothing,
  720.                             Optional ByVal Description As String = Nothing,
  721.                             Optional ByVal Arguments As String = Nothing,
  722.                             Optional ByVal Icon As String = Nothing,
  723.                             Optional ByVal IconIndex As Integer = Nothing,
  724.                             Optional ByVal HotKey_Modifier As HotkeyModifiers = Nothing,
  725.                             Optional ByVal HotKey_Key As Keys = Nothing,
  726.                             Optional ByVal WindowState As ShortcutWindowState = ShortcutWindowState.Normal)
  727.  
  728.        LoadShortcut(FilePath)
  729.  
  730.        DirectCast(lnk, IShellLinkW).SetPath(Target)
  731.  
  732.        DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
  733.                                                            WorkingDirectory,
  734.                                                            Path.GetDirectoryName(Target)))
  735.  
  736.        DirectCast(lnk, IShellLinkW).SetDescription(Description)
  737.        DirectCast(lnk, IShellLinkW).SetArguments(Arguments)
  738.        DirectCast(lnk, IShellLinkW).SetIconLocation(Icon, IconIndex)
  739.  
  740.        DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key <> 0,
  741.                                                  Convert.ToInt32(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
  742.                                                  Nothing))
  743.  
  744.        DirectCast(lnk, IShellLinkW).SetShowCmd(WindowState)
  745.  
  746.        DirectCast(lnk, IPersistFile).Save(FilePath, True)
  747.        DirectCast(lnk, IPersistFile).SaveCompleted(FilePath)
  748.  
  749.    End Sub
  750.  
  751. #End Region
  752.  
  753. #Region " Private Methods "
  754.  
  755.    ''' <summary>
  756.    ''' Loads the shortcut object to retrieve information.
  757.    ''' </summary>
  758.    ''' <param name="ShortcutFile">
  759.    ''' The shortcut file to retrieve the info.
  760.    ''' </param>
  761.    Private Shared Sub LoadShortcut(ByVal ShortcutFile As String)
  762.        DirectCast(lnk, IPersistFile).Load(ShortcutFile, 0)
  763.    End Sub
  764.  
  765.    ''' <summary>
  766.    ''' Gets the low order byte of a number.
  767.    ''' </summary>
  768.    Private Shared Function GetLoByte(ByVal Intg As Integer) As Integer
  769.        Return Intg And &HFF&
  770.    End Function
  771.  
  772.    ''' <summary>
  773.    ''' Gets the high order byte of a number.
  774.    ''' </summary>
  775.    Private Shared Function GetHiByte(ByVal Intg As Integer) As Integer
  776.        Return (Intg And &HFF00&) / 256
  777.    End Function
  778.  
  779. #End Region
  780.  
  781. End Class
  782.  
  783. #End Region


« Última modificación: 18 Noviembre 2013, 16:19 pm por EleKtro H@cker » En línea



Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines