开发者

How to use Control.FromHandle?

开发者 https://www.devze.com 2022-12-20 15:48 出处:网络
I saw a method called Control.FromHandle which (should) give you the access to it. Now, I wanted to try it using this code

I saw a method called Control.FromHandle which (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?


This method only works if the handle you pass in actually is a Control in your application.


In your particular case, since you just want to set the text, call SetWindowText from user32.dll


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消