Click here to Skip to main content
12,396,606 members (33,185 online)
   

C#

 
AnswerRe: Minidumps. Pin
Eddy Vluggen18-May-13 8:44
mvpEddy Vluggen18-May-13 8:44 
GeneralRe: Minidumps. Pin
PHS24118-May-13 9:14
memberPHS24118-May-13 9:14 
QuestionSome Basic Help About A Modification In a Script! Pin
Jesús Frías18-May-13 6:17
memberJesús Frías18-May-13 6:17 
AnswerRe: Some Basic Help About A Modification In a Script! Pin
Dave Kreskowiak18-May-13 7:53
mvpDave Kreskowiak18-May-13 7:53 
AnswerRe: Some Basic Help About A Modification In a Script! Pin
Calvijn18-May-13 10:55
professionalCalvijn18-May-13 10:55 
Questionc@# Pin
MKS Khalid18-May-13 5:56
memberMKS Khalid18-May-13 5:56 
AnswerRe: c@# Pin
OriginalGriff18-May-13 6:00
protectorOriginalGriff18-May-13 6:00 
Questionc# Thumbnail Viewer Pin
Member 873647517-May-13 18:39
memberMember 873647517-May-13 18:39 
Hello,

I am beginner ( Noob ) in c#,
I am trying to make a small Asset browsing tool for myself, I just wanted to be sure if the way i am going is good or is there a better way to do it.

Currently I have 4 classes
ThumbViewer : extends FlowlayoutPanel
ThumbItem : extends Button
CacheManager.

I have overridden the paint method in the ThumbItem class and painting my Own way.

I also have a Background worker process which reads image file and gets thumbnail out if it and then assigns it to the Image property in the Button.


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.ComponentModel;
using System.Drawing.Imaging;
 
namespace Thumbnailer
{
    public class ThumbItem : Button
    {
        private BackgroundWorker bw;
        private string _fullfilename;
        private bool _ismouseover = false;
        private bool _isSelected = false;
        private const int THUMBNAIL_DATA = 0x501B;
        private ToolTip _btn_Tooltip;
        private bool isDisposed = false;
        private bool _itemvisiblecalled = false;
        private bool _itemnotvisiblecalled = false;
 
        #region Properties
        public string FullName
        {
            get { return _fullfilename; }
            set { _fullfilename = value; }
        }        
        public bool Selected
        {
            get { return _isSelected; }
            set { _isSelected = value; }
        }
        public Image FileIcon { get; private set; }
        public bool isVisible { get; set; }
        public string FileName { get; set; }
        #endregion        

        #region Constructor
        public ThumbItem()
        {           
            //Setthe Items properties
            this.Text = "PlaceHolder Thumb";
            this.Size = new Size(128, 144);
            this.Padding = new Padding(4);            
            this.BackColor = Color.Transparent;            
            this.Font = new Font("Verdana", 9, GraphicsUnit.Point);
            this.DoubleBuffered = true;
 
            //Set the background worker and its Handlers
            bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(BW_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BW_RunWorkerCompleted);           
        }
 
        public ThumbItem(string file)
            : this()
        {
            if (!File.Exists(file))
            {
                throw new FileNotFoundException("Specified file " + file + " doesnt exists.");
            }
            FileInfo fi = new FileInfo(file);
            this.Text = fi.Name.Replace(fi.Extension, "");
            this.FileName = fi.Name.Replace(fi.Extension, "");
            this.FullName = fi.FullName;                        
            bw.RunWorkerAsync();
        }
 
        ~ThumbItem()
        {
            if(!this.isDisposed)
            {
                bw.DoWork -= BW_DoWork;
                bw.RunWorkerCompleted -= BW_RunWorkerCompleted;
                this.bw.Dispose();
            }
        }
        #endregion        

