C# 是否按进程名称取消隐藏进程?

C# 是否按进程名称取消隐藏进程?,c#,vb.net,winforms,winapi,process,C#,Vb.net,Winforms,Winapi,Process,很久以前,我编写了一段代码来隐藏/恢复流程窗口,我所做的是: 要隐藏进程,请执行以下操作: 1) 在正在运行的进程中查找进程名称 2) 将MainWindowHandle添加到容器(本例中为字典),这对于以后取消隐藏该进程是必要的 3) 使用ShowWindow API函数隐藏进程 要取消隐藏进程,请执行以下操作: 1) 在正在运行的进程中查找进程名称 2) 从容器中检索指定进程的已保存MainWindowHandle 3) 使用ShowWindow API函数取消隐藏进程 为什么我要使用字典来

很久以前,我编写了一段代码来隐藏/恢复流程窗口,我所做的是:

要隐藏进程,请执行以下操作:

1) 在正在运行的进程中查找进程名称

2) 将MainWindowHandle添加到容器(本例中为字典),这对于以后取消隐藏该进程是必要的

3) 使用ShowWindow API函数隐藏进程

要取消隐藏进程,请执行以下操作:

1) 在正在运行的进程中查找进程名称

2) 从容器中检索指定进程的已保存MainWindowHandle

3) 使用ShowWindow API函数取消隐藏进程

为什么我要使用字典来取消隐藏进程?因为隐藏进程的
MainWindowHandle
值为零
0
,所以这是我找到的唯一方法,可以在
ShowWindow
函数中检索适当的句柄来还原进程

但是我真的不想依赖于在隐藏进程之前保存所需的HWND
Hide
方法,我想通过知道如何在VB.NETC#中仅通过指定进程名称(例如:cmd.exe执行取消隐藏操作来改进这一切如果不在
MainWindowHandle
之前保存,可以这样做吗

我展示代码(在VB.NET中),让您了解我对HideProcess方法所做的工作:

但请注意,此代码与问题并不完全相关,我的问题是如何仅通过指定进程名称来取消隐藏隐藏的进程,以避免下面编写的代码需要检索保存的句柄来取消隐藏进程

”隐藏取消隐藏进程
'
'用法示例:
'
'HideProcess(Process.GetCurrentProcess().MainModule.ModuleName)
'HideProcess(“notepad.exe”,递归性:=False)
'HideProcess(“记事本”,递归性:=True)
'
'UnhideProcess(Process.GetCurrentProcess().MainModule.ModuleName)
'UnhideProcess(“notepad.exe”,递归性:=False)
'UnhideProcess(“记事本”,递归性:=True)
Private ProcessHandles作为新字典(字符串的,IntPtr)
私有共享函数ShowWindow(ByVal hwnd作为IntPtr,ByVal nCmdShow作为Integer)作为Integer
端函数
私有子HideProcess(ByVal ProcessName作为字符串,可选ByVal递归性作为布尔值=False)
如果ProcessName.EndsWith(“.exe”,StringComparison.OrdinalIgnoreCase),则
ProcessName=ProcessName.Remove(ProcessName.Length-.exe.Length)
如果结束
Dim Processes()为Process=Process.getProcessByName(ProcessName)
选择案例递归性
情况属实
对于流程中的每个p As流程
Add(String.Format(“{0};{1}”),ProcessName,CStr(p.Handle)),p.MainWindowHandle)
ShowWindow(p.MainWindowHandle,0)
下一个p
其他情况
如果不是(processs.Count=0)也不是(processs(0).MainWindowHandle=0),则
作为过程的尺寸p=过程(0)
Add(String.Format(“{0};{1}”),ProcessName,CStr(p.Handle)),p.MainWindowHandle)
ShowWindow(p.MainWindowHandle,0)
如果结束
结束选择
端接头
私有子UnhideProcess(ByVal ProcessName作为字符串,可选ByVal递归性作为布尔值=False)
如果ProcessName.EndsWith(“.exe”,StringComparison.OrdinalIgnoreCase),则
ProcessName=ProcessName.Remove(ProcessName.Length-.exe.Length)
如果结束
Dim TempHandles作为新字典(字符串,IntPtr)
在ProcessHandles中将每个句柄作为KeyValuePair(字符串的IntPtr)使用
添加(Handle.Key、Handle.Value)
下把手
在TempHandles中将每个句柄作为KeyValuePair(字符串的IntPtr)使用
如果Handle.Key.ToLower.Contains(ProcessName.ToLower)则
ShowWindow(Handle.Value,9)
ProcessHandles.Remove(Handle.Key)
如果是递归的话
退出
如果结束
如果结束
下把手
端接头
代码:

