473,789 Members | 2,876 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting Child Windows Using Process.GetProc ess

9 New Member
Hi everyone, I ran into a road block and cant seem to find anything on google.

I need to check all open windows/processes to see if certain software is running on the system. I was going to go the route of using core api from user32 for findwindow and so on, but then I came across using Process.Getproc esses and was very happy to see it was easy to get all processes and MainWindowTitle

Expand|Select|Wrap|Line Numbers
  1.         Dim poc() As Process = Process.GetProcesses()
  2.         For i As Integer = 0 To poc.Length - 1
  3.  
  4.             Try
  5.                 msgbox poc(i).mainwindowtitle
  6.  
  7.             Catch ex As Exception
  8.                 MsgBox(poc(i).ProcessName.ToString & " " & ex.Message)
  9.  
  10.             End Try
  11.  
  12.         Next
  13.  
  14.  
However... if the software has child windows or multiple windows open it does not get the title of these "sub windows". An example is an application that has 2 windows open from the same exe. Is there anyway to grab all window titles of a process using this same logic?
Nov 19 '08 #1
20 35546
nukefusion
221 Recognized Expert New Member
I'm not sure quite how to go about this using .NET's process class. You can however do this using P/Invoke. Code similar to the following should work:

Expand|Select|Wrap|Line Numbers
  1.            private delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
  2.  
  3.         [DllImport("user32.dll", SetLastError=true)]
  4.         private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
  5.  
  6.         [DllImport("USER32.DLL")]
  7.         private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
  8.  
  9.         [DllImport("USER32.DLL")]
  10.         private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
  11.  
  12.         [DllImport("USER32.DLL")]
  13.         private static extern int GetWindowTextLength(IntPtr hWnd);
  14.  
  15.         [DllImport("USER32.DLL")]
  16.         private static extern bool IsWindowVisible(IntPtr hWnd);
  17.  
  18.         [DllImport("USER32.DLL")]
  19.         private static extern IntPtr GetShellWindow();
  20.  
  21.         public IDictionary<IntPtr, string> GetOpenWindowsFromPID(int processID)
  22.         {
  23.             IntPtr hShellWindow = GetShellWindow();
  24.             Dictionary<IntPtr, string> dictWindows = new Dictionary<IntPtr, string>();
  25.  
  26.             EnumWindows(delegate(IntPtr hWnd, int lParam)
  27.                         {
  28.                             if (hWnd == hShellWindow) return true;
  29.                             if (!IsWindowVisible(hWnd)) return true;
  30.  
  31.                             int length = GetWindowTextLength(hWnd);
  32.                             if (length == 0) return true;
  33.  
  34.                             uint windowPid;
  35.                             GetWindowThreadProcessId(hWnd, out windowPid);                            
  36.                             if (windowPid != processID) return true;
  37.  
  38.                             StringBuilder stringBuilder = new StringBuilder(length);
  39.                             GetWindowText(hWnd, stringBuilder, length + 1);
  40.                             dictWindows.Add(hWnd, stringBuilder.ToString());
  41.                             return true;
  42.                         }, 0);
  43.  
  44.             return dictWindows;
  45.         }
You can then use the Process class to get the Process ID of the application you are targeting and call the above code to get a list of windows associated it, something along the lines of:

Expand|Select|Wrap|Line Numbers
  1.             Process[] processes = Process.GetProcessesByName("MyApp");
  2.             foreach (Process process in processes)
  3.             {
  4.                 IDictionary<IntPtr, string> windows = this.GetOpenWindowsFromPID(process.Id);
  5.                 foreach (KeyValuePair<IntPtr, string> kvp in windows)
  6.                 {
  7.                     // Do whatever you want here
  8.                 }
  9.             }
If you want to target hidden windows also you can modify the code slightly.
Hope it helps!
Nov 19 '08 #2
r035198x
13,262 MVP
If your goal is simply to determine if a particular program is running or not, then why do you need to find all windows? I'd expect that finding at least one window is sufficient.
I will add also that not finding a window is not sufficient to determine that the program is not running.
Nov 19 '08 #3
TomLasky
9 New Member
Do you have this in VB.NET form? I've been trying to do something similar using GetdesktopWindo w Hwnd and then using HWNDNEXT to loop through them all, the problem is I cant get the desktopwindow hwnd for some reason.

I visited the pinvoke web site and found a lot of the findwindow api's and such, maybe im going about it the wrong way?

