摘要:如何防止重複執行程式
原文位置:
http://forums.microsoft.com/msdn-cht/ShowPost.aspx?PostID=1835300&SiteID=14
Question:
我的環境是: WinXP pro + Office XP + VS.net 2005
我的程式有設定為單一執行個體,我希望如果使用者連續執行程式兩次時,只在第一次執行時出現Msgbox("Start Running"),我將下面的程式加入MDI母表單中
- Public Sub Me_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles
- Me.Startup
- MsgBox("Start Running")
- End Sub
- Public Event Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs)
Public Sub Me_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup MsgBox("Start Running") End Sub Public Event Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs)
可是執行時並沒有作用,請問我要如何才能做到這樣的功能??
Answer:
您可以在Form_Load加入您想要加入的訊息就可以了;
另外補充一下,如果您在專案屬性中把"建立單一執行個體選項"勾選的話,執行第二次的時候會自動將焦點轉移到第一次執行的程式;如果不用這個方式去做的話,下面有另外一個方式可以參考看看
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
- System.EventArgs) Handles MyBase.Load
- ''防止重複執行
- If PrevInstance() Then
- MessageBox.Show("程式執行中")
- Application.Exit()
- Exit Sub
- End If
- MessageBox.Show("Load")
- End Sub
- Public Function PrevInstance() As Boolean
- If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
- Return True
- Else
- Return False
- End If
- End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
''防止重複執行
If PrevInstance() Then
MessageBox.Show("程式執行中")
Application.Exit()
Exit Sub
End If
MessageBox.Show("Load")
End Sub
Public Function PrevInstance() As Boolean
If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
Return True
Else
Return False
End If
End Function