using System.Diagnostics;
using System.Runtime.InteropServices;

[DllImport("User32")]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

[DllImport("User32.dll")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string strClassName, string strWindowName);

[DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);

private const int SW_RESTORE = 9;

private void UnhideProcess(string processName) //Unhide Process
{
    IntPtr handle = IntPtr.Zero;
    int prcsId = 0;

    //an array of all processes with name "processName"
    Process[] localAll = Process.GetProcessesByName(processName);

    //check all open windows (not only the process we are looking) begining from the
    //child of the desktop, handle = IntPtr.Zero initialy.
    do
    {
        //get child handle of window who's handle is "handle".
        handle = FindWindowEx(IntPtr.Zero, handle, null, null);

        GetWindowThreadProcessId(handle, out prcsId); //get ProcessId from "handle"

        //if it matches what we are looking
        if (prcsId == localAll[0].Id)
        {
            ShowWindow(handle, SW_RESTORE); //Show Window

            return;
        }
    } while (handle != IntPtr.Zero);
}
如果有更多具有相同名称的实例,则可以使用变量,例如count和increment 它在if语句中出现

FindWindowEx()和Process.MainWindowHandle()之间的区别可能在于每个函数的位置
正在寻找手柄。FindWindowEx()与MainWindowHandle不同,它到处都在查找。另外,进程句柄被称为句柄,窗口句柄被称为HWND,这是我为vb.net编写的解决方案,这要归功于@γηρρσκωδ′αεπλλλδασκμε

<System.Runtime.InteropServices.DllImport("User32")>
Private Shared Function ShowWindow(
         ByVal hwnd As IntPtr,
         ByVal nCmdShow As Integer
) As Integer
End Function

<System.Runtime.InteropServices.DllImport("User32.dll")>
Private Shared Function FindWindowEx(
        ByVal hwndParent As IntPtr,
        ByVal hwndChildAfter As IntPtr,
        ByVal strClassName As String,
        ByVal strWindowName As String
) As IntPtr
End Function

<System.Runtime.InteropServices.DllImport("user32.dll")>
Private Shared Function GetWindowThreadProcessId(
        ByVal hWnd As IntPtr,
        ByRef ProcessId As Integer
) As Integer
End Function