        #region Background Worker
        private void BW_DoWork(object sender, DoWorkEventArgs e)
        {
            if (this._fullfilename != "")
            {                
                Image _thumbimg = null;
                Image _icon = null;
                FileInfo fi = new FileInfo(this._fullfilename);                
                if(fi.Extension == ".JPG")
                {
                    using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(this._fullfilename)))
                    {
                        using (Image img = Image.FromStream(ms))
                        {
                            if (CacheManager<Image>.CurrentInstance.isExists(this.FullName))
                            {
                                _thumbimg = CacheManager<Image>.CurrentInstance.GetByKey(this.FullName);
                            }
                            else
                            {
                                if (img != null)
                                {
                                    _thumbimg = img.GetThumbnailImage(64, 64, abort_callback, IntPtr.Zero);                                    
                                    CacheManager<Image>.CurrentInstance.Add(this.FullName, _thumbimg);
                                }
                            }
                        }                        
                    }
                }
                else
                {
                    _icon = Icon.ExtractAssociatedIcon(this.FullName).ToBitmap();
                }
                e.Result = new Image[] { _thumbimg, _icon };                
            }
        }
        private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {            
            this.Image = ((Image[])e.Result)[0];
            this.FileIcon = ((Image[])e.Result)[1];
            this.Invalidate();
        }
        #endregion       

        #region Painting Methods
        protected override void OnPaint(PaintEventArgs pevent)
        {                 
            //base.OnPaint(pevent);
            Graphics gfx = pevent.Graphics;
 
            StringFormat formatter = new StringFormat();
            formatter.LineAlignment = StringAlignment.Center;
            formatter.Alignment = StringAlignment.Center;
            Rectangle textrect = new Rectangle(0, (this.Height / 2) - (this.FontHeight / 2) - this.Padding.All, this.Width, this.Height);
                           
            Color fontcolor = Color.White;
            Rectangle parentbounds = this.Parent.Bounds;
 
            //Clear the Control Background with ts Parent Background COlor
            if (this.Parent != null)
            {
                gfx.Clear(this.Parent.BackColor);
            }
 
            if (((this.Bounds.Bottom - 10) < this.Parent.Bounds.Top) || (this.Bounds.Top - 10) > this.Parent.Bounds.Bottom)
            {
                if(!this._itemnotvisiblecalled)
                {
                    ItemNotVisible();
                }
            }
            else
            {
                if(!this._itemvisiblecalled)
                {
                    ItemVisible();
                }
            }           
 
            if(this.FileName == "IMG_0035")
            {
                Console.WriteLine("TEmp");
            }
 
            //If the Item is Selected the Colorize the Font to show Selection
            if (this.Selected)
            {
                gfx.FillRectangle(new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(25, 255, 255, 255), Color.FromArgb(150, 255, 255, 255), LinearGradientMode.Vertical), this.ClientRectangle);
            }
 
            //onMOuseHover Effects
            if (this._ismouseover)
            {
                gfx.FillRectangle(new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(25, 255, 255, 255), Color.FromArgb(100, 255, 255, 255), LinearGradientMode.Vertical), this.ClientRectangle);
            }
 
            //Draw the Broder
            Rectangle borderrect = this.ClientRectangle;
            ControlPaint.DrawBorder(gfx, borderrect, Color.FromArgb(100, 255, 255, 255), ButtonBorderStyle.Solid);
 
            //If the Image is Specified then Add that Image to Control            
            if (this.Image != null)
            {
                Rectangle imgrect = new Rectangle(this.Padding.All, this.Padding.All, (this.Width - (this.Padding.All * 2)), (this.Width - (this.Padding.All * 2)));
                gfx.DrawImage(this.Image, imgrect);
            }
            //Else Check if the Icon is Specified, if yes then Paint the Icon
            else if (this.FileIcon != null)
            {
                Rectangle iconrect = new Rectangle(((this.Width / 2) - 16), ((this.Height / 2) - 16), 32, 32);
                gfx.DrawImage(this.FileIcon, iconrect);
            }
 
            //Draw the Text on the Control
            string temp = this.Text;
            SizeF textsize = gfx.MeasureString(temp, this.Font);
            while (textsize.Width > this.Width / 1.5)
            {
                temp = temp.Remove(temp.Length - 1);
                textsize = gfx.MeasureString(temp, this.Font);
            }
            temp += "....";
            gfx.DrawString(temp, this.Font, new SolidBrush(fontcolor), textrect, formatter);        
        }
        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
            base.OnPaintBackground(pevent);            
        }
        #endregion

        #region Helper Methods
        public static Image ResizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;
 
            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
 
            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);
 
            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
 
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);
 
            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.Low;
 
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
 
            return (Image)b;
        }
        public void RefreshThumbnail()
        {
            this.Image = null;            
            while(!this.bw.IsBusy)
            {
                this.bw.RunWorkerAsync();
            }
        }
        private void ItemVisible()
        {
            this._itemvisiblecalled = true;
            this._itemnotvisiblecalled = false;
            //RefreshThumbnail();
        }
        private void ItemNotVisible()
        {            
            //this.Image = null;
            this._itemvisiblecalled = false;
            this._itemnotvisiblecalled = true;
        }
        private static bool HasJpegHeader(string filename)
        {
            using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
            {
                UInt16 soi = br.ReadUInt16();  // Start of Image (SOI) marker (FFD8)
                UInt16 jfif = br.ReadUInt16(); // JFIF marker (FFE0)

                return soi == 0xd8ff && jfif == 0xe0ff;
            }
        }
        #endregion

        #region Event Handlers
        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            this._ismouseover = true;
            if ( _btn_Tooltip == null)
            {
                _btn_Tooltip = new ToolTip();
                FileInfo fi = new FileInfo(this.FullName);
 
                string tooltiptext = "";
                tooltiptext += "FileName : "+fi.Name+"\n";
                tooltiptext += "Path : "+fi.FullName+"\n";
                tooltiptext += "Directory : " + fi.DirectoryName + "\n";
                _btn_Tooltip.SetToolTip(this, tooltiptext);
            }
        }
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            this._ismouseover = false;
        }
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
        }        
        #endregion        

        #region Event Methods
        #endregion

        #region UnUsed Methods
        private bool abort_callback()
        {
            return false;
        }
        #endregion

        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.ResumeLayout(false);
 
        }
    }
}

