1

I want to ask the correct way to use Mutex so that external apps (Notepad) can be opened once. Below are the codes that I am trying right now.

Imports System.Threading
Public Class Form1
Dim proc As New System.Diagnostics.Process()
Public Function IsSingleInstance() As Boolean
    Try
        Mutex.OpenExisting("Mutex") 
    Catch
        mutexx = New Mutex(True, "Mutex")
        Return True
    End Try
    Return False
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    proc = Process.Start("notepad.exe")
    proc.WaitForInputIdle()
    Me.Activate()

    If Not IsSingleInstance() Then
        MsgBox("There are more instance!")
        proc.CloseMainWindow()
    Else
        IsSingleInstance()
    End If
End Sub
End Class

The problem with my code is that after I close all notepad windows and click button1 again, notepad cannot be opened. I hope that maybe you guys can share ideas on solving this problem. Thank you.

iamaftar
  • 11
  • 1
  • 1
    Can't you just write, e.g., `Dim notepadIsRunning = Process.GetProcessesByName("notepad").FirstOrDefault() IsNot Nothing`? – Jimi Jun 17 '21 at 13:38
  • Using Mutex in this context doesn’t make sense (especially in external not handled apps). There are not threads that needs to interact to each other. In your case (based on your code) it’s sufficient to know that if process runs,so, just use Jimi’s comment. – G3nt_M3caj Jun 17 '21 at 14:09
  • Thank you both of you, Jimi and g3nt-m3caj. It's just that when I searched for keywords prevent apps from opening more than once on google, many mention about Mutex. That's why I narrow it down to Mutex usage. So, basically, for external not handled apps, there's no need for Mutex, right? – iamaftar Jun 17 '21 at 14:27
  • Your fundamental problem as implemented is that you open the Mutex but never close it. (And this potentially poses problems down the line with leaking Windows kernel resources.) Note that this strategy only makes sense if you want to coordinate between multiple instances of your own application. If you're working within a single instance, there are lighter-weight ways to do it. And you can't do anything about people opening an instance of e.g. Notepad outside of your application, because you don't control Notepad itself. – Craig Jun 17 '21 at 20:27
  • 1
    @Craig You can. With UI Automation and handling [WindowPatter.WindowOpendEvent](https://learn.microsoft.com/en-us/dotnet/api/system.windows.automation.windowpattern.windowopenedevent) and `WindowPatter.WindowCloseEvent`. Or installing WMI / MMI events notifications, e.g., [ManagementEventWatcher](https://learn.microsoft.com/en-us/dotnet/api/system.management.managementeventwatcher), targeting the `Win32_Process` class. There's an example there exactly related to the Notepad Process creation/destruction notifications. Or polling with the Process class (heavy). Or... – Jimi Jun 17 '21 at 21:08

0 Answers0