CBC_NS
CBC_NS

Reputation: 1957

Icon not showing on WPF at runtime C# .NET?

I have a WPF form where I am trying to add an icon. In the properties menu I selected my icon from my resources folder. In the design view, the icon appears where it should. When I go to run the application, it shows the default view. I've checked several sources. The most common response is to set it to the main form which I did as well. Below is what my code looks like.

//in private void InitializeComponent()
{
    this.Load += new System.EventHandler(this.CallTrak_Load);
}

//in CallTrak.Load
private void CallTrak_Load(object sender, EventArgs e)
{
    System.Drawing.Icon ico = Properties.Resources.favicon;
    this.Icon = ico;
}

So, my question is as it relates to the title of this post, am I loading my icon incorrectly at runtime? If so, suggestions on how to do so correctly. What else should I check to see what my problem is?

Upvotes: 1

Views: 2852

Answers (1)

Jan
Jan

Reputation: 376

I am not sure you have WPF app and in resource you have icon file type of ico?

If yes. Problem is maybe here:

Your ico variable is type of System.Drawing.Icon and Window.Icon property is type of ImageSource.

  System.Drawing.Icon ico = Properties.Resources.favicon;
  //can not assign Drawing.Icon to ImageSource
  this.Icon = ico;

You should get exception:

Cannot implicitly convert type 'System.Drawing.Icon' to 'System.Windows.Media.ImageSource'

If you want use your way you need convert System.Drawin.Icon to ImageSource.

    internal static class IconUtilities
    {
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);

        public static ImageSource ToImageSource(Icon icon)
        {
            Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();

            ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            if (!DeleteObject(hBitmap))
            {
                throw new Win32Exception();
            }

            return wpfBitmap;
        }
    }

    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        ImageSource imageSource = IconUtilities.ToImageSource(Properties.Resources.love);
        this.Icon = imageSource;

        //System.Drawing.Icon ico = Properties.Resources.love;
        //this.Icon = ico;
    }

Or simple way:

For example put you icon to images folder. Set build action to content and copy to output directory copy if newer. Then you can use:

this.Icon = new BitmapImage(new Uri("images/love.ico", UriKind.Relative));

Sample app you can download here.

Upvotes: 2

Related Questions