Boardy
Boardy

Reputation: 36237

Assign a system icon to a label

I am currently developing a c# application. I am making my own custom message box so I was wondering if would be possible for me to be able to assign a default system icon (i.e. one of the icons that you would see on a standard MessageBox) to a label.

Upvotes: 3

Views: 8431

Answers (3)

CrizztlCoder
CrizztlCoder

Reputation: 71

System.Drawing.Icon myIcon = new System.Drawing.Icon(System.Drawing.SystemIcons.Question,32,32);
label.Image = myIcon.ToBitmap();

Upvotes: 7

Thomas Levesque
Thomas Levesque

Reputation: 292765

SLaks' solution is probably the easiest way to go. If, for some reason, you don't want to use Windows Forms features, it's pretty easy to implement yourself:

public enum SystemIcons
{
    Application = 32512,
    Error = 32513,
    Hand = Error,
    Question = 32514,
    Warning = 32515,
    Exclamation = Warning,
    Information = 32516,
    Asterisk = Information,
    WinLogo = 32517,
    Shield = 32518,
}

public static ImageSource LoadSystemIcon(SystemIcons iconId)
{
    string iconName = "#" + ((int)iconId);
    IntPtr hIcon = LoadIcon(IntPtr.Zero, iconName);
    if (hIcon == IntPtr.Zero)
        return null;

    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
        hIcon, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}

[DllImport("user32.dll")]
static extern IntPtr LoadIcon(IntPtr hInstance, string lpIconName);

Upvotes: 1

SLaks
SLaks

Reputation: 888293

You can interoperate with System.Drawing and System.Windows.Forms:

System.Drawing.Icon icon = System.Drawing.SystemIcons.Warning;

BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

image1.Source = bs;

Upvotes: 4

Related Questions