0

I am trying to do something like the question asked in this post in win10 with C# SendInput to minimized window while you're working on other windows.

I followed the best answer to do and I find it didn't work as "GetProcessIdOfThread" always return 0.

Here is the code:

public MainWindow()
{
    InitializeComponent();

    IntPtr NotepadHandle = FindWindow("Notepad", "Untitled - Notepad");
    if (NotepadHandle == IntPtr.Zero)
    {
        MessageBox.Show("Notepad is not running.");
        return;
    }
    uint noteid = GetProcessIdOfThread(NotepadHandle);
    uint selfid = GetCurrentThreadId();
    bool attach = AttachThreadInput(selfid, noteid, true);
    if (attach == false)
    {
        MessageBox.Show("attach fail");
        return;
    }
}

Did I misunderstood anything? Thank you!

Community
  • 1
  • 1
A kid
  • 81
  • 1
  • 8
  • If the function succeeds, the return value is the process identifier of the process associated with the specified thread. If the function fails, the return value is zero. To get extended error information, call `GetLastError`. – Roman Marusyk Jul 22 '16 at 06:31
  • But don't directly call `GetLastError` - use [`Marshal.GetLastWin32Error`](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getlastwin32error(v=vs.100).aspx) and read the documentation there for other requirements. – Damien_The_Unbeliever Jul 22 '16 at 06:36

1 Answers1

1

MSDN about GetProcessIdOfThread:

Retrieves the process identifier of the process associated with the specified thread.

You are passing handle of a window (HWND) instead of handle of a thread to the function. That's why it returns zero. You need to get handle of the thread first or you can directly call the GetWindowThreadProcessId function to get process id from HWND.

IntPtr notepadHandle = FindWindow("Notepad", "Untitled - Notepad");
if (notepadHandle == IntPtr.Zero) {
    MessageBox.Show("Notepad is not running.");
    return;
}
uint noteId;
uint threadId = GetWindowThreadProcessId(notepadHandle , out noteId);
if (threadId != 0) {
   // Succeed
}
...
Mehrzad Chehraz
  • 5,092
  • 2
  • 17
  • 28