隐藏显示窗口

Posted VB.Net

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了隐藏显示窗口相关的知识,希望对你有一定的参考价值。

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。

使用系统的API函数ShowWindow可以隐藏和显示其它程序的窗口。
vb.net中的声明如下:

Declare Function ShowWindow Lib "user32" Alias "ShowWindow" (ByVal hwnd As IntPtr, ByVal nCmdShow As Integer) As Integer

参数hwnd是窗口的句柄;

参数nCmdShow是指定窗口如何显示,用来隐藏和显示的常数:

SW_HIDE= 0

SW_SHOW= 5
隐藏窗口代码:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim result As Integer
        For Each pro As Process In Process.GetProcesses
            Try
                If pro.ProcessName = "notepad" Then
                    Dim mainWin As IntPtr = pro.MainWindowHandle
                    result = ShowWindow(mainWin, SW_HIDE)
                End If
            Catch ex As Exception

            End Try
        Next
    End Sub

显示窗口代码:

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim result As Integer
        For Each pro As Process In Process.GetProcesses
            Try
                If pro.ProcessName = "notepad" Then
                    Dim mainWin As IntPtr = pro.MainWindowHandle
                    result = ShowWindow(mainWin, SW_SHOW)
                End If
            Catch ex As Exception

            End Try
        Next
    End Sub

如果用了以上代码,会发现,隐藏窗口没问题,但是却不能显示窗口。

添加监视,可以发现显示窗口代码中,mainWin为0,这是因为窗口隐藏后不会有窗口句柄。

只需要在隐藏时把窗口的句柄保存下来就可以隐藏后又显示出来。

修改后的代码如下:

    Declare Function ShowWindow Lib "user32" Alias "ShowWindow" (ByVal hwnd As IntPtr, ByVal nCmdShow As Integer) As Integer
    Public Const SW_HIDE As Integer = 0
    Public Const SW_SHOW As Integer = 5

    Dim hwnd As IntPtr = IntPtr.Zero

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim result As Integer
        For Each pro As Process In Process.GetProcesses
            Try
                If pro.ProcessName = "notepad" Then
                    hwnd = pro.MainWindowHandle
                    result = ShowWindow(hwnd, SW_HIDE)
                    Exit For
                End If
            Catch ex As Exception

            End Try
        Next
    End Sub


    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim result As Integer
        Try
            result = ShowWindow(hwnd, SW_SHOW)
        Catch ex As Exception

        End Try
    End Sub

在网上找到的很多代码,只会告诉使用ShowWindow可以隐藏显示窗口,但是并没有告诉需要保存原窗口的句柄。

由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看 vb.net 教程 目录

以上是关于隐藏显示窗口的主要内容,如果未能解决你的问题,请参考以下文章

易语言隐藏显示 怎么显示?版本 2 窗口隐藏显示 (取句柄 (“DNF.EXE”, , “地下城与勇士”))

显示警报后隐藏模式弹出窗口

如何在pyqt5中显示隐藏窗口?

隐藏 qdialog 并显示主窗口

如何显示使用“撤回”方法隐藏的窗口?

隐藏显示窗口