I'm writing a screen capture application for a client. The capture part is fine, but he wants to get the name and path of the file that the capture is of.
Using system.diagnostics.process I am able to get the process that the capture is of, and can get the full path of the EXE, but not the file that is open.
ie. Notepad is open with 'TextFile1.txt' as its document. I can get from the process the MainWindowTitle which would be 'TextFile1.txt - Notepad' but what I need is more like 'c:\users....\TextFile1.txt'
Is there a way of getting more information from the process?
I'm sure there is a way, but I can't figure it out
Any help greatly appreciated.
You can use ManagementObjectSearcher to get the command line arguments for a process, and in this notepad example, you can parse out the file name. Here's a simple console app example that writes out the full path and file name of all open files in notepad..
Imports System
Imports System.ComponentModel
Imports System.Management
Module Module1
Sub Main()
Dim cl() As String
For Each p As Process In Process.GetProcessesByName("notepad")
Try
Using searcher As New ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " & p.Id)
For Each mgmtObj As ManagementObject In searcher.Get()
cl = mgmtObj.Item("CommandLine").ToString().Split("""")
Console.WriteLine(cl(cl.Length - 1))
Next
End Using
Catch ex As Win32Exception
'handle error
End Try
Next
System.Threading.Thread.Sleep(1000000)
End Sub
End Module
I had to add a reference to this specific dll:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Managment.dll
i think it is the simplest way
For Each prog As Process In Process.GetProcesses
If prog.ProcessName = "notepad" Then
ListBox1.Items.Add(prog.ProcessName)
End If
Next
I know this post is old, but since I've searched for this two days ago, I'm sure others would be interested. My code below will get you the file paths from Notepad, Wordpad, Excel, Microsoft Word, PowerPoint, Publisher, Inkscape, and any other text or graphic editor's process, as long as the filename and extension is in the title bar of the opened window.
Instead of searching, it obtains the file's target path from Windows' hidden Recent Items directory, which logs recently opened and saved files as shortcuts. I discovered this hidden directory in Windows 7. You're gonna have to check if Windows 10 or 11 has this:
C:\Users\ "username" \AppData\Roaming\Microsoft\Windows\Recent
I slapped this code together under Framework 4, running as 64bit. The COM dlls that must be referenced in order for the code to work are Microsoft Word 14.0 Object Library, Microsoft Excel 14.0 Object Library, Microsoft PowerPoint 14.0 Object Library, and Microsoft Shell Controls And Automation.
For testing, the code below needs a textbox, a listbox, a button, and 3 labels (Label1, FilenameLabel, Filepath).
Once you have this working, after submitting a process name, you will have to click the filename item in the ListBox to start the function to retrieve it's directory path.
Option Strict On
Option Explicit On
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop.Word
Imports Microsoft.Office.Interop.PowerPoint
Imports Shell32
Public Class Form1
'function gets names of all opened Excel workbooks, adding them to the ListBox
Public Shared Function ExcelProcess(ByVal strings As String) As String
Dim Excel As Microsoft.Office.Interop.Excel.Application = CType(Marshal.GetActiveObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
For Each Workbook As Microsoft.Office.Interop.Excel.Workbook In Excel.Workbooks
Form1.ListBox1.Items.Add(Workbook.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
'function gets names of all opened Word documents, adding them to the ListBox
Public Shared Function WordProcess(ByVal strings As String) As String
Dim Word As Microsoft.Office.Interop.Word.Application = CType(Marshal.GetActiveObject("Word.Application"), Microsoft.Office.Interop.Word.Application)
For Each Document As Microsoft.Office.Interop.Word.Document In Word.Documents
Form1.ListBox1.Items.Add(Document.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
'function gets names of all opened PowerPoint presentations, adding them to the ListBox
Public Shared Function PowerPointProcess(ByVal strings As String) As String
Dim PowerPoint As Microsoft.Office.Interop.PowerPoint.Application = CType(Marshal.GetActiveObject("PowerPoint.Application"), Microsoft.Office.Interop.PowerPoint.Application)
For Each Presentation As Microsoft.Office.Interop.PowerPoint.Presentation In PowerPoint.Presentations
Form1.ListBox1.Items.Add(Presentation.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'clears listbox to prepare for new process items
ListBox1.Items.Clear()
'gets process title from TextBox1
Dim ProcessName As String = TextBox1.Text
'prepare string's case format for
ProcessName = ProcessName.ToLower
'corrects Office process names
If ProcessName = "microsoft excel" Then
ProcessName = "excel"
Else
If ProcessName = "word" Or ProcessName = "microsoft word" Then
ProcessName = "winword"
Else
If ProcessName = "powerpoint" Or ProcessName = "microsoft powerpoint" Then
ProcessName = "powerpnt"
Else
End If
End If
End If
'get processes by name (finds only one instance of Excel or Microsoft Word)
Dim proclist() As Process = Process.GetProcessesByName(ProcessName)
'adds window titles of all processes to a ListBox
For Each prs As Process In proclist
If ProcessName = "excel" Then
'calls function to add all Excel process instances' workbook names to the ListBox
ExcelProcess(ProcessName)
Else
If ProcessName = "winword" Then
'calls function to add all Word process instances' document names to the ListBox
WordProcess(ProcessName)
Else
If ProcessName = "powerpnt" Then
'calls function to add all Word process instances' document names to the ListBox
PowerPointProcess(ProcessName)
Else
'adds all Notepad or Wordpad process instances' filenames
ListBox1.Items.Add(prs.MainWindowTitle)
End If
End If
End If
Next
End Sub
Private Sub ListBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseClick
Try
'add ListBox item (full window title) to string
Dim ListBoxSelection As String = String.Join(Environment.NewLine, ListBox1.SelectedItems.Cast(Of String).ToArray)
'get full process title after "-" from ListBoxSelection
Dim GetProcessTitle As String = ListBoxSelection.Split("-"c).Last()
'create string to remove from ListBoxSelection
Dim Remove As String = " - " & GetProcessTitle
'Extract filename from ListBoxSelection string, minus process full name
Dim Filename As String = ListBoxSelection.Substring(0, ListBoxSelection.Length - Remove.Length + 1)
'display filename
FilenameLabel.Text = "Filename: " & Filename
'for every file opened and saved via savefiledialogs and openfiledialogs in editing software
'Microsoft Windows always creates and modifies shortcuts of them in Recent Items directory:
'C:\Users\ "Username" \AppData\Roaming\Microsoft\Windows\Recent
'so the below function gets the target path from files's shortcuts Windows created
FilePathLabel.Text = "File Path: " & GetLnkTarget("C:\Users\" & Environment.UserName & "\AppData\Roaming\Microsoft\Windows\Recent\" & Filename & ".lnk")
Catch ex As Exception
'no file path to show if nothing was saved yet
FilePathLabel.Text = "File Path: Not saved yet."
End Try
End Sub
'gets file's shortcut's target path
Public Shared Function GetLnkTarget(ByVal lnkPath As String) As String
Dim shl = New Shell32.Shell()
lnkPath = System.IO.Path.GetFullPath(lnkPath)
Dim dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath))
Dim itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath))
Dim lnk = DirectCast(itm.GetLink, Shell32.ShellLinkObject)
Return lnk.Target.Path
End Function
End Class
Related
I have a VB.NET program which lists some text files in a directory and loops through them. For each file, the program calls notepad.exe with the /p parameter and the filename to print the file, then copies the file to a history directory, sleeps for 5 seconds(to allow notepad to open and print), and finally deletes the original file.
What's happening is, instead of printing every single text file, it is only printing "random" files from the directory. Every single text file gets copied to the history directory and deleted from the original however, so I know that it is definitely listing all of the files and attempting to process each one. I've tried adding a call to Thread.Sleep for 5000 milliseconds, then changed it to 10000 milliseconds to be sure that the original file wasn't getting deleted before notepad grabbed it to print.
I'm more curious about what is actually happening than anything (a fix would be nice too!). I manually moved some of the files that did not print to the original directory, removing them from the history directory, and reran the program, where they DID print as they should, so I know it shouldn't be the files themselves, but something to do with the code.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim f() As String = ListFiles("l:\", "997")
Dim i As Integer
Try
For i = 0 To f.Length - 1
If Not f(i) = "" Then
System.Diagnostics.Process.Start("Notepad.exe", " /p l:\" & f(i))
My.Computer.FileSystem.CopyFile("l:\" & f(i), "k:\" & f(i))
'Thread.Sleep(5000)
Thread.Sleep(10000)
My.Computer.FileSystem.DeleteFile("l:\" & f(i))
End If
Next
'Thread.Sleep(5000)
Thread.Sleep(10000)
Catch ex As Exception
End Try
End Sub
Public Function ListFiles(ByVal strFilePath As String, ByVal strFileFilter As String) As String()
'finds all files in the strFilePath variable and matches them to the strFileFilter variable
'adds to string array strFiles if filename matches filter
Dim i As Integer = 0
Dim strFileName As String
Dim strFiles(0) As String
Dim strExclude As String = ""
Dim pos As Integer = 0
Dim posinc As Integer = 0
strFileName = Dir(strFilePath)
Do While Len(strFileName) > 0
'check to see if filename matches filter
If InStr(strFileName, strFileFilter) Then
If InStr(strFileName, "997") Then
FileOpen(1, strFilePath & strFileName, OpenMode.Input)
Do Until EOF(1)
strExclude = InputString(1, LOF(1))
Loop
pos = InStr(UCase(strExclude), "MANIFEST")
posinc = posinc + pos
pos = InStr(UCase(strExclude), "INVOICE")
posinc = posinc + pos
FileClose(1)
Else : posinc = 1
End If
If posinc > 0 Then
'add file to array
ReDim Preserve strFiles(i)
strFiles(i) = strFileName
i += 1
Else
My.Computer.FileSystem.MoveFile("l:\" & strFileName, "k:\" & strFileName)
End If
'MsgBox(strFileName & " " & IO.File.GetLastWriteTime(strFileName).ToString)
pos = 0
posinc = 0
End If
'get the next file
strFileName = Dir()
Loop
Return strFiles
End Function
Brief overview of the code above. An automated program fills the "L:\" directory with text files, and this program needs to print out certain files with "997" in the filename (namely files with "997" in the filename and containing the text "INVOICE" or "MANIFEST"). The ListFiles function does exactly this, then back in the Form1_Load() sub it is supposed to print each file, copy it, and delete the original.
Something to note, this code is developed in Visual Studio 2013 on Windows 7. The machine that actually runs this program is still on Windows XP.
I can see a few issues. the first and most obvious is the error handling:
You have a Try.. Catch with no error handling. You may be running in to an error without knowing it!! Add some output here, so you know if that is the case.
The second issue is to do with the way you are handling Process classes.
Instead of just calling System.Diagnostics.Process.Start in a loop and sleeping you should use the inbuilt method of handling execution. You are also not disposing of anything, which makes me die a little inside.
Try something like
Using p As New System.Diagnostics.Process
p.Start("Notepad.exe", " /p l:\" & f(i))
p.WaitForExit()
End Using
With both of these changes in place you should not have any issues. If you do there should at least be errors for you to look at and provide here, if necessary.
Following is a code sample of Addin I copied from MSDN(http://msdn.microsoft.com/en-us/library/vstudio/envdte.addin.aspx) and did some modifications to. I create a Add-in project by VS2008 and paste the following code into it.
But it seems that it does not work properly.
1> DTE Add-in count before and after the Update does not change
2> Guid of the added addin is all zeros
3> I get error: The parameter is incorrect, at code line: DTE.Solution.AddIns.Add
Public Sub OnConnection(ByVal application As Object, ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, ByRef custom As Array) Implements IDTExtensibility2.OnConnection
_applicationObject = CType(application, DTE2)
_addInInstance = CType(addInInst, AddIn)
Me.AddInExample(_applicationObject)
End Sub
Function BrowseFile() As String
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "*.dll file (*.dll)|*.dll|All files (*.*)|*.*"
OpenFileDialog1.FilterIndex = 1dialog
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
'MsgBox(OpenFileDialog1.FileName)
Return OpenFileDialog1.FileName
End If
Return ""
End Function
Sub AddInExample(ByVal DTE As DTE2)
' For this example to work correctly, there should be an add-in
' available in the Visual Studio environment.
' Set object references.
Dim addincoll As AddIns
Dim addinobj As AddIn
' Register an add-in, check DTE Add-in count before and after the
' Update.
addincoll = DTE.AddIns
MsgBox("AddIns collection parent name: " & addincoll.Parent.Name)
MsgBox("Number of Add-ins: " & addincoll.Count)
' NOTE: Use regsvr32 for Visual C++, regasm for [Visual Basic
' and Visual C#. Also, the pathname used below is an example only.
'Shell("regasm F:\AddIns\RegExplore\Debug\regexplore.dll")
'Shell("C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm e:\AddinTest1.dll")
Shell("C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm " & BrowseFile())
addincoll.Update()
MsgBox("Number of Add-ins: " & addincoll.Count)
addinobj = addincoll.Item(1)
' Connect the add-in if it is not already connected
' and list its SatelliteDLLPath and Guid.
If addinobj.Connected = False Then
addinobj.Connected = True
End If
MsgBox("Satellite DLL Path: " & addinobj.SatelliteDllPath)
MsgBox("DLL GUID: " & addinobj.Guid)
' Activates a solution add-in so that it is available, then
'deactivates it.
MsgBox(addinobj.ProgID)
MsgBox(addinobj.Description)
MsgBox(addinobj.Name)
addinobj = DTE.Solution.AddIns.Add(addinobj.ProgID, addinobj.Description, addinobj.Name, False)
DTE.Solution.AddIns.Item(1).Remove()
End Sub
I would start at the begining if I were you: MSDN VS Addin
Doing it this way allows you to debug (step-through) your code and will give you a good start. The page you are on assumes you already know how to do this.
It sounds very simple but I have searched and cannot seem to find a way to open a log file which the user just created from my windows form app. The file exits I just want to open it after it is created.
I have a Dim path As String = TextBox1.Text and once the user names and clicks ok on the savefiledialog I have a msgbox that says "Done" and when you hit OK I have tried this
FileOpen(FreeFile, path, OpenMode.Input) but nothing happens. I just want it to open the log and show it to the user so they can edit or save it again or anything.
This is where I got the above code.
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.filesystem.fileopen.aspx
Searching is difficult because everyone is trying to "Open" a file and process it during runtime. I am just trying to Show a file by Launching it like someone just double clicked it.
Here is the entire Export Button click Sub. It basically writes listbox items to file.
Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
Dim sfd As New SaveFileDialog
Dim path As String = TextBox1.Text
Dim arypath() As String = Split(TextBox1.Text, "\")
Dim pathDate As String
Dim foldername As String
foldername = arypath(arypath.Length - 1)
pathDate = Now.ToString("yyyy-MM-dd") & "_" & Now.ToString("hh;mm")
sfd.FileName = "FileScannerResults " & Chr(39) & foldername & Chr(39) & " " & pathDate
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
sfd.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
sfd.ShowDialog()
path = sfd.FileName
Using SW As New IO.StreamWriter(path)
If CkbxFolder.Checked = True Then
SW.WriteLine("Folders")
For Each itm As String In ListBox1.Items
SW.WriteLine(itm)
Next
End If
If CkbxFiles.Checked = True Then
SW.WriteLine("Files")
For Each itm As String In ListBox2.Items
SW.WriteLine(itm)
Next
End If
End Using
MsgBox("Done...")
FileOpen(FreeFile, path, OpenMode.Input) 'Why can't I open a file for you...
End Sub
Do not use the old VB6 methods. They are still here for compatibility reason, the new code should use the more powerful methods in the System.IO namespace.
However, as said in comments, FileOpen don't show anything for you, just opens the file
You coud write
Using sr = new StreamReader(path)
Dim line = sr.ReadLine()
if !string.IsNullOrEmpty(line) Then
textBoxForLog.AppendText(line)
End If
End Using
or simply (if the file is not too big)
Dim myLogText = File.ReadAllText(path)
textBoxForLog.Text = myLogText
As alternative, you could ask the operating system to run the program associated with the file extension and show the file for you
Process.Start(path)
To get the same behavior as if the user double-clicked it, just use System.Diagnostics.Process, and pass the filename to it's Start method:
Process.Start(path)
This will open the file using whatever the default application is for that filename based on its extension, just like Explorer does when you double-click it.
I'm building some Word 2003 macro that have to be put in the %APPDATA%\Microsoft\Word\Startup folder.
I can't change the location of this folder (to a network share). How can I auto update this macros ?
I have tried to create a bootstrapper macro, with an AutoExec sub that copy newer version from a file share to this folder. But as Word is locking the file, I get a Denied Exception.
Any idea ?
FYI, I wrote this code. The code is working fine for update templates in templates directory, but not in startup directory :
' Bootstrapper module
Option Explicit
Sub AutoExec()
Update
End Sub
Sub Update()
MirrorDirectory MyPath.MyAppTemplatesPath, MyPath.WordTemplatesPath
MirrorDirectory MyPath.MyAppStartupTemplatesPath, MyPath.WordTemplatesStartupPath
End Sub
' IOUtilities Module
Option Explicit
Dim fso As New Scripting.FileSystemObject
Public Sub MirrorDirectory(sourceDir As String, targetDir As String)
Dim result As FoundFiles
Dim s As Variant
sourceDir = RemoveTrailingBackslash(sourceDir)
targetDir = RemoveTrailingBackslash(targetDir)
With Application.FileSearch
.NewSearch
.FileType = MsoFileType.msoFileTypeAllFiles
.LookIn = sourceDir
.SearchSubFolders = True
.Execute
Set result = .FoundFiles
End With
For Each s In result
Dim relativePath As String
relativePath = Mid(s, Len(sourceDir) + 1)
Dim targetPath As String
targetPath = targetDir + relativePath
CopyIfNewer CStr(s), targetPath
Next s
End Sub
Public Function RemoveTrailingBackslash(s As String)
If Right(s, 1) = "\" Then
RemoveTrailingBackslash = Left(s, Len(s) - 1)
Else
RemoveTrailingBackslash = s
End If
End Function
Public Sub CopyIfNewer(source As String, target As String)
Dim shouldCopy As Boolean
shouldCopy = False
If Not fso.FileExists(target) Then
shouldCopy = True
ElseIf FileDateTime(source) > FileDateTime(target) Then
shouldCopy = True
End If
If (shouldCopy) Then
If Not fso.FolderExists(fso.GetParentFolderName(target)) Then fso.CreateFolder (fso.GetParentFolderName(target))
fso.CopyFile source, target, True
Debug.Print "File copied : " + source + " to " + target
Else
Debug.Print "File not copied : " + source + " to " + target
End If
End Sub
' MyPath module
Property Get WordTemplatesStartupPath()
WordTemplatesStartupPath = "Path To Application Data\Microsoft\Word\STARTUP"
End Property
Property Get WordTemplatesPath()
WordTemplatesPath = "Path To Application Data\Microsoft\Templates\Myapp\"
End Property
Property Get MyAppTemplatesPath()
MyAppTemplatesPath = "p:\MyShare\templates"
End Property
Property Get XRefStartupTemplatesPath()
MyAppStartupTemplatesPath = "p:\MyShare\startup"
End Property
[Edit] I explored another way
Another way I'm thinking about, is to pilot the organizer :
Sub Macro1()
'
' Macro1 Macro
' Macro recorded 10/7/2011 by beauge
'
Application.OrganizerCopy source:="P:\MyShare\Startup\myapp_bootstrapper.dot", _
Destination:= _
"PathToApplication Data\Microsoft\Word\STARTUP\myapp_bootstrapper.dot" _
, Name:="MyModule", Object:=wdOrganizerObjectProjectItems
End Sub
This is working, but has limitations :
either I have to hard-code modules to organize
or I have to change the option "Trust VBA project" to autodiscover items like this (which is not acceptable as it requires to lower the security of the station) :
the code of the project enumeration is this one :
Public Sub EnumProjectItem()
Dim sourceProject As Document
Dim targetProject As Document
Set sourceProject = Application.Documents.Open("P:\MyShare\Startup\myapp_bootstrapper.dot", , , , , , , , , wdOpenFormatTemplate)
Set targetProject = Application.Documents.Open("PathToApplication Data\Microsoft\Word\STARTUP\myapp_bootstrapper.dot", , , , , , , , , wdOpenFormatTemplate)
Dim vbc As VBcomponent
For Each vbc In sourceProject.VBProject.VBComponents 'crash here
Application.ActiveDocument.Range.InsertAfter (vbc.Name + " / " + vbc.Type)
Application.ActiveDocument.Paragraphs.Add
Next vbc
End Sub
[Edit 2] Another unsuccessful try :
I put, in my network share, a .dot with all the logic.
In my STARTUP folder, I put a simple .Dot file, that references the former one, with a single "Call MyApp.MySub".
This is actually working, but as the target template is not in a trusted location, a security warning is popped up each time word is launched (even if not related to the current application macro)
At least, I succeed partially using these steps :
Create a setup package. I use a NSIS script
the package detect any instance of Winword.exe and ask the user to retry when word is closed
extract from the registry the word's option path
deploy the files into the word's startup folder
add an uninstaller in the local user add/remove programs
I put the package in the remote share. I also added a .ini file containing the last version of the package (in the form "1.0")
In the macro itself, I have a version number ("0.9" for example).
At the startup (AutoExec macro), I compare the local version to the remote version
I use shell exec to fire the setup if a newer version is found.
The setup will wait for Word to close
A bit tricky, but it works on Word 2K3 and Word 2K10.
How to retrieve file icons associated with the file types and add them with the items of Listview in vb.net
I read about SHGetFileInfo but I didn't understand anything from that
please give me solution or please explain me ho system works with the .net controls in details
Having looked up SHGetFileInfo I can see why you're confused by it, but I think it might be slightly overkill for what I think you're trying to do i.e. enumerating the contents of a folder and adding items to the Listview.
If we have a form that contains a ListView and an ImageList, with the two related by having the ListView's LargeImageList property set to the ImageList, then here's how we put the contents of a folder into the ListView with the icons coming from the associated EXE file for each file.
Imports System.IO
Imports System.Drawing
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exePath As String
Dim exeIcon As Icon
dirInfo = New DirectoryInfo(path_to_some_folder
'We use this For...Each to iterate over the collection of files in the folder
For Each fileInfo In dirInfo.GetFiles
'We can only find associated exes by extension, so don't show any files that have no extension
If fileInfo.Extension = String.Empty Then
Else
'Use the function to get the path to the executable for the file
exePath = GetAssociatedProgram(fileInfo.Extension)
'Use ExtractAssociatedIcon to get an icon from the path
exeIcon = Drawing.Icon.ExtractAssociatedIcon(exePath)
'Add the icon if we haven't got it already, with the executable path as the key
If ImageList1.Images.ContainsKey(exePath) Then
Else
ImageList1.Images.Add(exePath, exeIcon)
End If
'Add the file to the ListView, with the executable path as the key to the ImageList's image
ListView1.Items.Add(fileInfo.Name, exePath)
End If
Next
End Sub
GetAssociatedProgram comes from developer.com
Public Function GetAssociatedProgram(ByVal FileExtension As _
String) As String
' Returns the application associated with the specified
' FileExtension
' ie, path\denenv.exe for "VB" files
Dim objExtReg As Microsoft.Win32.RegistryKey = _
Microsoft.Win32.Registry.ClassesRoot
Dim objAppReg As Microsoft.Win32.RegistryKey = _
Microsoft.Win32.Registry.ClassesRoot
Dim strExtValue As String
Try
' Add trailing period if doesn't exist
If FileExtension.Substring(0, 1) <> "." Then _
FileExtension = "." & FileExtension
' Open registry areas containing launching app details
objExtReg = objExtReg.OpenSubKey(FileExtension.Trim)
strExtValue = objExtReg.GetValue("").ToString
objAppReg = objAppReg.OpenSubKey(strExtValue & _
"\shell\open\command")
' Parse out, tidy up and return result
Dim SplitArray() As String
SplitArray = Split(objAppReg.GetValue(Nothing).ToString, """")
If SplitArray(0).Trim.Length > 0 Then
Return SplitArray(0).Replace("%1", "")
Else
Return SplitArray(1).Replace("%1", "")
End If
Catch
Return ""
End Try
End Function
At the end of all of that, when you run this code on this folder:
alt text http://www.philippursglove.com/stackoverflow/listview1.png
you should get:
alt text http://www.philippursglove.com/stackoverflow/listview2.png
If you know the file name of the file whose icon you want, you can use the System.Drawing.Icon.ExtractAssociatedIcon function for that purpose. e.g.
Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(#"C:\WINDOWS\system32\notepad.exe");
You can also refer to my answer to a related question for more implementation details.