简体   繁体   中英

Need to delete a file, in use by my own app

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 (eg 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 http://upload.snelhest.org/images/100219batwatch.jpg

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM