现在的位置: 首页 > 综合 > 正文

动态设置form的icon

2012年02月02日 ⁄ 综合 ⁄ 共 1885字 ⁄ 字号 评论关闭
  • Creates a Bitmap.

  • Draws that object to the screen.

  • Gets an icon handle for the Bitmap.

  • Sets the attribute of the form to an icon created from the handle.

    1. [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)]
    2.         extern static bool DestroyIcon(IntPtr handle);
    3.         private void GetHicon_Example(PaintEventArgs e)
    4.         {
    5.             // Create a Bitmap object from an image file.
    6.             Bitmap myBitmap = new Bitmap(@"c:/Blue hills.jpg");
    7.             // Draw myBitmap to the screen.
    8.             e.Graphics.DrawImage(myBitmap, 0, 0);
    9.             // Get an Hicon for myBitmap.
    10.             IntPtr Hicon = myBitmap.GetHicon();
    11.             // Create a new icon from the handle. 
    12.             Icon newIcon = Icon.FromHandle(Hicon);
    13.             // Set the form Icon attribute to the new icon.
    14.             this.Icon = newIcon;
    15.             // Destroy the Icon, since the form creates
    16.             // its own copy of the icon.
    17.             DestroyIcon(newIcon.Handle);
    18.         }

    这是msdn中的方法,它有一个不好的地方就是需要一个PaintEventArgs 参数,我不明白微软为什么要把它搞得这么复杂,

    以下是我修改的方法,去掉了参数,只要把它写到form的构造函数中就可以了。

    1. [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)]
    2.         extern static bool DestroyIcon(IntPtr handle);
    3.         private void GetHicon_Example()
    4.         {
    5.             // Create a Bitmap object from an image file.
    6.             Bitmap myBitmap = new Bitmap(@"c:/Blue hills.jpg");
    7.             // Draw myBitmap to the screen.
    8.             this.CreateGraphics().DrawImage(myBitmap, 0, 0);
    9.             // Get an Hicon for myBitmap.
    10.             IntPtr Hicon = myBitmap.GetHicon();
    11.             // Create a new icon from the handle. 
    12.             Icon newIcon = Icon.FromHandle(Hicon);
    13.             // Set the form Icon attribute to the new icon.
    14.             this.Icon = newIcon;
    15.             // Destroy the Icon, since the form creates
    16.             // its own copy of the icon.
    17.             DestroyIcon(newIcon.Handle);
    18.         }
    【上篇】
    【下篇】

    抱歉!评论已关闭.