隐藏显示窗口

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 教程 目录

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

在android中显示隐藏片段

仅在一个片段中隐藏状态栏并在其他片段中显示

显示/隐藏片段而不是替换

JavaFX窗口拖动

Android 片段隐藏显示 OnHide/OnShow?

隐藏/显示不同片段的操作栏选项菜单项