private void showDetails()
        {
            // show the link's details:
            lblShortCut.Text = System.IO.Path.GetFileName(link.ShortCutFile);

            txtTarget.Text      = link.Target;
            txtArguments.Text   = link.Arguments;
            txtDescription.Text = link.Description;
            txtIconFile.Text    = link.IconPath;
            txtIconIndex.Text   = (link.IconPath.Length > 0 ? link.IconIndex.ToString() : "");
            System.Drawing.Icon linkIcon = link.LargeIcon;
            if (linkIcon != null)
            {
                picIcon.Image = linkIcon.ToBitmap();
                linkIcon.Dispose();
            }
            else
            {
                picIcon.Image = null;
            }
            linkIcon = link.SmallIcon;
            if (linkIcon != null)
            {
                picSmallIcon.Image = linkIcon.ToBitmap();
                linkIcon.Dispose();
            }
            else
            {
                picSmallIcon.Image = null;
            }
        }
 private void GenerateWindowsIcon()
 {
     var stm = new MemoryStream();
     var icon = new Icon(new MemoryStream(resource.Bytes));
     dlg.Image = Bitmap.FromHicon(icon.Handle);
     icon.Dispose();
 }
        public static Image GetFileIcon(string fullpath, FileIconSize size)
        {
            UnsafeNativeMethods.SHFILEINFO info = new UnsafeNativeMethods.SHFILEINFO();

            uint flags = UnsafeNativeMethods.SHGFI_USEFILEATTRIBUTES | UnsafeNativeMethods.SHGFI_ICON;

            if (size == FileIconSize.Small)
            {
                flags |= UnsafeNativeMethods.SHGFI_SMALLICON;
            }

            int retval = UnsafeNativeMethods.SHGetFileInfo(fullpath, UnsafeNativeMethods.FILE_ATTRIBUTE_NORMAL,
                                                           ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);

            if (retval == 0)
            {
                return(null);  // error occured
            }

            System.Drawing.Icon icon    = System.Drawing.Icon.FromHandle(info.hIcon);
            ImageList           imglist = new ImageList();

            imglist.ImageSize = icon.Size;
            imglist.Images.Add(icon);
            Image image = imglist.Images[0];

            icon.Dispose();
            return(image);
        }
Beispiel #4
0
        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                // Release the icon resource.
                icnTask.Dispose();
            }

            base.Dispose(isDisposing);
        }
        /// <summary>
        /// Adds a 32bit alphablended icon or image to an existing imagelist from an embedded image or icon.
        /// </summary>
        /// <param name="ResourceName">The name of an embedded resource.</param>
        /// <param name="Imagelist">An existing imagelist to add the resource to.</param>
        /// <example>.AddEmbeddedResource( "ProjectName.file.ico", toolbarImagelist );</example>
        public static void AddEmbeddedResource( string resourceName, ImageList destinationImagelist )
        {
            Bitmap bm = new Bitmap ( Assembly.GetExecutingAssembly ( ).GetManifestResourceStream ( resourceName ) );

            if ( bm.RawFormat.Guid == ImageFormat.Icon.Guid ) {
                Icon icn = new Icon ( Assembly.GetExecutingAssembly ( ).GetManifestResourceStream ( resourceName ) );
                destinationImagelist.Images.Add ( resourceName, Icon.FromHandle ( icn.Handle ) );
                icn.Dispose ( );
            } else {
                AddFromImage ( bm, destinationImagelist );
            }
            bm.Dispose ( );
        }
        public static void Add(string FileName, ImageList Imagelist)
        {
            Bitmap bitmap = new Bitmap(FileName);

            if (bitmap.RawFormat.Guid == ImageFormat.Icon.Guid)
            {
                Icon icon = new Icon(FileName);

                Imagelist.Images.Add(Icon.FromHandle(icon.Handle));
                icon.Dispose();
            }
            else
                Add(bitmap, Imagelist);

            bitmap.Dispose();
        }
 private Image GetTargetWindowIcon()
 {
     Image image = null;
     IntPtr handle = System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef(this, Control.GetSafeHandle(this.target)), 0x7f, 0, 0);
     System.Windows.Forms.IntSecurity.ObjectFromWin32Handle.Assert();
     try
     {
         Icon original = (handle != IntPtr.Zero) ? Icon.FromHandle(handle) : Form.DefaultIcon;
         Icon icon2 = new Icon(original, SystemInformation.SmallIconSize);
         image = icon2.ToBitmap();
         icon2.Dispose();
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
     return image;
 }
 public static BitmapSource ConvertFromIcon(Icon icon)
 {
     try
     {
         var bs = Imaging
             .CreateBitmapSourceFromHIcon(icon.Handle,
                                          new Int32Rect(0, 0, icon.Width, icon.Height),
                                          BitmapSizeOptions.FromWidthAndHeight(icon.Width,
                                                                               icon.Height));
         return bs;
     }
     finally
     {
         DeleteObject(icon.Handle);
         icon.Dispose();
         // ReSharper disable RedundantAssignment
         icon = null;
         // ReSharper restore RedundantAssignment
     }
 }
 private int AddIconToHandle(Original original, Icon icon)
 {
     int num2;
     try
     {
         int num = System.Windows.Forms.SafeNativeMethods.ImageList_ReplaceIcon(new HandleRef(this, this.Handle), -1, new HandleRef(icon, icon.Handle));
         if (num == -1)
         {
             throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ImageListAddFailed"));
         }
         num2 = num;
     }
     finally
     {
         if ((original.options & OriginalOptions.OwnsImage) != OriginalOptions.Default)
         {
             icon.Dispose();
         }
     }
     return num2;
 }
        /// <summary>
        /// Proceudra obtine icoana unui fisier
        /// </summary>
        /// <param name="fullpath">Calea fisierului</param>
        /// <returns>Returneaza icoana fisierului</returns>
        public static System.Drawing.Image GetFileIcon(string fullpath)
        {
            SHFILEINFO info = new SHFILEINFO();

            int retval = SHGetFileInfo(fullpath, FILE_ATTRIBUTE_NORMAL, ref info,
                                       System.Runtime.InteropServices.Marshal.SizeOf(info), SHGFI_USEFILEATTRIBUTES
                                       | SHGFI_ICON);

            if (retval == 0)
            {
                return(null);                // error occured
            }

            System.Drawing.Icon icon    = System.Drawing.Icon.FromHandle(info.hIcon);
            ImageList           imglist = new ImageList();

            imglist.ImageSize = icon.Size;
            imglist.Images.Add(icon);
            System.Drawing.Image image = imglist.Images[0];
            icon.Dispose();
            return(image);
        }
Beispiel #11
0
        protected override int _AddImageInternal(IntPtr icon, int destinationIndex)
        {
            if (icon == IntPtr.Zero)
            {
                return(-1);
            }

            int result = -1;

            lock (this)
            {
                if (_imageList == null)
                {
                    throw new Aurigma.GraphicsMill.UnexpectedException(StringResources.GetString("InternalImageListCannotBeNull"));
                }

                System.Drawing.Icon bitmap = System.Drawing.Icon.FromHandle(icon);
                if (_imageList.ImageSize != new Size(bitmap.Width, bitmap.Height))
                {
                    _imageList.ImageSize = new Size(bitmap.Width, bitmap.Height);
                }

                if (destinationIndex != -1)
                {
                    _imageList.Images[destinationIndex] = bitmap.ToBitmap();
                    bitmap.Dispose();
                    result = destinationIndex;
                }
                else
                {
                    _imageList.Images.Add(bitmap);
                    result = _imageList.Images.Count - 1;
                }
            }

            return(result);
        }
Beispiel #12
0
        private void SavePicture(string S_Name)
        {
            string[] arry     = S_Name.Split('.');
            Bitmap   Bmp      = new Bitmap((Bitmap)Image.FromFile(textBox1.Text + "\\" + S_Name), int.Parse(textBox3.Text), int.Parse(textBox4.Text));
            string   SaveName = textBox2.Text + "\\";

            IfNotFileCreat(SaveName);
            SaveName += (arry[0] + "." + SaveType);
            switch (SaveType)
            {
            case "Png": Bmp.Save(SaveName, ImageFormat.Png); break;

            case "Ico": Bmp.Save(SaveName, ImageFormat.Icon);
                System.Drawing.Icon  icon       = System.Drawing.Icon.FromHandle(Bmp.GetHicon());
                System.IO.FileStream fileStream = new System.IO.FileStream(SaveName, System.IO.FileMode.Create);
                icon.Save(fileStream);
                Bmp.Dispose();
                fileStream.Close();
                fileStream.Dispose();
                icon.Dispose();
                break;

            case "Emf": Bmp.Save(SaveName, ImageFormat.Emf); break;

            case "Jpg": Bmp.Save(SaveName, ImageFormat.Jpeg); break;

            case "Wmf": Bmp.Save(SaveName, ImageFormat.Wmf); break;

            case "Gif": Bmp.Save(SaveName, ImageFormat.Gif); break;

            case "Exif": Bmp.Save(SaveName, ImageFormat.Exif); break;

            case "Bmp": Bmp.Save(SaveName, ImageFormat.Bmp); break;

            default: break;
            }
        }