Can anyone please tell me if this is the best way to do it, if not then can you please guide me in right direction.

Thanks
Dinesh
AnswerRe: c# Thumbnail Viewer Pin
BillWoodruff17-May-13 20:42
memberBillWoodruff17-May-13 20:42 
GeneralRe: c# Thumbnail Viewer Pin
Member 873647518-May-13 5:44
memberMember 873647518-May-13 5:44 
GeneralRe: c# Thumbnail Viewer Pin
Dave Kreskowiak18-May-13 7:46
mvpDave Kreskowiak18-May-13 7:46 
GeneralRe: c# Thumbnail Viewer Pin
BillWoodruff19-May-13 2:05
memberBillWoodruff19-May-13 2:05 
GeneralRe: c# Thumbnail Viewer Pin
Member 873647519-May-13 4:16
memberMember 873647519-May-13 4:16 
QuestionFlashing form Pin
PozzaVecia17-May-13 12:28
memberPozzaVecia17-May-13 12:28 
AnswerRe: Flashing form Pin
Dave Kreskowiak17-May-13 17:34
mvpDave Kreskowiak17-May-13 17:34 
AnswerRe: Flashing form Pin
BillWoodruff17-May-13 20:17
memberBillWoodruff17-May-13 20:17 
GeneralRe: Flashing form Pin
PozzaVecia17-May-13 22:01
memberPozzaVecia17-May-13 22:01 
QuestionTimestamp Value in SQLServer Pin
abhi_here17-May-13 8:13
memberabhi_here17-May-13 8:13 
AnswerRe: Timestamp Value in SQLServer Pin
PIEBALDconsult17-May-13 8:43
professionalPIEBALDconsult17-May-13 8:43 
AnswerRe: Timestamp Value in SQLServer Pin
abhi_here29-May-13 4:34
memberabhi_here29-May-13 4:34 
AnswerRe: Timestamp Value in SQLServer Pin
jschell17-May-13 10:32
memberjschell17-May-13 10:32 
GeneralRe: Timestamp Value in SQLServer Pin
PIEBALDconsult17-May-13 11:04
professionalPIEBALDconsult17-May-13 11:04 
QuestionDifferent behaviour from button in MDI parent and button in child form Pin
FRotondo17-May-13 4:09
memberFRotondo17-May-13 4:09 
AnswerRe: Different behaviour from button in MDI parent and button in child form Pin
Simon_Whale17-May-13 10:21
professionalSimon_Whale17-May-13 10:21 
GeneralRe: Different behaviour from button in MDI parent and button in child form Pin
FRotondo17-May-13 22:12
memberFRotondo17-May-13 22:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.


Advertise | Privacy | Mobile
Web01 | 2.8.160721.1 | Last Updated 25 Jul 2016
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid