microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.
MIT License
2.07k stars 87 forks source link

Add helpful static functions to `PICTDESC` #674

Open elachlan opened 2 years ago

elachlan commented 2 years ago

These static functions below are in winforms. FromIcon might be hard without a method to resolve dependencies added from templates.

public static PICTDESC FromBitmap(Bitmap bitmap, IntPtr paletteHandle = default)
{
    PICTDESC desc = new PICTDESC
    {
        picType = PICTYPE.BITMAP
    };

    desc.Union.bmp.hbitmap = bitmap.GetHbitmap();
    desc.Union.bmp.hpal = paletteHandle;
    return desc;
}

public static PICTDESC FromIcon(Icon icon, bool copy)
{
    PICTDESC desc = new PICTDESC
    {
        picType = PICTYPE.ICON
    };

    desc.Union.icon.hicon = copy ?
        User32.CopyImage(
            icon.Handle,
            User32.IMAGE.ICON,
            icon.Width,
            icon.Height,
            User32.LR.DEFAULTCOLOR)
        : icon.Handle;

    GC.KeepAlive(icon);
    return desc;
}

public static PICTDESC FromMetafile(Metafile metafile)
{
    PICTDESC desc = new PICTDESC
    {
        picType = PICTYPE.ENHMETAFILE
    };

    desc.Union.emf.hemf = metafile.GetHenhmetafile();
    return desc;
}

Winforms Tracking: https://github.com/dotnet/winforms/issues/7468

elachlan commented 2 years ago

I tried quickly to add FromBitmap and FromMetafile via a template. I got compile errors in the generated code around the global::System.Drawing.Bitmap and global::System.Drawing.Imaging.Metafile with the types not being available in the namespace.

AArnott commented 2 years ago

I got compile errors in the generated code ... with the types not being available

I'm guessing because the compilation would have to reference System.Drawing.dll to resolve those types. We may need to suppress using that template for compilations that do not already reference System.Drawing.

elachlan commented 1 year ago

@AArnott Do you have any examples of suppressing a template for compilations without certain references?

AArnott commented 1 year ago

Nothing for templates, no. I did recently add something so that templates can reference other metadata types and have that automatically trigger generation of those referenced types. So if you wanted to build on that to say that if the referenced types are not in the metadata and are not referenced otherwise to just skip the template, that sounds good to me.