Edgars Šturms Edgars Šturms - 2 months ago 16x
C# Question

ManagementObjectSearcher does not work within global hook

When I try to get all running processes inside mouse event handler it throws an exception.

First I though that the problem persists because I put

keyword before mouse event handler, but it was not the case, as the exception is thrown also for non-asynchronous methods.

I'm using MouseKeyHook library.

Exception message:

Additional information: Transition into COM context 0x1ac936a0 for
this RuntimeCallableWrapper failed with the following error: An
outgoing call cannot be made since the application is dispatching an
input-synchronous call. (Exception from HRESULT: 0x8001010D

Event handler from which I'm getting all processes:

private async void MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
List<ProcessInfo> allRunningProcesses = Logic.GetAllProcesses();
// ...

Get all processes by using

public static List<ProcessInfo> GetAllProcesses()
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get()) // EXCEPTION THROWN!
// ...

As you can see the exception is thrown when calling
Note: This method works without any issues if used outside the mouse event handler (

I will appreciate any helpful advises and provide additional information if needed, thanks.


As it turns out, COM requires you to run your code on STA if there is MTA involved and you are using the ManagementObjectSearcher methods within SendMessage().
So, what I needed to do is to run my code on differet thread and set SetApartmentState to ApartmentState.STA.

List<ProcessInfo> allRunningProcesses = null;

Thread threadProc = new Thread(() =>
    allRunningProcesses = Logic.GetAllProcesses();


Useful links:

msdn- Understanding and Using COM Threading Models
stackoverflow- How to run something in the STA thread