When using the following class in a console application and if there is at least one instance of Notepad, it GetWindowThreadProcessIdcorrectly returns a non-zero thread identifier. However, if the same code is included in the Windows service, it GetWindowThreadProcessIdalways returns 0and no exceptions are thrown. Changing the user launched by the service to the same as the one that launches the console application has not changed the result. What makes GetWindowThreadProcessIdreturn 0, even if it is equipped with a valid hwnd? And why does it work differently in console application and service? Note. I am running a 32-bit version of Windows 7 and targeting to .NET 3.5.
public class TestClass
{
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
public void AttachToNotepad()
{
var processesToAttachTo = Process.GetProcessesByName("Notepad")
foreach (var process in processesToAttachTo)
{
var threadID = GetWindowThreadProcessId(process.MainWindowHandle,
IntPtr.Zero);
....
}
}
}
Console Code:
class Program
{
static void Main(string[] args)
{
var testClass = new TestClass();
testClass.AttachToNotepad();
}
}
Service Code:
public class TestService : ServiceBase
{
private TestClass testClass = new TestClass();
static void Main()
{
ServiceBase.Run(new TestService());
}
protected override void OnStart(string[] args)
{
testClass.AttachToNotepad();
base.OnStart(args);
}
protected override void OnStop()
{
...
}
}