How to use Control.FromHandle?

I saw a method called Control.FromHandle that (should) give you access to it. Now I wanted to try 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 this obviously will not work. I personally checked that the descriptor is correct ... but the method returns a null control. Any explanation?

+3
source share
3 answers

This method only works if the handle you are passing is actually Controlin your application.

+3
source

, , SetWindowText user32.dll

+2

- , , , , http://www.codeguru.com/forum/showthread.php?t=443191 , "MadHatter":

, , Control.FromHandle , , .net, , , , . - , , .net, , , / , windows api Control.FromHandle, - / .

Reading more about your question, it seems like you are trying to do some automation, or at least manipulate the window somehow. Perhaps I recommend looking at the Managed Windows API project at SourceForge. This is pretty well written, and we used it for the purposes you describe.

0
source

Source: https://habr.com/ru/post/1733700/


All Articles