Beispiel #13
0
        /// <summary>
        /// Extracts an icon from any file type.
        /// </summary>
        public static Icon ExtractIcon(string filePath, IconSize size)
        {
            Icon icon     = null;
            var  fileInfo = new SHFILEINFOW();

            if (NativeMethods.SHGetFileInfoW(filePath, NativeMethods.FILE_ATTRIBUTE_NORMAL, ref fileInfo, Marshal.SizeOf(fileInfo), NativeMethods.SHGFI_SYSICONINDEX) == 0)
            {
                throw new FileNotFoundException();
            }

            var        iidImageList = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950");
            IImageList imageList    = null;

            NativeMethods.SHGetImageList((int)size, ref iidImageList, ref imageList);

            if (imageList != null)
            {
                var hIcon = IntPtr.Zero;
                imageList.GetIcon(fileInfo.iIcon, (int)NativeMethods.ILD_IMAGE, ref hIcon);
                icon = Icon.FromHandle(hIcon).Clone() as Icon;

                NativeMethods.DestroyIcon(hIcon);

                if (icon.ToBitmap().PixelFormat != PixelFormat.Format32bppArgb)
                {
                    icon.Dispose();

                    imageList.GetIcon(fileInfo.iIcon, (int)NativeMethods.ILD_TRANSPARENT, ref hIcon);
                    icon = Icon.FromHandle(hIcon).Clone() as Icon;

                    NativeMethods.DestroyIcon(hIcon);
                }
            }

            return(icon);
        }
		public void Icon256ToBitmap ()
		{
			if (RunningOnUnix)
				Assert.Ignore ("Depends on bug #323511");

			using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/415581.ico"))) {
				Icon icon = new Icon (fs, 48, 48);
				using (Bitmap b = icon.ToBitmap ()) {
					Assert.AreEqual (0, b.Palette.Entries.Length, "#A1");
					Assert.AreEqual (48, b.Height, "#A2");
					Assert.AreEqual (48, b.Width, "#A3");
					Assert.IsTrue (b.RawFormat.Equals (ImageFormat.MemoryBmp), "#A4");
					Assert.AreEqual (2, b.Flags, "#A5");
				}
				icon.Dispose ();
			}

			using (FileStream fs = File.OpenRead (TestBitmap.getInFile ("bitmaps/415581.ico"))) {
				Icon icon = new Icon (fs, 256, 256);
				using (Bitmap b = icon.ToBitmap ()) {
					Assert.AreEqual (0, b.Palette.Entries.Length, "#B1");
					Assert.AreEqual (48, b.Height, "#B2");
					Assert.AreEqual (48, b.Width, "#B3");
					Assert.IsTrue (b.RawFormat.Equals (ImageFormat.MemoryBmp), "#B4");
					Assert.AreEqual (2, b.Flags, "#B5");
				}
			}
		}
        public VCRNETControl( string[] args )
        {
            // Report
            Log( "VCC [2013/06/01] starting up" );

            // Autostart service
            if (m_Settings.AutoStartService)
                if (!ThreadPool.QueueUserWorkItem( StartService ))
                    StartService( null );

            // This is us
            Type me = GetType();

            // Pattern start
            string prefix = me.Namespace + ".TrayIcons.";
            string suffix = ".ICO";

            // Load tray icons
            foreach (string resname in me.Assembly.GetManifestResourceNames())
                if (resname.StartsWith( prefix ))
                    if (resname.EndsWith( suffix ))
                    {
                        // Icon
                        string iconname = resname.Substring( prefix.Length, resname.Length - prefix.Length - suffix.Length );

                        // Load
                        using (Stream stream = me.Assembly.GetManifestResourceStream( resname ))
                        {
                            // Load the icon
                            Icon icon = new Icon( stream );

                            // Check for debugger
                            if (Debugger.IsAttached)
                                using (var bmp = icon.ToBitmap())
                                {
                                    // Change
                                    using (var gc = Graphics.FromImage( bmp ))
                                    using (var color = new SolidBrush( Color.Black ))
                                    {
                                        // Paint
                                        gc.FillRectangle( color, 0, 15, bmp.Width, 5 );
                                    }

                                    // Free icon
                                    icon.Dispose();

                                    // Reload
                                    icon = Icon.FromHandle( bmp.GetHicon() );
                                }

                            // Get the related color
                            var colorIndex = (TrayColors)Enum.Parse( typeof( TrayColors ), iconname, true );

                            // Add to map
                            m_TrayIcons[colorIndex] = icon;
                        }
                    }

            // Load picture
            using (var stream = me.Assembly.GetManifestResourceStream( me.Namespace + ".Icons.Connected.ico" ))
                m_Connected = Image.FromStream( stream );

            // Startup
            InitializeComponent();

            // Load the top menu string
            m_TopMenu = mnuDefault.Text;

            // Correct IDE problems (destroyed when language changes)
            selHibernate.Value = 5;
            selHibernate.Minimum = 1;
            selHibernate.Maximum = 30;
            selInterval.Value = 10;
            selInterval.Minimum = 5;
            selInterval.Maximum = 300;
            selPort.Maximum = ushort.MaxValue;
            selPort.Value = 80;
            selPort.Minimum = 1;
            selStreamPort.Maximum = ushort.MaxValue;
            selStreamPort.Value = 2910;
            selStreamPort.Minimum = 1;
            lstServers.View = View.Details;
            errorMessages.SetIconAlignment( txArgs, ErrorIconAlignment.MiddleLeft );
            errorMessages.SetIconAlignment( txMultiCast, ErrorIconAlignment.MiddleLeft );

            // Make sure that handle exists
            CreateHandle();

            // Load servers
            if (null != m_Settings.Servers)
                foreach (var setting in m_Settings.Servers)
                    lstServers.Items.Add( setting.View );

            // Load settings
            ckAutoStart.Checked = m_Settings.AutoStartService;
            ckHibernate.Checked = (m_Settings.HibernationDelay > 0);
            selHibernate.Value = ckHibernate.Checked ? (int)m_Settings.HibernationDelay : 5;
            txMultiCast.Text = m_Settings.MulticastIP;
            selStreamPort.Value = m_Settings.MinPort;
            selDelay.Value = m_Settings.StartupDelay;
            txArgs.Text = m_Settings.ViewerArgs;
            txViewer.Text = m_Settings.Viewer;

            // The default
            CultureItem selectedItem = null;

            // Fill language list
            foreach (var info in CultureInfo.GetCultures( CultureTypes.NeutralCultures ))
            {
                // Skip all sub-languages
                if (info.NativeName.IndexOf( '(' ) >= 0) continue;

                // Create
                var item = new CultureItem( info );

                // Add to map
                selLanguage.Items.Add( item );

                // Remember default
                if (Equals( m_Settings.Language, info.TwoLetterISOLanguageName )) selectedItem = item;
            }

            // Copy over
            selLanguage.SelectedItem = selectedItem;

            // Update GUI
            CheckLocal();
            CheckStream();

            // No local service
            frameLocal.Enabled = false;

            // See if local service exists
            try
            {
                // Attach to registry
                using (var vcr = Registry.LocalMachine.OpenSubKey( @"SYSTEM\CurrentControlSet\Services\VCR.NET Service" ))
                    if (null != vcr)
                    {
                        // Load path
                        string image = (string)vcr.GetValue( "ImagePath" );
                        if (!string.IsNullOrEmpty( image ))
                        {
                            // Correct
                            if (image.StartsWith( "\"" ) && image.EndsWith( "\"" ) && (image.Length > 1))
                            {
                                // Remove quotes
                                image = image.Substring( 1, image.Length - 2 ).Replace( "\"\"", "\"" );
                            }
                        }

                        // Attach to configuration file
                        var config = new FileInfo( image + ".config" );
                        if (config.Exists)
                        {
                            // Load DOM
                            XmlDocument dom = new XmlDocument();
                            dom.Load( config.FullName );

                            // Check for port
                            var portNode = (XmlElement)dom.SelectSingleNode( "configuration/appSettings/add[@key='TCPPort']" );
                            var port = ushort.Parse( portNode.GetAttribute( "value" ) );

                            // At least there is a valid local server
                            frameLocal.Enabled = true;

                            // Check for defaulting
                            if (lstServers.Items.Count < 1)
                            {
                                // Create a new entry
                                var settings =
                                    new PerServerSettings
                                    {
                                        ServerName = "localhost",
                                        RefreshInterval = 10,
                                        ServerPort = port,
                                    };

                                // Add
                                m_Settings.Servers = new PerServerSettings[] { settings };

                                // Try add
                                try
                                {
                                    // Save
                                    m_Settings.Save();

                                    // Add to list
                                    lstServers.Items.Add( settings.View );
                                }
                                catch
                                {
                                    // Reset
                                    m_Settings.Servers = null;
                                }
                            }
                        }
                    }
            }
            catch
            {
                // Ignore any error
            }

            // Install tray icons
            CreateTrayIcons();

            // Prepare buttons
            lstServers_SelectedIndexChanged( lstServers, EventArgs.Empty );
        }
        private System.Windows.Media.ImageSource ConvertIconToImageSource(VistaTaskDialogIcon icon, Icon customIcon, bool isLarge)
        {
            System.Windows.Media.ImageSource iconSource = null;
            System.Drawing.Icon   sysIcon = null;
            System.Drawing.Bitmap altBmp  = null;

            try
            {
                switch (icon)
                {
                default:
                case VistaTaskDialogIcon.None:
                    break;

                case VistaTaskDialogIcon.Information:
                    sysIcon = SystemIcons.Information;
                    break;

                case VistaTaskDialogIcon.Warning:
                    sysIcon = SystemIcons.Warning;
                    break;

                case VistaTaskDialogIcon.Error:
                    sysIcon = SystemIcons.Error;
                    break;

                case VistaTaskDialogIcon.Shield:
                    if (isLarge)
                    {
                        altBmp = Properties.Resources.shield_32;
                    }
                    else
                    {
                        altBmp = Properties.Resources.shield_16;
                    }
                    break;
                }

                // Custom Icons always take priority
                if (customIcon != null)
                {
                    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                        customIcon.Handle,
                        System.Windows.Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                }
                else if (sysIcon != null)
                {
                    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                        sysIcon.Handle,
                        System.Windows.Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                }
                else if (altBmp != null)
                {
                    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        altBmp.GetHbitmap(),
                        IntPtr.Zero,
                        System.Windows.Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                }
            }
            finally
            {
                // Not responsible for disposing of custom icons

                if (sysIcon != null)
                {
                    sysIcon.Dispose();
                }
                if (altBmp != null)
                {
                    altBmp.Dispose();
                }
            }

            return(iconSource);
        }