Also, in response to the last post, yes I do need to know the programs thats are running but I also need to know if those programs are running other windows inside of their app. Problem is .NET's getprocesses just gets the mainwindowtitle and doesnt also provide childwindows... in my personal opinion it's a huge let down on the part of .NET. Everyone is always informing me to try and not use Win32API's directly because it's unmanaged and sloppy but in this instance im forced to use it. Anyway, any help would be appreciated, I'm on my 9th hour of google searching for a simple thing I could do in VB6 in 5 minutes.
Nov 19 '08 #4
Plater
7,872 Recognized Expert Expert
As pointed out, not finding the window doesn't mean the pogram is not running.
Shouldn't you be looking for a particular .exe or some other more discriminate property to see if it is running?
Nov 19 '08 #5
TomLasky
9 New Member
Here's what I'm doing:

I'm managing instant message windows or trying to anyway. I need to get all open windows for a specific program. I can find if a application is running, thats not the problem. The problem is finding all open windows for that app. As of right now I can only get the active top most window of that app and thats it, but theres 20 more windows from the same app that are not being found. I understand software can be hidden and just because an open window isn't there doesn;t mean it's not running, understood but it has no bearing on what im trying to accomplish.

Simply put... if you have 10 instant message windows open using AIM, I need to find the title text for all of those windows, not just the mainwindowtitle .

I've been messing around with old school enumwindows but its not working in .NET, most likely im declaring the wrong type. As of now I butchered the code so badly I'm starting from scratch. I liked the first answer posted, makes sense im lost with delegates and need help in the area of vb.net.
Nov 19 '08 #6
Plater
7,872 Recognized Expert Expert
Ahh ok, you aren't so much interested in the running process, as what the process is running (all its windows)

Yeah I am afraid you are stuck using win32_api for that unfortunatly
Nov 19 '08 #7
TomLasky
9 New Member
I forgot to thank everyone for their help, I'm just burnt out pounding my head against the wall over this so I apologize for my lack of understanding. But sincerely, thank you for your time in helping me with this, it's much appreciated.
Nov 19 '08 #8
TomLasky
9 New Member
Plater, I was hoping it wouldn't be so! haha... oh well...

Any advice on proper logic to use to go about doing this?

I was trying to start from getting the desktop hwnd and then going hwndnext, I dont know... I'm brainless right now.
Nov 19 '08 #9
nukefusion
221 Recognized Expert New Member
Hi Tom,

Sorry, VB.NET really isn't my strong point but still, I've had a go at translating the code sample for you. I hope you can get some use out of it.

