2016-07-22 123 views
0

我想在C#中使用win10這個帖子來處理這個問題。SendInput to minimized window while you're working on other windows'GetProcessIdOfThread'總是返回零

我跟着最好的答案做,我覺得這並不像「GetProcessIdOfThread」工作始終返回0

下面是代碼:

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; 
    } 
} 

難道我誤解了什麼? 謝謝!

+0

如果函數成功,則返回值是與指定線程關聯的進程的進程標識符。如果函數失敗,返回值爲零。要獲得擴展的錯誤信息,請調用'GetLastError'。 – Marusyk

+0

但是不要直接調用'GetLastError' - 使用['Marshal.GetLastWin32Error'](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getlastwin32error(v = vs。 100).aspx)並閱讀其中的文檔以獲取其他要求。 –

回答

1

MSDN約GetProcessIdOfThread

檢索與指定 線程相關聯的進程的進程標識符。

您正在將一個窗口句柄(HWND)而不是線程的句柄傳遞給該函數。這就是爲什麼它返回零。您需要先處理線程,或者您可以直接調用GetWindowThreadProcessId函數從HWND獲取進程ID。

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 
} 
...