开发者

System.Drawing.Icon constructor throwing "Operation completed successfully" exception

开发者 https://www.devze.com 2022-12-21 09:12 出处:网络
On a Windows XP machine, the following code is throwing a System.ComponentMode开发者_运维百科l.Win32Exception with the message \"The operation completed successfully\"

On a Windows XP machine, the following code is throwing a System.ComponentMode开发者_运维百科l.Win32Exception with the message "The operation completed successfully"

System.Drawing.Icon icon = new System.Drawing.Icon("icon.ico");

I can stop the program crashing with

try
{
    System.Drawing.Icon icon = new System.Drawing.Icon("icon.ico");
}
catch(System.ComponentModel.Win32Exception ex)
{
    if (ex.NativeErrorCode != 0)
    {
        throw;
    }
}

but of course the icon is not set.

The full stack trace is

at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(String fileName, Int32 width, Int32 height)
at System.Drawing.Icon..ctor(String fileName)
at hermes.Window1..ctor() in D:\\projects\\hermesclient\\hermesWPF\\hermes\\Window1.xaml.cs:line 50"

That line 50 is the original line I posted.

This is a WPF app, and on a Windows 7 machine the code works fine.

EDIT: Turned out the icon wasn't working in Windows XP at all, adding 256 colour versions seems to have fixed it.


From the looks of it the problem seems to be an issue with not disposing with objects properly. It's hard to pin point exactly where the issue in your case is occurring but as a general rule of thumb make sure you implement the using directive when dealing with objects that implement IDisposable.

Even in the sample you have provided try doing something like:

using (var icon = new System.Drawing.Icon("icon.ico"))
{
    // use icon
}
// icon is then disposed.

Have a read of this article.


Does the file icon1.ico exists in the same directory as the .NET executable? You did not say explicitly...are you reading this as an external icon file? perhaps this

string sPath2Icon = Path.Combine(Environment.CurrentDirectory, "icon1.ico");
using (System.Drawing.Icon icon = new System.Drawing.Icon(sPath2Icon)){
    // Do what you have to do with icon!
}

Hope this helps, Best regards, Tom.


I had a similar problem. in my case the icon file was a multiicon file containing 32x32, 48x48 and 256x256 size icons. I changed it to a single icon file size 32x32 and it worked fine after that.


Turned out the icon wasn't working in Windows XP at all, adding 256 colour versions seems to have fixed it.

0

精彩评论

暂无评论...
验证码 换一张
取 消