1

I'm using infinite loop to know when a word file is open.
Is there any other way to avoid infinite loop, like trigger for something?

Do While True
  CheckIfRunning(NewStatues, OldStatues)
  Threading.Thread.Sleep(10000)
Loop
MatSnow
  • 7,357
  • 3
  • 19
  • 31
Salahudin Malik
  • 398
  • 4
  • 17
  • 2
    What does CheckIfRunning do? Could you try something like this, using ManagementEventWatcher? https://stackoverflow.com/questions/18757391/detect-when-exe-is-started-vb-net (you may have to add System.Management as a reference, it wasn't added by default for me) – Capellan Nov 17 '17 at 12:17
  • 2
    Possible duplicate of [Detect when exe is started vb.net](https://stackoverflow.com/questions/18757391/detect-when-exe-is-started-vb-net) – MatSnow Nov 17 '17 at 12:19

1 Answers1

1

You can use the FileSystemWatcher class.
It can be used to watch & report changes to files and directories.

Opening a file, in this case, generates a change in the directory files structure because a temporary file is created, thus causing the FileSystemWatcher to report the event.
Depending on which events have been subscribed, more than one event may be raised.

FileSystemEventArgs gives information about the event:

➜ .ChangeType     Defines what changed (a file has been renamed, opened, deleted...)
➜ .Name                Name of the File or Directory affected
➜ .FullPath            Fully qualified name of the file or directory

Private WithEvents fsw As System.IO.FileSystemWatcher

Private Sub SetupFileSystemWatcher()
    fsw = New System.IO.FileSystemWatcher()
    fsw.Filter = "*.docx"
    fsw.Path = "SomePathToWatch"

    'Set at least a filter to NotifyFilters.LastAccess, so that when a
    'file is opened (saved, created, deleted, renamed), you are notified
    fsw.NotifyFilter = (System.IO.NotifyFilters.LastAccess Or _
                        System.IO.NotifyFilters.LastWrite Or _
                        System.IO.NotifyFilters.FileName Or _
                        System.IO.NotifyFilters.DirectoryName)

    'Set the handler to the events you want to receive
    AddHandler fsw.Changed, AddressOf OnChanged
    AddHandler fsw.Created, AddressOf OnChanged
    AddHandler fsw.Deleted, AddressOf OnChanged
    AddHandler fsw.Renamed, AddressOf OnRenamed
    fsw.EnableRaisingEvents = True
End Sub

'Setup the delegates to receive the events raised by the FileWatcher
Private Shared Sub OnChanged(sender As Object, e As System.IO.FileSystemEventArgs)
    Console.Write("A file has been Opened, Saved, Created or Deleted")
End Sub

Private Shared Sub OnRenamed(sender As Object, e As System.IO.RenamedEventArgs)
    Console.Write("A file has been Renamed")
End Sub
Jimi
  • 29,621
  • 8
  • 43
  • 61