2012-06-16 230 views
-2

對於我的生活,我不明白爲什麼我的編碼不起作用。如果文件在記事本中打開,下面的代碼會給我一個消息,但是如果文件在word或excel中打開,那麼這種方式不會消失?檢查文件是否打開

Dim apps = 0 
    Dim Process() As Process = System.Diagnostics.Process.GetProcesses 
    For Each p As Process In Process 
     If p.MainWindowTitle.ToString.Contains("test") Then 
      If p.ProcessName = "notepad" Then 
       MsgBox("test file is open in notepad") 
       apps += 1 
      ElseIf p.ProcessName = "winword" Then 
       MsgBox("test file is open in word") 
       apps += 1 
      ElseIf p.ProcessName = "excel" Then 
       MsgBox("test file is open in excel") 
       apps += 1 
      End If 
     End If 
    Next 

    If apps = 0 Then 
     'run my code 
    End If 

這似乎並沒有檢查word和excel,但下面的代碼片段的工作?

Dim Process2() As Process = System.Diagnostics.Process.GetProcessesByName("winword") 
    For Each p As Process In Process2 
     If p.MainWindowTitle.Contains("test") Then 
      MsgBox("test file is open in word") 
     End If 
    Next 

Dim Process2() As Process = System.Diagnostics.Process.GetProcessesByName("excel") 
    For Each p As Process In Process2 
     If p.MainWindowTitle.Contains("test") Then 
      MsgBox("test file is open in excel") 
     End If 
    Next 
+0

什麼用'MainWindowTitle'後'.ToString'在你的第一個例子是?您是否嘗試調試 –

+0

?!我建議你這樣做,那麼你很容易就會發現問題所在 –

回答

2

因爲p.ProcessName是 「WINWORD」 - >大寫
您測試 「WINWORD」 - >小寫。

改變你的測試

if(String.Compare(p.ProcessName, "winword", true)) 
    ..... 

忽略的情況下