Beispiel #17
0
            private Image GetTargetWindowIcon() {
                Image systemIcon = null;
                IntPtr hIcon = UnsafeNativeMethods.SendMessage(new HandleRef(this, Control.GetSafeHandle(target)), NativeMethods.WM_GETICON, NativeMethods.ICON_SMALL, 0);
                IntSecurity.ObjectFromWin32Handle.Assert();
                try {
                    Icon icon =  (hIcon != IntPtr.Zero) ? Icon.FromHandle(hIcon) : Form.DefaultIcon;
                    Icon smallIcon = new Icon(icon, SystemInformation.SmallIconSize);

                    systemIcon = smallIcon.ToBitmap();
                    smallIcon.Dispose();
                } finally {
                    CodeAccessPermission.RevertAssert();
                }

                return systemIcon;
                
            }
 private static Bitmap GetBitmapFromIcon(string iconName)
 {
     Size desiredSize = new Size(iconsWidth, iconsHeight);
     Icon icon = new Icon(BitmapSelector.GetResourceStream(typeof(DataGridViewRowHeaderCell), iconName), desiredSize);
     Bitmap b = icon.ToBitmap();
     icon.Dispose();
     
     if (DpiHelper.IsScalingRequired && (b.Size.Width != iconsWidth || b.Size.Height != iconsHeight))
     {
         Bitmap scaledBitmap = DpiHelper.CreateResizedBitmap(b, desiredSize);
         if (scaledBitmap != null)
         {
             b.Dispose();
             b = scaledBitmap;
         }
     }
     return b;
 }