Public Enum WindowState As Integer

    ''' <summary>
    ''' Hides the window and activates another window.
    ''' </summary>
    Hide = 0I

    ''' <summary>
    ''' Activates and displays a window. 
    ''' If the window is minimized or maximized, the system restores it to its original size and position.
    ''' An application should specify this flag when displaying the window for the first time.
    ''' </summary>
    Normal = 1I

    ''' <summary>
    ''' Activates the window and displays it as a minimized window.
    ''' </summary>
    ShowMinimized = 2I

    ''' <summary>
    ''' Maximizes the specified window.
    ''' </summary>
    Maximize = 3I

    ''' <summary>
    ''' Activates the window and displays it as a maximized window.
    ''' </summary>      
    ShowMaximized = Maximize

    ''' <summary>
    ''' Displays a window in its most recent size and position. 
    ''' This value is similar to <see cref="WindowVisibility.Normal"/>, except the window is not actived.
    ''' </summary>
    ShowNoActivate = 4I

    ''' <summary>
    ''' Activates the window and displays it in its current size and position.
    ''' </summary>
    Show = 5I

    ''' <summary>
    ''' Minimizes the specified window and activates the next top-level window in the Z order.
    ''' </summary>
    Minimize = 6I

    ''' <summary>
    ''' Displays the window as a minimized window. 
    ''' This value is similar to <see cref="WindowVisibility.ShowMinimized"/>, except the window is not activated.
    ''' </summary>
    ShowMinNoActive = 7I

    ''' <summary>
    ''' Displays the window in its current size and position.
    ''' This value is similar to <see cref="WindowVisibility.Show"/>, except the window is not activated.
    ''' </summary>
    ShowNA = 8I

    ''' <summary>
    ''' Activates and displays the window. 
    ''' If the window is minimized or maximized, the system restores it to its original size and position.
    ''' An application should specify this flag when restoring a minimized window.
    ''' </summary>
    Restore = 9I

    ''' <summary>
    ''' Sets the show state based on the SW_* value specified in the STARTUPINFO structure 
    ''' passed to the CreateProcess function by the program that started the application.
    ''' </summary>
    ShowDefault = 10I

    ''' <summary>
    ''' <b>Windows 2000/XP:</b> 
    ''' Minimizes a window, even if the thread that owns the window is not responding. 
    ''' This flag should only be used when minimizing windows from a different thread.
    ''' </summary>
    ForceMinimize = 11I

End Enum

Private Sub SetWindowState(ByVal ProcessName As String,
                           ByVal WindowState As WindowState,
                           Optional ByVal Recursivity As Boolean = False)

    If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
        ProcessName = ProcessName.Remove(ProcessName.Length - ".exe".Length)
    End If

    Dim pHandle As IntPtr = IntPtr.Zero
    Dim pID As Integer = 0I

    Dim Processes As Process() = Process.GetProcessesByName(ProcessName)

    ' If any process matching the name is found then...
    If Processes.Count = 0 Then
        Exit Sub
    End If

    For Each p As Process In Processes

        Do Until pID = p.Id ' Check all windows.

            ' Get child handle of window who's handle is "pHandle".
            pHandle = FindWindowEx(IntPtr.Zero, pHandle, Nothing, Nothing)

            ' Get ProcessId from "pHandle".
            GetWindowThreadProcessId(pHandle, pID)

            ' If the ProcessId matches the "pID" then...
            If pID = p.Id Then

                ShowWindow(pHandle, WindowState)

                If Not Recursivity Then
                    Exit For
                End If

            End If

        Loop

    Next p

End Sub

私有共享函数显示窗口(
ByVal hwnd作为IntPtr,
ByVal nCmdShow为整数
)作为整数
端函数
私有共享函数FindWindowEx(
ByVal hwndParent作为IntPtr,
ByVal hwndChildAfter As IntPtr,
ByVal strClassName作为字符串,
ByVal strWindowName作为字符串
)As IntPtr
端函数
私有共享函数GetWindowThreadProcessId(
ByVal hWnd作为IntPtr,
ByRef ProcessId为整数
)作为整数
端函数
公共枚举WindowsState为整数
''' 
''隐藏窗口并激活另一个窗口。
''' 
隐藏=0I
''' 
''激活并显示一个窗口。
''如果窗口最小化或最大化,系统会将其恢复到其原始大小和位置。
''应用程序在第一次显示窗口时应指定此标志。
''' 
正常值=1I
''' 
''激活窗口并将其显示为最小化窗口。
''' 
ShowMinimized=2I
''' 
''最大化指定的窗口。
''' 
最大化=3I
''' 
''激活窗口并将其显示为最大化窗口。
'''       
显示最大化=最大化
''' 
''以最新的大小和位置显示窗口。
''此值与类似,只是窗口未激活。
''' 
ShowNoActivate=4I
''' 
''激活窗口并在中显示它
<System.Runtime.InteropServices.DllImport("User32")>
Private Shared Function ShowWindow(
         ByVal hwnd As IntPtr,
         ByVal nCmdShow As Integer
) As Integer
End Function

<System.Runtime.InteropServices.DllImport("User32.dll")>
Private Shared Function FindWindowEx(
        ByVal hwndParent As IntPtr,
        ByVal hwndChildAfter As IntPtr,
        ByVal strClassName As String,
        ByVal strWindowName As String
) As IntPtr
End Function

<System.Runtime.InteropServices.DllImport("user32.dll")>
Private Shared Function GetWindowThreadProcessId(
        ByVal hWnd As IntPtr,
        ByRef ProcessId As Integer
) As Integer
End Function

Public Enum WindowState As Integer

    ''' <summary>
    ''' Hides the window and activates another window.
    ''' </summary>
    Hide = 0I

    ''' <summary>
    ''' Activates and displays a window. 
    ''' If the window is minimized or maximized, the system restores it to its original size and position.
    ''' An application should specify this flag when displaying the window for the first time.
    ''' </summary>
    Normal = 1I

    ''' <summary>
    ''' Activates the window and displays it as a minimized window.
    ''' </summary>
    ShowMinimized = 2I

    ''' <summary>
    ''' Maximizes the specified window.
    ''' </summary>
    Maximize = 3I

    ''' <summary>
    ''' Activates the window and displays it as a maximized window.
    ''' </summary>      
    ShowMaximized = Maximize

    ''' <summary>
    ''' Displays a window in its most recent size and position. 
    ''' This value is similar to <see cref="WindowVisibility.Normal"/>, except the window is not actived.
    ''' </summary>
    ShowNoActivate = 4I

    ''' <summary>
    ''' Activates the window and displays it in its current size and position.
    ''' </summary>
    Show = 5I

    ''' <summary>
    ''' Minimizes the specified window and activates the next top-level window in the Z order.
    ''' </summary>
    Minimize = 6I

    ''' <summary>
    ''' Displays the window as a minimized window. 
    ''' This value is similar to <see cref="WindowVisibility.ShowMinimized"/>, except the window is not activated.
    ''' </summary>
    ShowMinNoActive = 7I

    ''' <summary>
    ''' Displays the window in its current size and position.
    ''' This value is similar to <see cref="WindowVisibility.Show"/>, except the window is not activated.
    ''' </summary>
    ShowNA = 8I

    ''' <summary>
    ''' Activates and displays the window. 
    ''' If the window is minimized or maximized, the system restores it to its original size and position.
    ''' An application should specify this flag when restoring a minimized window.
    ''' </summary>
    Restore = 9I

    ''' <summary>
    ''' Sets the show state based on the SW_* value specified in the STARTUPINFO structure 
    ''' passed to the CreateProcess function by the program that started the application.
    ''' </summary>
    ShowDefault = 10I

    ''' <summary>
    ''' <b>Windows 2000/XP:</b> 
    ''' Minimizes a window, even if the thread that owns the window is not responding. 
    ''' This flag should only be used when minimizing windows from a different thread.
    ''' </summary>
    ForceMinimize = 11I

End Enum

Private Sub SetWindowState(ByVal ProcessName As String,
                           ByVal WindowState As WindowState,
                           Optional ByVal Recursivity As Boolean = False)

    If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
        ProcessName = ProcessName.Remove(ProcessName.Length - ".exe".Length)
    End If

    Dim pHandle As IntPtr = IntPtr.Zero
    Dim pID As Integer = 0I

    Dim Processes As Process() = Process.GetProcessesByName(ProcessName)

    ' If any process matching the name is found then...
    If Processes.Count = 0 Then
        Exit Sub
    End If

    For Each p As Process In Processes

        Do Until pID = p.Id ' Check all windows.

            ' Get child handle of window who's handle is "pHandle".
            pHandle = FindWindowEx(IntPtr.Zero, pHandle, Nothing, Nothing)

            ' Get ProcessId from "pHandle".
            GetWindowThreadProcessId(pHandle, pID)

            ' If the ProcessId matches the "pID" then...
            If pID = p.Id Then

                ShowWindow(pHandle, WindowState)

                If Not Recursivity Then
                    Exit For
                End If

            End If

        Loop

    Next p

End Sub