如果尚未打开,打开文件夹路径,如果打开显示窗口

时间:2014-11-18 20:21:24

标签: vb.net visual-studio

这似乎是一项简单的任务,但我似乎无法产生寻找的结果。

目前我有这段代码

 Dim folderpath As String

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    folderpath = "C:\epds\WIP"
    Process.Start("explorer.exe", folderpath)

End Sub

没关系,它会按照指示打开我的文件夹路径,但是,如果该文件夹的实例已在资源管理器中打开,我该如何使该窗口保持最新状态而不是打开新的窗口浏览器?

编辑:这似乎可以解决问题,感谢你指点我正确的方向@ Okuma.Scott

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow( _
  ByVal lpClassName As String, _
  ByVal lpWindowName As String) As IntPtr
End Function

<DllImport("user32.dll", EntryPoint:="FindWindow", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindowByClass( _
  ByVal lpClassName As String, _
  ByVal zero As IntPtr) As IntPtr
End Function

<DllImport("user32.dll", EntryPoint:="FindWindow", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindowByCaption( _
  ByVal zero As IntPtr, _
  ByVal lpWindowName As String) As IntPtr
End Function

Dim folderpath As String

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    folderpath = "C:\epds\WIP"
    'Process.Start("explorer.exe", folderpath)
    Dim nWnd As IntPtr
    Dim ceroIntPtr As New IntPtr(0)
    Dim Wnd_name As String

    Wnd_name = "WIP"
    nWnd = FindWindow(Nothing, Wnd_name)
    'show the info
    If nWnd.Equals(ceroIntPtr) Then
        Process.Start("explorer.exe", folderpath)
    Else
        AppActivate(Wnd_name)
        SendKeys.SendWait("~")
    End If


End Sub

3 个答案:

答案 0 :(得分:3)

我试图解决同样的问题并发现它似乎可以通过调用Process.Start来实现所需的路径:

Process.Start("C:\Temp")

如果文件夹已在资源管理器窗口中打开,则会打开现有窗口,否则会打开一个新窗口。

答案 1 :(得分:1)

您需要导入Imports System.Runtime.InteropServices

然后你可以使用Findwindow功能

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function

然后制作2个dims 1. folderpath,2是foldername
然后在您的点击事件中使用“System.IO.Path.GetFileName(folderpath)”来获取您要查找的窗口的名称。“for WIP WIP”

然后检查if语句,如果FindWindow(vbNullString,foldername)= 0“not open”

vbNullString表示打印和显示函数以及调用外部过程的零长度字符串。“msdn”

因此,如果findwindow为0,则打开文件夹,然后对焦文件夹

Dim folderpath As String
Dim foldername As String

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    folderpath = "C:\epds\WIP"
    foldername = System.IO.Path.GetFileName(folderpath)
    If FindWindow(vbNullString, foldername) = 0 Then
        Process.Start("explorer.exe", folderpath)
    Else
        AppActivate(foldername)
        SendKeys.SendWait("~")
    End If
End Sub

答案 2 :(得分:0)

这有效,并且不会打开多个窗口:

Process.Start(new ProcessStartInfo() { FileName = "C:\\", UseShellExecute = true });

唯一的缺点是它不会将打开的文件夹放在前台(根据您的使用情况,这可能是坏事也可能不是坏事!