Expand|Select|Wrap|Line Numbers
  1. Imports System.Runtime.InteropServices
  2. Imports System.Text
  3.  
  4. Public Class Test
  5.  
  6.     <DllImport("USER32.DLL")> _
  7.     Private Shared Function GetShellWindow() As IntPtr
  8.     End Function
  9.  
  10.     <DllImport("USER32.DLL")> _
  11.     Private Shared Function GetWindowText(ByVal hWnd As IntPtr, ByVal lpString As StringBuilder, ByVal nMaxCount As Integer) As Integer
  12.     End Function
  13.  
  14.     <DllImport("USER32.DLL")> _
  15.     Private Shared Function GetWindowTextLength(ByVal hWnd As IntPtr) As Integer
  16.     End Function
  17.  
  18.     <DllImport("user32.dll", SetLastError:=True)> _
  19.     Private Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, <Out()> ByRef lpdwProcessId As UInt32) As UInt32
  20.     End Function
  21.  
  22.     <DllImport("USER32.DLL")> _
  23.     Private Shared Function IsWindowVisible(ByVal hWnd As IntPtr) As Boolean
  24.     End Function
  25.  
  26.     Private Delegate Function EnumWindowsProc(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean
  27.  
  28.     <DllImport("USER32.DLL")> _
  29.     Private Shared Function EnumWindows(ByVal enumFunc As EnumWindowsProc, ByVal lParam As Integer) As Boolean
  30.     End Function
  31.  
  32.     Private hShellWindow As IntPtr = GetShellWindow()
  33.     Private dictWindows As New Dictionary(Of IntPtr, String)
  34.     Private currentProcessID As Integer
  35.  
  36.  
  37.     Public Function GetOpenWindowsFromPID(ByVal processID As Integer) As IDictionary(Of IntPtr, String)
  38.         dictWindows.Clear()
  39.         currentProcessID = processID
  40.         EnumWindows(AddressOf enumWindowsInternal, 0)
  41.         Return dictWindows
  42.     End Function
  43.  
  44.     Private Function enumWindowsInternal(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean
  45.         If (hWnd <> hShellWindow) Then
  46.             Dim windowPid As UInt32
  47.             If Not IsWindowVisible(hWnd) Then
  48.                 Return True
  49.             End If
  50.             Dim length As Integer = GetWindowTextLength(hWnd)
  51.             If (length = 0) Then
  52.                 Return True
  53.             End If
  54.             GetWindowThreadProcessId(hWnd, windowPid)
  55.             If (windowPid <> currentProcessID) Then
  56.                 Return True
  57.             End If
  58.             Dim stringBuilder As New StringBuilder(length)
  59.             GetWindowText(hWnd, stringBuilder, (length + 1))
  60.             dictWindows.Add(hWnd, stringBuilder.ToString)
  61.         End If
  62.         Return True
  63.     End Function
  64. End Class
You should be able to call it in a similar fashion, although I haven't tested this even though it does compile, i.e:

Expand|Select|Wrap|Line Numbers
  1. Dim processes As Process() = Process.GetProcessesByName("MyApp")
  2. For Each process As Process In processes
  3.     Dim windows As IDictionary(Of IntPtr, String) = GetOpenWindowsFromPID(process.Id)
  4.     For Each kvp As KeyValuePair(Of IntPtr, String) In windows
  5.                         ' Do whatever you want here 
  6.     Next
  7. Next
Nov 19 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2512
by: sshuangw | last post by:
Hello: I am encountering a very weird issue with MDI child, Overriden WndProc function and hidden form. Basically, the application has two forms, Form1(parent form), Form2(Child form), Form2's WndProc method is overriden, if the message is CLOSE message, just hide the form. I first initialize and show the child form, then close it by clicking the Close(X) button, the overriden WndProc method gets invoked, and the form is hidden. Then
4
2032
by: Bonj | last post by:
Further to my last post, I have managed to get a child window to display. But its messages are routed to the same WNDPROC that the main window's messages are routed to - what is the way of identifying from the lParam or wParam whether the message came from a child window or the parent? And what if the message uses some other data in the wParam or lParam? Is it better to use one wndproc for the parent window, and one wndproc for all child windows...
10
4030
by: Charles Law | last post by:
For some reason, when I click the X to close my MDI parent form, the action appears to be re-directed to one of the MDI child forms, and the parent remains open. I am then unable to close the application. What should happen, is that the main MDI form should close, taking the child forms with it. There is code to loop through the child forms, remove the controls on each of them, and then close the form, but this code should execute only...
0
1126
by: Darrell Wesley | last post by:
I have a program that some else wrote but it's my duty to try and maintain and in there are a couple of places where it makes a call to the System.Diagnostics.Process.GetProcess in order to find out if one or more programs are currently runnig and give the user a chance to exit out of them before killing them off. All of this works just fine as long a the logged in user has administrative rights to their PC but when the local IS...
7
5824
by: Sheikko | last post by:
Hi all, i have an application and i wan to call another program into it, like notepad, so when i minimize the notepad, or maximize, it must rest in my application. thank you
0
1856
by: dan.jakubiec | last post by:
I'm trying to write a Python app which accepts a socket connection and then spawns another Python process to handle it. I need it to run under both Linux and Windows. I have it working under Linux, but am having problems with the Windows implementation. My app uses the subprocess.Popen class to spawn the child process. The first problem I ran into was that Windows Python won't let you pass a socket object via the Popen stdin argument...
1
7469
by: ranju | last post by:
I am trying to spawn a process (say an exe file) with different user crendentials than that of the current user. 1) Called LogonUserEx() to logon the user and recieve a handle to the token that represents the logged-on user. 2) Called ImpersonateLoggedOnUSer() to let the calling thread impersonate the security context of logged on user. 3) Used CreateEnvironmentBlock() to get lpEnv
11
6034
by: geoffbache | last post by:
Hi, As part of my efforts to write a test tool that copes with GUIs nicely, I'm trying to establish how I can start a GUI process on Windows that will not bring up the window. So I try to hide the window as follows: info = subprocess.STARTUPINFO() info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.wShowWindow = subprocess.SW_HIDE
4
6194
by: Quill_Patricia | last post by:
I have a Python script which is used to load data into a database. Up to now this script has been run by customers from the Windows command prompt using "python edg_loader.pyc". Any error messages generated are written to a log file. A project team working in the same company as me here would like to use this loading utility. They write UI applications for Windows using Java. They were able to launch the Python script from within Java by...
0
9665
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10199
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6768
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5417
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3697
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.