views:

211

answers:

2

Hello, there is a software which calls a method in my C# dll. In this dll method i need to have the window handle of the program/window which called my dll.

how to get this "calling window handle"?

Thanks!

+1  A: 

You can't: windows don't call methods, code calls methods.

You should ideally add a window handle parameter to your method. If that's absolutely impossible, you could use, say, the GetActiveWindow API function to get the window active on the current thread. This isn't guaranteed to work; maybe there are no windows open.

What do you need the window handle for?

Tim Robinson
to modify calling window, currently i use GetForegroundWindow but this is not really a good solution, so if user is changing window immediatelly i will have the wrong handle
Tobi
A: 

This can return the main window handle.

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle

As i know there is no way to get a concrete window because it's no more than Form object. But Form class has a property Handle. You can pass it as an argument to dll method calls.

ILya
thats the problem, I can't pass an argument to my dll method from source program. so i cant pass the handle. i need to find out the handle within my dll method
Tobi
Hmmm... Unfortunately the only way to solve a problem is to rewrite dll a little. I see no troubles here (if both dll and executable are written by you so you have sources) except the design of assembly will suffer...
ILya
yeah i implemeted the code you told me, this works. don't have sources of calling program, so i had to use GetCurrentProcess().MainWindowHandle. i think there is no other "clean" way?
Tobi
Yes, i can't imagine another solution. Another methods will be probabalistic so they're not a choice.
ILya