Solved

How to use Get(Next)Window and GetWindowText?

Posted on 1997-07-25
13
673 Views
Last Modified: 2010-05-18
Hi

I've tried to use the API functions GetWindow/GetNextWindow in combination with GetWindowText. Seamingly I can't do to much wrong with these functions, but I also can't get them working.

The purpose is to make a listbox that contains the names of all active applications (helping the user at start of the Setup of my program to close the apps that are currently running). Probably I can't get ALL the active applications this way (it would be nice to get the hidden applications as well. All the links listed in the Ctrl-Alt-Del window are enough).
If you know a way to do about the same thing as Ctrl-Alt-Del does to get the running apps in the window, please let me know. If I need something else then the above named API's, let me know as well, but please explain also how I can get them (the above named) working.

Thanks a lot in advance
0
Comment
Question by:braaksma
  • 7
  • 6
13 Comments
 
LVL 5

Expert Comment

by:y96andha
Comment Utility
This is a small sample on how you can use the APIs you mentioned to get a list of all windows, both hidden and visible.

Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Const GW_HWNDFIRST = 0
Private Const GW_HWNDNEXT = 2

Private Sub Command1_Click()
    Cls
    Dim hwnd As Variant
    Dim txt As String

    'get first window
    hwnd = GetWindow(Form1.hwnd, GW_HWNDFIRST)
    Do
    txt = String(256, 0)
    GetWindowText hwnd, txt, 256
    Print Left(txt, InStr(txt, Chr(0)) - 1)
    hwnd = GetWindow(hwnd, GW_HWNDNEXT)
    Loop Until hwnd = 0
End Sub


0
 

Author Comment

by:braaksma
Comment Utility
Yes, I've tried this and it works, but in the list I get there are a few too much applications. In the Ctrl-Alt-Del window you only see the ones connected to a real application. When I only ask for the non-hidden windows, I can get them except for the ones in the SysTray (like QuickRes or MagnaRam). When I call everything I get a list with numerous windows I've never heard of. I can trace them back, but the end-user won't be able to do that.
It has to be the same as in Ctrl-Alt-Del, but I don't know how Windows filters the windows when you press Ctrl-Alt-Del. I need the same.
I've tried to do it with EnumWindows, but maybe my declaration is not good: As soon as the program gets into the EnumWindowsProc function I have, even before any statement gets executed, an error 91 (Object variable or With block not set).
EnumWindows is in the Win32 API-reference helpfile I have, but not in the API-loader which comes with VB 5.0. Maybe I've translated the C-declaration the wrong way. Besides, since I can't get this function running, I'm not sure if it works any better then Get(Next)Window, in combination with IsWindowVisible.

Here is the code I've tried:
In the last line of ErrHandling I placed and Cstr(Hwnd) as well. In that case I got the VB-message of error 91. When I left is out, I got my own message (?). Besides, I've never managed to have GetLastError return something else then zero, even when it should. In C++ it does, but I need to use VB5 (sometimes unfortunately).
These first four lines are in the frm-file, the rest in a Module

Private Sub cmdGetWindows_Click()

lstWindows.Clear            'Listbox on frmGetWindow
EnumWindows AddressOf EnumWindowsProc, lstWindows

End Sub


'From here it's in the Module

Declare Function GetWindowText Lib "user32" Alias _
"GetWindowTextA" (ByVal Hwnd As Long, ByVal lpString As String, _
ByVal cch As Long) As Long

Declare Function IsWindowVisible Lib "user32" (ByVal Hwnd As _
Long) As Long

Declare Function EnumWindows Lib "user32" (ByVal _ lpEnumWindowsProc As Long, ByVal LParam As Any) As Long

Declare Function GetLastError Lib "kernel32" () As Long

Function EnumWindowsProc(Hwnd As Long, LParam As ListBox) As Long
  'CALLBACK function for EnumWindows
  Dim Ret As Long
  Dim LenTxt As Long
  Dim WinText As String
  On Error GoTo ErrHandling
 
  WinText = Space$(255)
  If Hwnd = 0 Then
    'Not a real window
    EnumWindowsProc = 1
    Exit Function
  End If
 
  If IsWindowVisible(Hwnd) <> False Then
    LenTxt = GetWindowText(Hwnd, WinText, 255)
    If GetLastError() <> 0 Then
      MsgBox "Error!"
      EnumWindowsProc = False
      Exit Function
    End If
    If LenTxt = 0 Then
      MsgBox "No windowtext"
      EnumWindowsProc = 1
      Exit Function
    End If
    LParam.AddItem Left$(WinText, LenTxt)
  End If
  EnumWindowsProc = 1
 
ErrHandling:
  MsgBox "An error occurred: " & CStr(Err) & "  " & _  
          Err.Description & ", source = " & Err.Source
 
End Function

0
 
LVL 5

Expert Comment

by:y96andha
Comment Utility
Filtering out child windows and hidden windows will reduce the list:

Private Const GW_HWNDFIRST = 0
Private Const GW_HWNDNEXT = 2
Private Const GWL_HWNDPARENT = (-8)

Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As Long) As Long


Private Sub Command2_Click()
    Cls
    Dim hwnd As Variant
    Dim txt As String
    'get first window
    hwnd = GetWindow(Form1.hwnd, GW_HWNDFIRST)
    Do
        txt = String(256, 0)
        GetWindowText hwnd, txt, 256
        If (GetWindowLong(hwnd, GWL_HWNDPARENT) = 0) And (IsWindowVisible(hwnd) <> 0) Then
            Print Left(txt, InStr(txt, Chr(0)) - 1)
        End If
        hwnd = GetWindow(hwnd, GW_HWNDNEXT)
    Loop Until hwnd = 0
