Is there a way to get a bi-dimensional array containing pairs of a windows title and handle for all existing windows?
I think this would require to get the titles of all opened windows first and then retrieve their handles and build the bi-dimensional array from two lists, but I’m not completely sure how to do that.
I also know it involves the Process.GetProcesses() method, but I am not entirely sure how to do it.
Look at the http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx and read about the MainWindowTitle and MainWindowHandle properties.
The GetProcesses method returns you a list of exactly such Process objects. Thus, in verbose form:
and this is it. Now if you want to get N-th process information:
As you see, there’s a problem that the array has only ONE data type. That means that keeping a string and an IntPtr (the handle) forces you to find a common super type, which is .. the most general ‘object’ type. Thus, you have to cast when you are reading the data, because only you know that at [0] the object is actually a string.
Consider using a Dictionary class. That way you will have your data nicely typed – but you will lose the “order” of the processes. They will be sorted randomly. But I dont think that at this point you needed the order anyways? See the code here:
and this is it. Now if you want to read the process information:
Note that with Dictionary the access to N-th element is a little difficult, but usually you do not need that anyways. If you need it – you can add LINQ to the toolset:
so, not that bad. As we have the LINQ in hand, we can write the initial dictionary-creating code even shorter:
Ok. So lets fix one thing – I’ve fooled you with the dictionary a little. The Dictio has a constraint: the keys must be unique. And the window titles may be any! They may repeat and surely they will. Thus, you have to either SWAP the key with the value and form a Dictionary – as the handles should never repeat – or else you may use a LINQ .ToLookup method instead of .ToDictionary. The Lookup holds multiple values for a single key, so for an “Internet explorer” window title it will be capable of holding a list of 15 handles, etc.
Have fun.