实例介绍
【实例简介】
【实例截图】
【核心代码】
public partial class ImageGrabberForm : Form { #region Data /// <summary> /// The assembly whose embedded images are currently being displayed. /// </summary> private Assembly currentAssembly; #endregion // Data #region Constructors public ImageGrabberForm() { InitializeComponent(); } public ImageGrabberForm( string assemblyPath ) : this() { if( assemblyPath != null ) this.LoadImagesFromAssembly( assemblyPath ); this.splitContainer.Panel2Collapsed = true; string[] modes = Enum.GetNames( typeof( PictureBoxSizeMode ) ); this.toolStripComboBox.Items.AddRange( modes ); this.toolStripComboBox.Items.Remove( "AutoSize" ); this.toolStripComboBox.Text = "CenterImage"; this.toolStripComboBox.Visible = false; this.toolStripComboSeparator.Visible = false; } #endregion // Constructors #region Event Handlers #region Drag-Drop #region DragEnter private void ImageGrabberForm_DragEnter( object sender, DragEventArgs e ) { if( !e.Data.GetDataPresent( DataFormats.FileDrop ) ) return; string[] filePaths = e.Data.GetData( DataFormats.FileDrop ) as string[]; if( filePaths.Length != 1 ) return; Assembly assembly = this.LoadAssembly( filePaths[0], false ); if( assembly == null ) return; e.Effect = DragDropEffects.Link; } #endregion // DragEnter #region DragDrop private void ImageGrabberForm_DragDrop( object sender, DragEventArgs e ) { string assemblyPath = (e.Data.GetData( DataFormats.FileDrop ) as string[])[0]; this.LoadImagesFromAssembly( assemblyPath ); } #endregion // DragDrop #endregion // Drag-Drop #region ToolStrip Commands #region Open private void openToolStripButton_Click( object sender, EventArgs e ) { this.PerformOpen(); } #endregion // Open #region Save private void saveToolStripButton_Click( object sender, EventArgs e ) { this.PerformSave(); } #endregion // Save #region Copy private void copyToolStripButton_Click( object sender, EventArgs e ) { this.PerformCopy(); } #endregion // Copy #region View/Hide Properties private void propertiesToolStripButton_Click( object sender, EventArgs e ) { this.PerformViewHideProperties(); } #endregion // View/Hide Properties #region SizeMode private void toolStripComboBox_SelectedIndexChanged( object sender, EventArgs e ) { if( this.Created ) this.pictureBox.SizeMode = (PictureBoxSizeMode)Enum.Parse( typeof(PictureBoxSizeMode), this.toolStripComboBox.Text ); } #endregion // SizeMode #endregion // ToolStrip Commands #region BindingSource #region ListChanged private void bindingSource_ListChanged( object sender, ListChangedEventArgs e ) { if( e.ListChangedType == ListChangedType.Reset ) { this.bindingSource.Position = 0; bool imagesExist = this.bindingSource.Count > 0; this.copyToolStripButton.Enabled = imagesExist; this.saveToolStripButton.Enabled = imagesExist; this.toolStripComboBox.Enabled = imagesExist; this.propertiesToolStripButton.Enabled = imagesExist; this.tabControl.Enabled = imagesExist; this.propertyGrid.Enabled = imagesExist; if( !imagesExist ) { MessageBox.Show( "The selected assembly does not have any embedded images.", "No Images", MessageBoxButtons.OK, MessageBoxIcon.Information ); } if( this.propertyGrid.DataBindings.Count == 0 ) { this.pictureBox.DataBindings.Add( "Image", this.bindingSource, "Image" ); this.propertyGrid.DataBindings.Add( "SelectedObject", this.bindingSource, "ResourceDetails" ); this.dataGridView.DataSource = this.bindingSource; this.dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; this.dataGridView.Columns[1].Visible = false; } } } #endregion // ListChanged #endregion // BindingSource #region ContextMenuStrip Commands private void menuItemCopy_Click( object sender, EventArgs e ) { this.PerformCopy(); } private void menuItemProperties_Click( object sender, EventArgs e ) { this.PerformViewHideProperties(); } private void menuItemSave_Click( object sender, EventArgs e ) { this.PerformSave(); } #endregion // ContextMenuStrip Commands #region Misc #region dataGridView_MouseDown private void dataGridView_MouseDown( object sender, MouseEventArgs e ) { // To ensure that the user is going to save/copy the image under the cursor, // make the row under the cursor the current item in the binding source. if( e.Button == MouseButtons.Right ) { System.Windows.Forms.DataGridView.HitTestInfo info = this.dataGridView.HitTest( e.X, e.Y ); if( info.RowIndex > -1 ) this.bindingSource.Position = info.RowIndex; } } #endregion // dataGridView_MouseDown #region tabControl_SelectedIndexChanged private void tabControl_SelectedIndexChanged( object sender, EventArgs e ) { this.toolStripComboBox.Visible = this.tabControl.SelectedTab == this.tabPageIndividualImage; this.toolStripComboSeparator.Visible = this.tabControl.SelectedTab == this.tabPageIndividualImage; } #endregion // tabControl_SelectedIndexChanged #endregion // Misc #endregion // Event Handlers #region Private Helpers #region ExtractImagesFromAssembly private List<ImageInfo> ExtractImagesFromAssembly( Assembly assembly ) { List<ImageInfo> imageInfos = new List<ImageInfo>(); foreach( string name in assembly.GetManifestResourceNames() ) { using( Stream stream = assembly.GetManifestResourceStream( name ) ) { #region Icon // Treat the resource as an icon. try { Icon icon = new Icon( stream ); imageInfos.Add( new ImageInfo( icon, name ) ); continue; } catch( ArgumentException ) { stream.Position = 0; } #endregion // Icon #region Cursor // Treat the resource as a cursor. try { Cursor cursor = new Cursor( stream ); imageInfos.Add( new ImageInfo( cursor, name ) ); continue; } catch( ArgumentException ) { stream.Position = 0; } #endregion // Cursor #region Image // Treat the resource as an image. try { Image image = Image.FromStream( stream ); // If the image is an animated GIF, do not add it to the collection // because the Image class cannot handle them and will throw an exception // when the image is displayed. FrameDimension frameDim = new FrameDimension( image.FrameDimensionsList[0] ); bool isAnimatedGif = image.GetFrameCount( frameDim ) > 1; if( !isAnimatedGif ) imageInfos.Add( new ImageInfo( image, name ) ); else image.Dispose(); continue; } catch( ArgumentException ) { stream.Position = 0; } #endregion // Image #region Resource File // Treat the resource as a resource file. try { // The embedded resource in the stream is not an image, so // read it into a ResourceReader and extract the values from there. using( IResourceReader reader = new ResourceReader( stream ) ) { foreach( DictionaryEntry entry in reader ) { if( entry.Value is Icon ) { imageInfos.Add( new ImageInfo( entry.Value, name ) ); } else if( entry.Value is Image ) { imageInfos.Add( new ImageInfo( entry.Value, name ) ); } else if( entry.Value is ImageListStreamer ) { // Load an ImageList with the ImageListStreamer and // store a reference to every image it contains. using( ImageList imageList = new ImageList() ) { imageList.ImageStream = entry.Value as ImageListStreamer; foreach( Image image in imageList.Images ) imageInfos.Add( new ImageInfo( image, name ) ); } } } } } catch( Exception ) { } #endregion // Resource File } } return imageInfos; } #endregion // ExtractImagesFromAssembly #region LoadAssembly private Assembly LoadAssembly( string assemblyPath, bool showErrorDialog ) { try { // Use ReflectionOnlyLoadFrom to ensure that the assembly can be loaded. Assembly assembly = Assembly.ReflectionOnlyLoadFrom( assemblyPath ); // Update the text/tooltip in the StatusStrip to the new assembly info. this.toolStripStatusLabel.Text = assembly.FullName; this.toolStripStatusLabel.ToolTipText = assembly.Location; return assembly; } catch( Exception ) { if( showErrorDialog ) { MessageBox.Show( "The specified file is not a .NET assembly.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } return null; } } #endregion // LoadAssembly #region LoadImagesFromAssembly private void LoadImagesFromAssembly( string assemblyPath ) { // Try to load the assembly at the specified location. Assembly assembly = this.LoadAssembly( assemblyPath, true ); if( assembly == null ) return; this.currentAssembly = assembly; // Dispose of the images currently being displayed, if any. if( this.bindingSource.DataSource != null ) foreach( ImageInfo imgInfo in this.bindingSource.DataSource as List<ImageInfo> ) imgInfo.Dispose(); // Bind to a list of every image embedded in the assembly. this.bindingSource.DataSource = this.ExtractImagesFromAssembly( this.currentAssembly ); } #endregion // LoadImagesFromAssembly #region PerformXXX private void PerformCopy() { if( this.pictureBox.Image != null ) Clipboard.SetImage( this.pictureBox.Image ); } private void PerformOpen() { using( OpenFileDialog dlg = new OpenFileDialog() ) { dlg.Filter = "Assemblies (*.exe, *.dll)|*.exe;*.dll"; if( dlg.ShowDialog() == DialogResult.OK ) this.LoadImagesFromAssembly( dlg.FileName ); } } private void PerformSave() { using( SaveFileDialog dlg = new SaveFileDialog() ) { ImageInfo imageInfo = this.bindingSource.Current as ImageInfo; dlg.Filter = "Bitmap (*.bmp)|*.bmp"; if( imageInfo.ResourceDetails.ImageType == ImageType.Icon ) dlg.Filter = "Icon (*.ico)|*.ico|" dlg.Filter; else if( imageInfo.ResourceDetails.ImageType == ImageType.Cursor ) dlg.Filter = "Cursor (*.cur)|*.cur|" dlg.Filter; if( dlg.ShowDialog() == DialogResult.OK ) this.SaveImage( imageInfo, dlg.FileName ); } } private void PerformViewHideProperties() { this.splitContainer.Panel2Collapsed = !this.splitContainer.Panel2Collapsed; string text = this.splitContainer.Panel2Collapsed ? "View Properties" : "Hide Properties"; this.propertiesToolStripButton.ToolTipText = text; this.menuItemProperties.Text = text; // If the tab control does not repaint now, a section of it will not be // drawn properly. this.tabControl.Refresh(); } #endregion // PerformXXX #region SaveImage private void SaveImage( ImageInfo imageInfo, string fileName ) { string extension = String.Empty; if( fileName.Length > 4 ) extension = fileName.Substring( fileName.Length - 4, 4 ); try { switch( extension ) { #region Icon case ".ico": // If, for some bizarre reason, someone tries to save a bitmap as an icon, // ignore that request and just save it as a bitmap. if( imageInfo.SourceObject is Icon == false ) goto default; using( FileStream stream = new FileStream( fileName, FileMode.Create, FileAccess.Write ) ) (imageInfo.SourceObject as Icon).Save( stream ); break; #endregion // Icon #region Cursor case ".cur": // If, for some bizarre reason, someone tries to save a bitmap as a cursor, // ignore that request and just save it as a bitmap. if( imageInfo.SourceObject is Cursor == false ) goto default; // Copy the cursor byte-by-byte out of the assembly into a file. using( Stream stream = this.currentAssembly.GetManifestResourceStream( imageInfo.ResourceDetails.ResourceName ) ) using( FileStream fileStream = new FileStream( fileName, FileMode.Create, FileAccess.Write ) ) { int i; while( (i = stream.ReadByte()) > -1 ) fileStream.WriteByte( (byte)i ); } break; #endregion // Cursor #region Bitmap case ".bmp": default: // Make sure the file name ends with ".bmp" if( extension != ".bmp" ) fileName = ".bmp"; // Copy the image to a new bitmap or else an error can occur while saving. using( Bitmap bmp = new Bitmap( imageInfo.Image ) ) bmp.Save( fileName ); break; #endregion // Bitmap } } catch( Exception ex ) { MessageBox.Show( "An exception was thrown while trying to save the image: " ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } #endregion // SaveImage #endregion // Private Helpers }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论