问题
i saw a method called Control.FromHandle wich (should) give you the access to it. Now, i wanted to try it using this code
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern bool ReleaseDC(IntPtr hwnd, IntPtr hdc);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
IntPtr ptr = FindWindowByCaption(IntPtr.Zero, "Download");
Control f = Control.FromHandle(ptr);
f.Text = "Something";
}
but it won't, obviously, work. I checked personally that the handle is correct... but the method returns a null control. Any explaining?
回答1:
This method only works if the handle you pass in actually is a Control
in your application.
回答2:
In your particular case, since you just want to set the text, call SetWindowText from user32.dll
回答3:
For anyone else googling that found this answer and wondered why this behavior is the case this post http://www.codeguru.com/forum/showthread.php?t=443191 is particularly enlightening, specifically the last post from 'MadHatter':
well just from looking over what goes on in Control.FromHandle in reflector, it looks like as windows are added to the .net world, it stores a table of what handles it has loaded, the problem comes when you pass in a handle that is not listed in its tables. There may be some hack that would allow you to register the window through all the subsystems that are used when creating windows from within the .net app, but it would probably be better / more consistent to wrap whatever functionality you need directly through the windows api then try to hack in Control.FromHandle to allow you to access / manipulate the window of some other process.
Reading more into your question it seems like you are trying to do some automation or at very least manipulate the window in some way. Might I recommend looking at the Managed Windows API project on SourceForge. It is pretty well written and we've used it for the purposes you are describing.
来源:https://stackoverflow.com/questions/2303812/how-to-use-control-fromhandle