Beispiel #19
0
 private int AddIconToHandle(Original original, Icon icon) {
     try {
         Debug.Assert(HandleCreated, "Calling AddIconToHandle when there is no handle");
         int index = SafeNativeMethods.ImageList_ReplaceIcon(new HandleRef(this, Handle), -1, new HandleRef(icon, icon.Handle));
         if (index == -1) throw new InvalidOperationException(SR.GetString(SR.ImageListAddFailed));
         return index;
     } finally {
         if((original.options & OriginalOptions.OwnsImage) != 0) { /// this is to handle the case were we clone the icon (see WHY WHY WHY below)
             icon.Dispose();
         }
     }
 }
 private static Bitmap CreateDotDotDotBitmap()
 {
     Bitmap bitmap = null;
     Icon icon = null;
     try
     {
         icon = new Icon(typeof(TypeEditorHost), "dotdotdot.ico");
         using (var original = icon.ToBitmap())
         {
             bitmap = BitmapFromImageReplaceColor(original);
         }
     }
     catch
     {
         bitmap = new Bitmap(16, 16);
         throw;
     }
     finally
     {
         if (icon != null)
         {
             icon.Dispose();
         }
     }
     return bitmap;
 }
Beispiel #21
0
        private static Image ExtractBestImageFromIco(byte[] pb)
        {
            List<GfxImage> l = UnpackIco(pb);
            if((l == null) || (l.Count == 0)) return null;

            long qMax = 0;
            foreach(GfxImage gi in l)
            {
                if(gi.Width == 0) gi.Width = 256;
                if(gi.Height == 0) gi.Height = 256;

                qMax = Math.Max(qMax, (long)gi.Width * (long)gi.Height);
            }

            byte[] pbHdrPng = new byte[] {
                0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A
            };
            byte[] pbHdrJpeg = new byte[] { 0xFF, 0xD8, 0xFF };

            Image imgBest = null;
            int bppBest = -1;

            foreach(GfxImage gi in l)
            {
                if(((long)gi.Width * (long)gi.Height) < qMax) continue;

                byte[] pbImg = gi.Data;
                Image img = null;
                try
                {
                    if((pbImg.Length > pbHdrPng.Length) &&
                        MemUtil.ArraysEqual(pbHdrPng,
                        MemUtil.Mid<byte>(pbImg, 0, pbHdrPng.Length)))
                        img = GfxUtil.LoadImage(pbImg);
                    else if((pbImg.Length > pbHdrJpeg.Length) &&
                        MemUtil.ArraysEqual(pbHdrJpeg,
                        MemUtil.Mid<byte>(pbImg, 0, pbHdrJpeg.Length)))
                        img = GfxUtil.LoadImage(pbImg);
                    else
                    {
                        MemoryStream ms = new MemoryStream(pb, false);
                        try
                        {
                            Icon ico = new Icon(ms, gi.Width, gi.Height);
                            img = ico.ToBitmap();
                            ico.Dispose();
                        }
                        finally { ms.Close(); }
                    }
                }
                catch(Exception) { Debug.Assert(false); }

                if(img == null) continue;

                if((img.Width < gi.Width) || (img.Height < gi.Height))
                {
                    Debug.Assert(false);
                    img.Dispose();
                    continue;
                }

                int bpp = GetBitsPerPixel(img.PixelFormat);
                if(bpp > bppBest)
                {
                    if(imgBest != null) imgBest.Dispose();

                    imgBest = img;
                    bppBest = bpp;
                }
                else img.Dispose();
            }

            return imgBest;
        }
