我的WPF元素是在屏幕上可见还是被任何应用程序的另一个窗口隐藏

时间:2015-02-18 12:52:17

标签: wpf winapi

如何知道我的WPF应用程序中的某个元素是否被任何应用程序的另一个窗口隐藏

以下是我如何获取有关在屏幕上打开窗口的信息的示例。例如:我的申请是否在最佳状态。

(我在http://www.codeproject.com/Articles/19529/Is-My-Application-on-Top中学到的基本代码)

 Declare Function GetTopWindow Lib "user32" Alias "GetTopWindow" (ByVal hwnd As Integer) As Integer
    Declare Function GetNextWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As Integer, ByVal wFlag As Integer) As Integer
    Declare Function IsWindowVisible Lib "user32" Alias "IsWindowVisible" (ByVal hwnd As Integer) As Boolean
    Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Integer, ByVal lpString As String, ByVal cch As Integer) As Integer
    Declare Function GetWindowRect Lib "user32" Alias "GetWindowRect" (ByVal hwnd As IntPtr, ByRef pwi As Rect) As Boolean

    Function IsOnTop(ByVal hwnd As Integer) As Boolean
        Dim i As Integer = GetTopWindow(0)
        Dim x As Integer = 1
        Dim s As String

        Do
            i = GetNextWindow(i, 2)  ' Find next window in Z-order
            If i = hwnd Then
                Exit Do
            Else
                If i = 0 Then           ' Never find any window match the input handle
                    Return False
                End If
            End If

            If IsWindowVisible(i) = True Then
                s = Space(256)
                If GetWindowText(i, s, 255) <> 0 Then
                    ' Very important to prevent confusing of BalloonTips and ContextMenuStrips
                    x += 1
                End If
            End If
        Loop

        ' x is Z-order number

        If x = 1 Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetWindowText(ByVal hWnd As IntPtr) As String
        Dim s = Space(256)
        GetWindowText(hWnd, s, 255)
        Return s.ToString()
    End Function

    Function GetRectWindow(hwnd As Integer) As Rect
        Dim rc As Rect
        GetWindowRect(hwnd, rc)
        Return rc
    End Function

我需要知道宽度和宽度。其他窗户的高度。如果没有这些数据,我仍然无法知道一个元素是否隐藏给用户。例如,在我的应用程序中,我有一个包含两个DataGrid的窗口,其中一个可能被其他应用程序隐藏。

问题是,虽然GetRectWindow方法返回此数据,但是,例如,它在Width属性= 4.09332988076806E-311中给出它应该是350.据我所知,它使用Twips单位。我将它转换为像素单位,但我得到的结果是无限数字-0。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

  • 计算视觉相对于根视觉的边界(Visual.TransformToAncestor)
  • 计算视觉相对于屏幕的边界(原生GetWindowRect&amp; GetClientRect)
  • 枚举所有顶级窗口(原生EnumWindows)
  • 检查每个窗口是否可见,以及它是否与视觉边界重叠(原生GetWindowRect)