views:

65

answers:

1

I'm fiddling with a desktop gadget (a clock). It has a reflection effect underneath it that needs to be transparent, and I'm using CopyFromScreen to get the background, then just setting the form background to this.

Like so (part of a "dock/undock" button):

        Rectangle bounds = this.Bounds;

        using (Bitmap ss = new Bitmap(bounds.Width, bounds.Height))
        using (Graphics g = Graphics.FromImage(ss))
        {
            this.Opacity = 0;

            g.CopyFromScreen(this.Location, Point.Empty, bounds.Size);
            ss.Save(@"C:\clock1s\bg", ImageFormat.Png);

            this.Opacity = 100;
            this.BackgroundImage = new Bitmap(@"C:\clock1s\bg");

            g.Dispose();
        }

Now, whenever I want to use this again (e.g move the clock) I'm not able to delete that file or resave it because it is currently in use. I've already tried setting the form BG to something else, but that didn't work.

How do I go about?

EDIT: Sorted, thanks (Lance McNearney).

Now, what if I had to save it to file?

Also, bonus question:

the goddamn batwatch

Selections and icons ending up underneath the form is a minor annoyance, and if possible I'd like them to either end up on top, or below (keeping the smooth anti-aliasing). I'm assuming that's way out of my leauge to fix though.

+5  A: 

Do you really need to save the image to the file system? Can't you store it in memory just for your application (and you won't have the problem anymore)?

A MemoryStream should work as a drop-in replacement for the file path in your code (although I obviously can't compile to test it):

Rectangle bounds = this.Bounds;

using (Bitmap ss = new Bitmap(bounds.Width, bounds.Height))
using (Graphics g = Graphics.FromImage(ss))
{
    this.Opacity = 0;
    g.CopyFromScreen(this.Location, Point.Empty, bounds.Size);

    using(MemoryStream ms = new MemoryStream()) {
        ss.Save(ms, ImageFormat.Png);

        this.Opacity = 100;
        this.BackgroundImage = new Bitmap(ms);
    }

    g.Dispose();
}
Lance McNearney
Duh. Thanks.Marking your answer later, allowing people to comment on the second part
m3n