3

How can I get the window class name of a certain process? I want to achieve this in c#.

I've tried the process class in c# but I can only get the window name of the process.

Thanks

Rotem
  • 21,452
  • 6
  • 62
  • 109
Jax
  • 977
  • 8
  • 22
  • 40

2 Answers2

7

I assume you mean you want to get the class name of the main window of a process.

To do this, you will need to get the handle to the main window using the MainWindowHandle of your Process object, and then use the following interop method to obtain the class name:

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

see pinvoke.net for sample code and MSDN for details on the function.

Rotem
  • 21,452
  • 6
  • 62
  • 109
  • 3
    MainWindowHandle is NOT guaranteed to be the "main window" of the application. It is usually only the first one created by that thread/message pump, which if that was a splash screen won't help you. The more reliable way especially since you're using the WinAPI anyway is to call FindWindow, passing it the name of the main window you're looking for. – KeithS Sep 11 '12 at 15:02
  • @KeithS That's a good idea provided you filter out windows that do not belong to the process. – Rotem Sep 11 '12 at 15:05
  • FindWindow returns the first match. If you already are concerned you're not checking the "main window", then using "Find Window" may be equally dubious if the application could have multiple windows with the same name. The more reliable way would be to iterate all of the windows of the application and check their names until you find the window or window(s) you want. – JamesHoux Jun 06 '23 at 01:43
1

You can also use the windows ui automation framework to achieve this without getting into pinvoke.

        int pidToSearch = 316;
        //Init a condition indicating that you want to search by process id.
        var condition = new PropertyCondition(AutomationElementIdentifiers.ProcessIdProperty, 
            pidToSearch);
        //Find the automation element matching the criteria
        AutomationElement element = AutomationElement.RootElement.FindFirst(
            TreeScope.Children, condition);

        //get the classname
        var className = element.Current.ClassName;
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85