How to use Control.FromHandle?

FBSC picture FBSC · Feb 20, 2010 · Viewed 9.2k times · Source

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?

Answer

user180326 picture user180326 · Feb 20, 2010

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