End Sub


About GetLastError:
I think that you should use Err.LastDLLError instead of GetLastError. VB uses so many system calls of its own, so the error code is reset before you have a chance to retrieve it with GetLastError. I haven't tested it though.


0
 

Author Comment

by:braaksma
Comment Utility
Thanks again for you efforts

One small (to my appl. a big) problem remains unsolved. I've tried exactly the same. It works fine, but it still doesn't come up with SysTray-windows. I know, they won't always be there, but I have to check it!
Those windows are hidden, so filtering them with IsWindowHidden does not work well enough since too many running applications get lost that way. Finally I DO need the same list as with Ctrl-Alt-Del. Filtering out Explorer is than but an easy task.
Do you know a way to use EnumWindows? Not that I'm so sure that it does what I want, but it is worth the try. Besides, if you know a way of just getting all the SysTray-windows it will be enough as well (I hope). I only miss some virusscanners than when I use it in combination with your above mentioned code.

Please, if you have any idea, y96andha, let me know

Thanks.
0
 

Author Comment

by:braaksma
Comment Utility
Erratum: In stead of IsWindowHidden, I ment (of course): IsWindowVisible.
0
 
LVL 5

Expert Comment

by:y96andha
Comment Utility
Will you be running this under Windows 95 or under Windows NT? I recently researched a way to find all running applications under Windows 95 and posted as an answer to an other question. In case this is something you could use..


0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:braaksma
Comment Utility
PLEASE, y96andha,

That's probably exactly the thing I need.
Please, post it as a comment, than I don't have to reject you first proposed answer (or ain't that the right way?). I hope it also captures the running applications as a hidden Sophos or McAfee, or SysTray applications like MagnaRam, QuickRes and so on.
Please post it here and I will soon look at it.

Thanks in advance,

ABEL
0
 

Author Comment

by:braaksma
Comment Utility
Sorry, I didn't mean to reject, but once clicked I couldnot (of course) disable the choice of the option button.

I forgot to tell you that I use usually Windows 95, and the recommended platform to my clients will also be Win95, but it would be nice to make it working for both platforms. (NT and 95)
Never mind that. I will be helped a lot with a Win95 procedure to do it. Maybe it helps me on my way to the same solution for WinNT, or I'll post the question again for that platform.

0
 
LVL 5

Accepted Solution

by:
y96andha earned 190 total points
Comment Utility
OK, here is the code. I think the most useful things are the exe name and the PID. The PID can be used with other calls to obtain more information about the process. But with applications such as Magnaram, you can't be sure there is a window title available to display.

Try this code, and comment on what kind of information you would need more.

Private Const TH32CS_SNAPPROCESS = &H2
Private Const MAX_PATH = 260
Private Type PROCESSENTRY32
 dwSize As Long
 cntUsage As Long
 th32ProcessID As Long
 th32DefaultHeapID As Long
 th32ModuleID As Long
 cntThreads As Long
 th32ParentProcessID As Long
 pcPriClassBase As Long
 dwFlags As Long
 szExeFile As String * MAX_PATH
End Type
Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, ByVal PID As Long) As Long
Private Declare Function Process32First Lib "kernel32" (ByVal hSnapShot As Long, pe32 As PROCESSENTRY32) As Long
Private Declare Function Process32Next Lib "kernel32" (ByVal hSnapShot As Long, pe32 As PROCESSENTRY32) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Sub Command1_Click()
 Cls
 Dim hSnapShot As Long: hSnapShot = 0
 Dim pe32 As PROCESSENTRY32

 hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
 If hSnapShot = -1 Then
 MsgBox "error"
 Exit Sub
 End If

 pe32.dwSize = Len(pe32)

 If Process32First(hSnapShot, pe32) Then
 Do
 Print pe32.szExeFile
 Loop While Process32Next(hSnapShot, pe32)
 Else
 MsgBox "process32first failed!"
 End If

 CloseHandle hSnapShot
End Sub
0
 

Author Comment

by:braaksma
Comment Utility
The function gets exactly the processes I wanted. Thanks.
But where to find all the toolhelp-functions? They are documented in win32 API helpfile, but not in its index/contents. I didn't find an overview, but with searching I do find something. Those functions aren't loaded in my API-viewer, which means that I'm not certain on how to declare most of them. The problem is: the ID's used with PROCESSENTRY32 can only be used with other Toolhelp functions (at least, that's what I read). I don't mind that, but how to find the Window-caption of the windows connected to a process? Or how to terminate the process? (I can manage as soon as I have the Window-handle, but how to retrieve them via this function?)
If you have an idea to do this, please tell me, I will increase the points a bit.
Or can I use the PIDs with TerminateProcess? Or something alike when I want to terminate the process?

Thanks in advance.
0
 
LVL 5

Expert Comment

by:y96andha
Comment Utility
You can use the PID in a call to OpenProcess, and then you recieve a process handle, which can be used with many functions.
0
 

Author Comment

by:braaksma
Comment Utility
Thanks for everything, I now know what I need to know to do what I want.
0
 
LVL 5

Expert Comment

by:y96andha
Comment Utility
Good Luck. You can comment here any time, and I'll look at it and try to help.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now