Beispiel #22
0
        private void AddButtons(DesignerForm newDialog, XmlNodeList buttons)
        {
            foreach (XmlNode button in buttons)
            {
                try
                {
                    Button newButton = new Button();
                    SetControlAttributes(newButton, button);

                    if (button.Attributes["Icon"] != null &&
                        button.Attributes["Icon"].Value.ToLower() == "yes")
                    {
                        string binaryId = GetTextFromXmlElement(button);
                        try
                        {
                            using (Stream imageStream = GetBinaryStream(binaryId))
                            {
                                Bitmap bmp = new Icon(imageStream).ToBitmap();
                                Bitmap dest = new Bitmap((int)Math.Round(bmp.Width * scale), (int)Math.Round(bmp.Height * scale));

                                Graphics g = Graphics.FromImage(dest);
                                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                                g.DrawImage(bmp,
                                    new Rectangle(0, 0, dest.Width, dest.Height),
                                    new Rectangle(0, 0, bmp.Width, bmp.Height),
                                    GraphicsUnit.Pixel);

                                g.Dispose();
                                bmp.Dispose();

                                newButton.Image = dest;
                            }
                        }
                        catch
                        {
                            SetText(newButton, button);
                        }
                    }
                    else
                    {
                        newButton.FlatStyle = FlatStyle.System;
                        SetText(newButton, button);
                    }

                    newDialog.AddControl(button, newButton);
                }
                catch
                {
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Adds an alphablended icon or image to an existing imagelist from an external image or icon file.
        /// </summary>
        /// <param name="FileName">The full path to a 32bit alphablended file.</param>
        /// <param name="Imagelist">An existing imagelist to add the image or icon to.</param>
        /// <example>.FromFile( "C:\\file.ico", toolbarImagelist );</example>
        public static void AddFromFile( string fileName, ImageList destinationImagelist )
        {
            Bitmap bm = new Bitmap ( fileName );

            if ( bm.RawFormat.Guid == ImageFormat.Icon.Guid ) {
                Icon icn = new Icon ( fileName );
                destinationImagelist.Images.Add ( Path.GetFileName ( fileName ), Icon.FromHandle ( icn.Handle ) );
                icn.Dispose ( );
            } else {
                Add ( bm, destinationImagelist );
            }
            bm.Dispose ( );
        }
Beispiel #24
0
        /// <summary>
        /// Hides from Alt-TAB
        /// </summary>
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        // Turns on WS_EX_TOOLWINDOW style bit to hide from Alt-TAB list
        //        cp.ExStyle |= 0x80;
        //        return cp;
        //    }
        //}
        /// <summary>
        /// Creates tray icon from embedded to project icon. Throws execptions
        /// </summary>
        private void CreateFormIcons()
        {
            // Create tray icon
            Assembly asm = Assembly.GetExecutingAssembly();
            FileInfo fi = new FileInfo(asm.GetName().Name);
            using(Stream s = asm.GetManifestResourceStream(string.Format("{0}.av1.ico", fi.Name)))
            {
                // Create icon to be used in Form and Tray
                Icon icon = new Icon(s);

                Icon = new Icon(icon, icon.Size);

                _icon = new NotifyIcon();
                _icon.Visible = true;
                _icon.Icon = new Icon(icon, icon.Size);

                icon.Dispose();
            }
        }
Beispiel #25
0
 private void CreateIcon(String name, Icon icon)
 {
     using (Stream iconStream = new FileStream(name, FileMode.Create))
     {
         icon.Save(iconStream);
     }
     icon.Dispose();
 }
Beispiel #26
0
        private System.Windows.Media.ImageSource ConvertIconToImageSource(VistaTaskDialogIcon icon, bool isLarge)
        {
            System.Windows.Media.ImageSource iconSource = null;
            System.Drawing.Icon   sysIcon = null;
            System.Drawing.Bitmap altBmp  = null;

            try
            {
                switch (icon)
                {
                default:
                case VistaTaskDialogIcon.None:
                    break;

                case VistaTaskDialogIcon.Information:
                    sysIcon = System.Drawing.SystemIcons.Information;
                    break;

                case VistaTaskDialogIcon.Warning:
                    sysIcon = System.Drawing.SystemIcons.Warning;
                    break;

                case VistaTaskDialogIcon.Error:
                    sysIcon = System.Drawing.SystemIcons.Error;
                    break;

                case VistaTaskDialogIcon.Shield:
                    if (isLarge)
                    {
                        altBmp = new Bitmap(AssemblyHelper.GetEmbeddedResource("IExtendFramework.Controls.AdvancedMessageBox.Resources.shield-32.png"));
                    }
                    else
                    {
                        altBmp = new Bitmap(AssemblyHelper.GetEmbeddedResource("IExtendFramework.Controls.AdvancedMessageBox.Resources.shield-16.png"));
                    }
                    break;
                }

                if (sysIcon != null)
                {
                    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                        sysIcon.Handle,
                        System.Windows.Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                }
                else if (altBmp != null)
                {
                    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        altBmp.GetHbitmap(),
                        IntPtr.Zero,
                        System.Windows.Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                }
            }
            finally
            {
                if (sysIcon != null)
                {
                    sysIcon.Dispose();
                }
                if (altBmp != null)
                {
                    altBmp.Dispose();
                }
            }

            return(iconSource);
        }
 private Bitmap CreateDownArrow()
 {
     Bitmap bitmap = null;
     try
     {
         Icon icon = new Icon(typeof(BindingFormattingDialog), "BindingFormattingDialog.Arrow.ico");
         bitmap = icon.ToBitmap();
         icon.Dispose();
     }
     catch
     {
         bitmap = new Bitmap(0x10, 0x10);
     }
     return bitmap;
 }
Beispiel #28
0
        public static void Main()
        {
            var iconPath = Path.Combine(Application.StartupPath, "csFiler.ico");
            using (var icon = new Icon(iconPath))
            using (var commandMenu = new ToolStripMenuItem("コマンド入力"))
            using (var exitMenuItem = new ToolStripMenuItem("終了"))
            using (var contextMenu = new ContextMenuStrip())
            using (var taskTray = new NotifyIcon())
            using (var hotKeyLoop = new HotKeyMessageLoop())
            {
                taskTray.Icon = icon;
                taskTray.Text = "csFiler";
                taskTray.ContextMenuStrip = contextMenu;

                var openCommand = new HotKey(
                    new Action(() =>
                        {
                            var window = new FilerWindow();
                            window.WindowStartupLocation = Wpf.WindowStartupLocation.CenterScreen;
                            window.Show();
                        }),
                    Key.V, ModifierKeys.Windows);

                hotKeyLoop.Add(openCommand);

                contextMenu.Items.AddRange(
                    new ToolStripItem []
                    {
                        commandMenu,
                        exitMenuItem,
                    });
                contextMenu.Click += (sender, e) => openCommand.Action.Invoke();
                exitMenuItem.Click += (sender, e) => Wpf.Application.Current.Shutdown();

                var application = new Wpf.Application()
                {
                    ShutdownMode = Wpf.ShutdownMode.OnExplicitShutdown,
                };

                application.DispatcherUnhandledException += (sender, e) =>
                {
                    MessageBox.Show(
                        string.Concat("想定外のエラーが発生しました。",
                        Environment.NewLine, e.Exception.Message), "csFiler");
                    e.Handled = true;
                };

                application.Exit += (sender, e) =>
                {
                    hotKeyLoop.Dispose();
                    taskTray.Dispose();
                    contextMenu.Dispose();
                    exitMenuItem.Dispose();
                    commandMenu.Dispose();
                    icon.Dispose();
                };

                taskTray.Visible = true;
                application.Run();
            }
        }
 private Bitmap CreateDownArrow()
 {
     Bitmap bitmap = null;
     try
     {
         Icon icon = new Icon(typeof(PropertyGrid), "Arrow.ico");
         bitmap = icon.ToBitmap();
         icon.Dispose();
     }
     catch (Exception)
     {
         bitmap = new Bitmap(0x10, 0x10);
     }
     return bitmap;
 }
		private void CreateIcon(string path, bool useDefault = true) {
			var str = Legacy.UserSettings.ImageDir + @"\" + g.FileSafeTitle + ".ico";
			if (useDefault) {
				using (var stream = new FileStream(str, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
					Properties.Resources.icon.Save(stream);
					return;
				}
			}
			var icon = new Icon(path);
			using (var stream2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
				icon.Save(stream2);
				icon.Dispose();
			}
		}
Beispiel #31
0
        private Bitmap CreateDownArrow() {
            Bitmap bitmap = null;

            try
            {
                Icon icon = new Icon(typeof(PropertyGrid), "Arrow.ico");
                bitmap = icon.ToBitmap();
                icon.Dispose();
            }
            catch (Exception e)
            {
                Debug.Fail(e.ToString());
                bitmap = new Bitmap(16, 16);
            }
            return bitmap;
        }
Beispiel #32
0
        Image GetIcon(string file)
        {
            Icon ficon;
            WinAPI.SHFILEINFO shinfo = new WinAPI.SHFILEINFO();
            IntPtr ptr = WinAPI.SHGetFileInfo(file, WinAPI.FILE_ATTRIBUTE_NORMAL, ref shinfo, (uint)Marshal.SizeOf(shinfo), WinAPI.SHGFI_SYSICONINDEX);
            if (ptr == IntPtr.Zero) ficon = Icon.ExtractAssociatedIcon(file);
            else
            {
                int iconIndex = shinfo.iIcon;
                Guid iImageListGuid = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950");
                WinAPI.IImageList iml;
                int hres = WinAPI.SHGetImageList(0x04, ref iImageListGuid, out iml);
                IntPtr hIcon = IntPtr.Zero;
                hres = iml.GetIcon(iconIndex, 1, ref hIcon);
                ficon = System.Drawing.Icon.FromHandle(hIcon);
            }

            Image img;
            Icon temp = new Icon(ficon, 128, 128);
            img = temp.ToBitmap();
            temp.Dispose();
            ficon.Dispose();
            return img;
        }
Beispiel #33
0
        public static Icon GetIcon(byte[] bytes)
        {
            if (bytes == null)
                return null;

            if (bytes.Length == 0)
                return null;

            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            Icon icon = new Icon(stream);
            stream.Close();
            try
            {
                return (Icon)icon.Clone();
            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex);
            }
            finally
            {
                icon.Dispose();
            }
            return null;
        }
Beispiel #34
0
        public void ViewFile(string fileName)
        {
            try
            {
                /*
                ViewInWebBrowser.Visible = false;
                ViewInWebBrowser.Url = null;

                if (
                    fileName.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".docx", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".vsd", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".html", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".xls", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".ppt", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".pps", StringComparison.CurrentCultureIgnoreCase)
                    )
                {
                    ViewInWebBrowser.Visible = true;
                    ViewInWebBrowser.Url = new Uri(GitCommands.Settings.WorkingDir + fileName);
                    return;
                } else*/
                if (fileName.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".bmp", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".jpeg", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".ico", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".tif", StringComparison.CurrentCultureIgnoreCase) ||
                    fileName.EndsWith(".tiff", StringComparison.CurrentCultureIgnoreCase)
                    )
                {
                    Image image;

                    if (fileName.EndsWith(".ico", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Icon icon = new Icon(GitCommands.Settings.WorkingDir + fileName);
                        image = icon.ToBitmap();
                        icon.Dispose();
                    }
                    else
                    {
                        Image fileImage = Image.FromFile(GitCommands.Settings.WorkingDir + fileName);
                        image = (Image)fileImage.Clone();
                        fileImage.Dispose();
                    }

                    PictureBox.Visible = true;
                    TextEditor.Visible = false;

                    if (image.Size.Height > PictureBox.Size.Height ||
                        image.Size.Width > PictureBox.Size.Width)
                    {
                        PictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                    }
                    else
                    {
                        PictureBox.SizeMode = PictureBoxSizeMode.CenterImage;
                    }
                    PictureBox.Image = image;

                }
                else
                    if (fileName.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase) ||
                        fileName.EndsWith(".gif", StringComparison.CurrentCultureIgnoreCase) ||
                        fileName.EndsWith(".mpg", StringComparison.CurrentCultureIgnoreCase) ||
                        fileName.EndsWith(".mpeg", StringComparison.CurrentCultureIgnoreCase) ||
                        fileName.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase) ||
                        fileName.EndsWith(".avi", StringComparison.CurrentCultureIgnoreCase))
                    {
                        ClearImage();
                        PictureBox.Visible = false;
                        TextEditor.Visible = true;
                        TextEditor.Text = "Binary file: " + fileName;
                        TextEditor.Refresh();
                    }
                    else
                    {
                        ClearImage();
                        PictureBox.Visible = false;
                        TextEditor.Visible = true;

                        if (File.Exists(GitCommands.Settings.WorkingDir + fileName))
                            TextEditor.LoadFile(GitCommands.Settings.WorkingDir + fileName);
                    }
            }
            catch
            {
            }
        }
 public void Dispose()
 {
     _cachedIcon.Dispose();
 }