0

I'm still quite new to how handles works and need some help to understand this a bit more.

I have this method in my class, "cbxWebsite" is a combobox.

public IntPtr GetCurrentHandle()
{
    foreach (Process process in Process.GetProcesses())
    {
        if (process.ProcessName.Contains("chrome") 
            && process.MainWindowTitle.Contains(cbxWebsite.SelectedValue.ToString()))
        {
            return process.MainWindowHandle;
        }
    }
    return IntPtr.Zero;
}

And I'm trying to implement this: Capture screen of Window by handle

My question is about these lines:

    IntPtr hwnd = GetCurrentHandle();
    User32.GetWindowRect(new HandleRef(null, hwnd), ref rc);

When I call GetWindowRect, the HandleRef() complains about "Cannot convert from HandleRef to IntPtr".

MS docs says this about process.MainWindowHandle: The system-generated window handle of the main window of the associated process.

So I guess I don't understand from here. I thought I was returning the handle of the current window I want to work with from GetCurrentHandle(). But is it returning the handle of the process of that window and not the actual window-handle itself?

Can someone please clarify.

jumbotrone
  • 25
  • 3
  • 1
    It doesn't make much sense to create a `HandleRef` with a `null` wrapper instance. Why don't you just pass `hwnd` directly, when it's the expected parameter anyway? Btw. you should get some notification that though the conversion does not work an explicit cast [exists](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.handleref.op_explicit) from `HandleRef` to `IntPtr` – György Kőszeg Dec 19 '22 at 11:59
  • Good point, still exploring why. Also, just saw that MS states HandleRef is replaced by SafeHandle from NET 2.0 due to leaks in random ways. Anyway, yeah passing hwnd did solve the issue. Thanks. – jumbotrone Dec 19 '22 at 16:10

0 Answers0