Skip to content


Adding new looks / functionality to exsiting .NET controls - ListBox.

So I am starting a series of posts that involves extending the default .NET controls to add new looks as well as new functionality. Today we will be extending the ListBox, so let’s get started.

The new listbox that we will create will have a main text or title and a description text below it as well as the ability to add an image on the control.

To get started we will create a class which I will name ListBoxItem which will contain the new properties that will be added to the control (Title, description, image).

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Drawing;
  5.  
  6. namespace ListBoxEx
  7. {
  8.     public class ListBoxItem
  9.     {
  10.         Image image;
  11.         string text;
  12.         string desc;
  13.  
  14.         public Image Image
  15.         {
  16.             get
  17.             {
  18.                 return image;
  19.             }
  20.             set
  21.             {
  22.                 image = value;
  23.             }
  24.         }
  25.  
  26.         public string Text
  27.         {
  28.             get
  29.             {
  30.                 return text;
  31.             }
  32.             set
  33.             {
  34.                 text = value;
  35.             }
  36.         }
  37.  
  38.  
  39.         public string Desc
  40.         {
  41.             get
  42.             {
  43.                 return desc;
  44.             }
  45.             set
  46.             {
  47.                 desc = value;
  48.             }
  49.         }
  50.     }
  51. }

So now that we got that done we can get started with the ListBox itself. We are going to create a class to extend the original ListBox control.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Drawing;
  5. using System.Drawing.Drawing2D;
  6. using System.Windows.Forms;
  7.  
  8. namespace ListBoxEx
  9. {
  10.     public class ListBoxEx : ListBox
  11.     {
  12.        
  13.     }
  14. }

Now lets start with the ListBoxEx class. Firstly we will add a constructor to the class and we will set the ItemHeight in it. We could set the ItemHeight dynamically by using the combined height of the strings or the height of the image.

  1. public ListBoxEx()
  2. {
  3.     this.ItemHeight = 35;
  4. }

Now lets write the method that sets up the drawing of the items.
What we will do here is firstly check that we have a valid index if so then select the currently active item. After that we are going to check if it is selected or not then draw either a gradient background or the standard background. Then draw the image if one is used then the text.

  1. protected override void OnDrawItem(DrawItemEventArgs e)
  2. {
  3.     //Lets grab are current item from the list of items, as well as check to see
  4.     //that we actually have a valid index for are item.
  5.  
  6.     if (this.Items.Count > 0)
  7.     {
  8.         ListBoxItem item = (ListBoxItem)this.Items[e.Index];
  9.         Color textColor = this.ForeColor;
  10.         bool isUsingImage = false;
  11.         int textMargin = 2;
  12.  
  13.         //Check to see that we actually have an image.
  14.         if (item.Image != null)
  15.             isUsingImage = true;
  16.  
  17.         e.DrawFocusRectangle();
  18.  
  19.         //Draw are graident background if the control is selected otherwise the standard background.
  20.         if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
  21.         {
  22.             e.Graphics.FillRectangle(new LinearGradientBrush(new Point(0, 0), new Point(0, this.ItemHeight),
  23.                 Color.LightSkyBlue, Color.LightSteelBlue), e.Bounds);
  24.             textColor = Color.White;
  25.         }
  26.         else
  27.         {
  28.             e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds);
  29.         }
  30.  
  31.         //Draw are image if one is being used then draw the text.
  32.         if (isUsingImage)
  33.         {
  34.             Rectangle imgRect = new Rectangle();
  35.             imgRect.Location = new Point(2, (e.Bounds.Y + 2));
  36.             imgRect.Size = new Size(20, 20);
  37.  
  38.             e.Graphics.DrawImage(item.Image, imgRect);
  39.             textMargin = 26;
  40.         }
  41.  
  42.         //We can extend this even further by using the TextRender class and be able to add an ellipsis to are strings if they go beyond the
  43.         //edge of the control and all sorts of other nifty things.
  44.         e.Graphics.DrawString(item.Text, new Font(this.Font.FontFamily, 10, FontStyle.Regular),
  45.             new SolidBrush(textColor), new PointF(textMargin, (e.Bounds.Y + 2)));
  46.         e.Graphics.DrawString(item.Desc, this.Font, new SolidBrush(textColor), new PointF(textMargin, (e.Bounds.Y + 20)));
  47.     }
  48.  
  49.     base.OnDrawItem(e);
  50. }

Here is the result of what I got as well as the download of the project and code.

ListBoxEx Screenshot

ListBoxEx Screenshot

ExtendedControls - ListBoxEx (55)

Posted in .NET, C#, Software, code..

Simple background removal with PHP and GD.

I haven’t posted in awhile, but I got a short, article on background removal in images using PHP and the GD image library.

The way I did this is take a specified image and a specified color to look for as well as a difference or a maximum difference in each color allowed. After that it will take the values entered for each of the items just listed and go through each pixel looking for the colors in the range specified. If the pixel color is not within range, it set’s the color to white, or black depending on the color you are looking for. Anyhow here are the functions which do this.

Firstly HexToRGB which will turn an Hexadecimal color value to RGB integer values.

  1. function HexToRGB($hex) {
  2.         $hex = str_replace("#", "", $hex);
  3.         $colors = array();
  4.        
  5.         if(strlen($hex) == 3) {
  6.             $colors['r'] = hexdec(substr($hex, 0, 1) . $r);
  7.             $colors['g'] = hexdec(substr($hex, 1, 1) . $g);
  8.             $colors['b'] = hexdec(substr($hex, 2, 1) . $b);
  9.         }
  10.         else if(strlen($hex) == 6) {
  11.             $colors['r'] = hexdec(substr($hex, 0, 2));
  12.             $colors['g'] = hexdec(substr($hex, 2, 2));
  13.             $colors['b'] = hexdec(substr($hex, 4, 2));
  14.         }
  15.         $colors;
  16.     }

Last is the RemoveBackground function, which is the one that does all the hard work. It scans the image and removes unwanted colors. But is quite and simple function. As of right now it just draws the image to the browser as a png, but that is easily modified.

You will have to play around with the difference when calling the RemoveBackground function to get your desired results.

  1. function RemoveBackground($image, $foregroundColor, $difference = 0) {
  2.         if(file_exists($image)) {
  3.             list($width, $height, $type) = getimagesize($image);
  4.             $ext = strtolower(array_pop(explode(".", $image)));
  5.             $img = null;
  6.            
  7.             switch($ext) {
  8.                 case "jpg":
  9.                 case "jpeg":
  10.                     $img = imagecreatefromjpeg($image);
  11.                     break;
  12.                 case "png":
  13.                     $img = imagecreatefrompng($image);
  14.                     break;
  15.                 case "gif":
  16.                     $img = imagecreatefromgif($image);
  17.                     break;
  18.                 case "bmp":
  19.                     $img = imagecreatefromwbmp($image);
  20.                     break;
  21.                 case "xbm":
  22.                     $img = imagecreatefromxbm($image);
  23.                     break;
  24.                 case "xpm":
  25.                     $img = imagecreatefromxpm($image);
  26.                     break;
  27.             }
  28.            
  29.             if($img != null) {
  30.                 list($r, $g, $b) = HexToRGB($foregroundColor);
  31.                 $color = imagecolorallocate($img, $r, $g, $b);
  32.                 $white = imagecolorallocate($img, 255, 255, 255);
  33.                 $black = imagecolorallocate($img, 0, 0, 0);
  34.                
  35.                 for($x = 0; $x < $width; $x++) {
  36.                     for($y = 0; $y < $height; $y++) {
  37.                         $pixelColor = imagecolorat($img, $x, $y);
  38.                         $pixelR = ($pixelColor >> 16) & 0xFF;
  39.                         $pixelG = ($pixelColor >> 8) & 0xFF;
  40.                         $pixelB = $pixelColor & 0xFF;
  41.                        
  42.                         if($pixelR < ($r - $difference) || $pixelR > ($r + $difference) ||
  43.                             $pixelG < ($g - $difference) || $pixelG > ($g + $difference) ||
  44.                             $pixelB < ($b - $difference) || $pixelB > ($b + $difference)) {
  45.                             if($color != $white) {
  46.                                 imagesetpixel($img, $x, $y, $white);
  47.                             }
  48.                             else {
  49.                                 imagesetpixel($img, $x, $y, $black);
  50.                             }
  51.                         }
  52.                         else {
  53.                             imagesetpixel($img, $x, $y, $pixelColor);
  54.                         }
  55.                     }
  56.                 }
  57.                 header("Content-Type: image/png");
  58.                 imagepng($img, null);
  59.             }
  60.         }
  61.     }

It is a simple as that. Below is a zip file containing the functions above, as well as a test image.
Background Removal (116)

Posted in PHP, Software, code..

Fuzzy array search using PHP.

Update on the fuzzy string search with PHP article. I’ve seen a few searches from Google of people try to find out how to do a fuzzy / approximate string search against array values, well today I have the class for doing just that.

The class is simple to use.
It also does multi-level searching, so embed the arrays as far as you want.

  1. <?php
  2.     include "FuzzyArraySearch.php";
  3.     $search = new ArraySearch("test", array("pest");
  4.     $search->Search();
  5.     $search->GetResults();
  6. ?>

As a quick example, the following array.

  1. array("rest", "string", "blah", array("hello", array("again", array(array(array("reset"), "rest"))), "pest"))

Output the following when var_dumping the results.

  1. array
  2.   0 => string 'rest at Base->0' (length=15)
  3.   1 => string 'reset at Base->3->1->1->0->0->0' (length=31)
  4.   2 => string 'rest at Base->3->1->1->0->0->1' (length=30)
  5.   3 => string 'pest at Base->3->1->2' (length=21)

Quite simple. Anyhow, that is all I wanted to post, the download link is just below.

Fuzzy Array Search (140)

Posted in Uncategorized.

SimpleMail - Easily send email’s with attachments from php.

Here is a pretty simple class that uses the default mail function so no sockets or direct connections to server’s
have to be used. But this script will allow you to add multiple contacts, as well as multiple attachments, easily.

It is as simple as this.

  1. <?php
  2.     include "SimpleMail.php";
  3.     $mail = new SimpleMail("test@domain.com", "test@test.com", "This is a test message");
  4.    
  5.     $msg = "This is a quick test message, just sending some attachments\n";
  6.     $msg.= "with this test email, yeah";
  7.    
  8.     $mail->AddMessage($msg);
  9.     $mail->AddAttachment("test.txt");
  10.     $mail->AddAttachment("test.png");
  11.     $mail->AddAttachment("test.jpg");
  12.    
  13.     if($mail->SendMessage()) {
  14.         echo "Your message was sussecfully sent";
  15.     }
  16.     else {
  17.         echo "Your message failed to send, please try again later";
  18.     }
  19. ?>

Hope someone finds it useful, enjoy.
SimpleMail (141)

Posted in PHP, Software, code..

Create image preview of textfile with PHP and the GD library.

This will be a small tutorial on how to create preview images / thumbnails of textfiles using PHP and the built-in GD library.
Note: This tutorial requires that you have GD2+ with Freetype support.

Ok so lets get started. This is actually quite an easy task, the basic idea is that we read in the lines of the
textfile convert tabs to spaces, and then draw each line to the image file we have created, easy huh?

First things first lets create the function name and arguments.

  1. function FileToThumb($textSource, $thumbDest, $width, $height, $useEntireFile) {
  2.  
  3. }

Ok we now have are function and are ready to start adding code, but first a brief overview of
what each argument is for.

$textSource - The textfile to read from.
$thumbDesc - The path to save the image, use null to display in browser.
$width - The width of the image.
$height - The height of the image.
$useEntireFile - Use the entire file for the preview or just the first few lines.

Now that we have got that out of the way, lets start adding are code.
Firstly we will want to check a couple of arguments, as well as checking for are
fontfile.

  1. if(file_exists($textSource) && is_readable($textSource) && file_exists("arial.ttf")) {
  2.         if($useEntireFile)
  3.             $fontSize = 4;
  4.         else
  5.             $fontSize = 7;

Ok that will check that the text file and font file exists as well ad checking whether of not
the text file is readable.

Now we can load are text file, get the maximum number of lines to draw
and set up are image and colors.

  1. $lines = file($textSource);
  2. $lineHeight = ($fontSize + 2);
  3. $maxLines = ($height / $lineHeight);
  4.  
  5. $thumb = imagecreatetruecolor($width, $height);
  6. $black = imagecolorallocate($thumb, 0, 0, 0);
  7. $white = imagecolorallocate($thumb, 255, 255, 255);
  8. imagefill($thumb, 0, 0, $white);

Ok now all that is left is to draw the lines and save the image.

  1. for($i = 1; $i < $maxLines + 1; $i++) {
  2.             $line = str_replace("\t", "    ", $lines[$i]);
  3.             imagettftext($thumb, $fontSize, 0, 2, ($i * $lineHeight), $black, "arial.ttf", $line);
  4.         }
  5.        
  6.         if(!imagepng($thumb, $thumbDest)) {
  7.             return false;
  8.         }
  9.         return true;

Ok and there it is, I used png because png is the better format for save images which contain a lot of text.
But now you probably want the whole thing, so here you go.

  1. <?php
  2. /*
  3.     FileToThumb - Creates a thumbnail preview of a textfile.
  4.     arg1 = textfile to create preview of.
  5.     arg2 = destination of thumbnail preview. (Use null to display to browser)
  6.     arg3 = width of thumbnail.
  7.     arg4 = height of thumbnail.
  8.     arg5 = true or false for using the entire file or the first few
  9.         lines for the thumbnail.
  10. */
  11.  
  12. function FileToThumb($textSource, $thumbDest, $width, $height, $useEntireFile) {
  13.     if(file_exists($textSource) && is_readable($textSource) && file_exists("arial.ttf")) {
  14.         if($useEntireFile)
  15.             $fontSize = 4;
  16.         else
  17.             $fontSize = 7;
  18.        
  19.         $lines = file($textSource);
  20.         $lineHeight = ($fontSize + 2);
  21.         $maxLines = ($height / $lineHeight);
  22.        
  23.         $thumb = imagecreatetruecolor($width, $height);
  24.         $black = imagecolorallocate($thumb, 0, 0, 0);
  25.         $white = imagecolorallocate($thumb, 255, 255, 255);
  26.         imagefill($thumb, 0, 0, $white);
  27.        
  28.         for($i = 1; $i < $maxLines + 1; $i++) {
  29.             $line = str_replace("\t", "    ", $lines[$i]);
  30.             imagettftext($thumb, $fontSize, 0, 2, ($i * $lineHeight), $black, "arial.ttf", $line);
  31.         }
  32.        
  33.         if(!imagepng($thumb, $thumbDest)) {
  34.             return false;
  35.         }
  36.         return true;
  37.     }
  38. }
  39. ?>

Here is a simple example of the output of the function using this statment.

  1. FileToThumb("test.txt", "test.png", 80, 120, false);

test

There is your ready to use function for creating image previews of textfiles, enjoy.

Posted in PHP, Software, code..

Simple Fuzzy Search with PHP

Approximate string search or Fuzzy string search, can be a difficult task if you have a very sophisticated searching / matching algorithm. So today I will show you a quite simple Fuzzy string search and use it to create a small efficient search application.

The CompareStrings method that we have ready is what we check a word against our search and give us back a value of difference (or threshold) from our search and the word we are checking. It does this by first checking each character while also checking for case insensitive or not, any difference in case if it applies or the character will add one to the threshold. We then check the length and add one for each single character difference in length. After all that we return the threshold and from there we can check the threshold to see if the word is something we want to keep and do something with. So before we do anything else, lets take a look at the CompareStrings function / method.

  1. function CompareStrings($str1, $str2, $caseInsensitive = false) {
  2.  $threshold = 0;
  3.  
  4.  if(strlen($str1) != strlen($str2)) {
  5.   if(strlen($str1) > strlen($str2)) {
  6.    $threshold = strlen($str1) - strlen($str2);
  7.   }
  8.   else if(strlen($str2) > strlen($str1)) {
  9.    $threshold = strlen($str2) - strlen($str1);
  10.   }
  11.  }
  12.  
  13.  for($i = 0; $i < strlen($str1); $i++) {
  14.   if($i <= strlen($str2) - 1) {
  15.    if($caseInsensitive) {
  16.     if(strtolower($str1{$i}) != strtolower($str2{$i})) {
  17.      $threshold++;
  18.     }
  19.    }
  20.    else {
  21.     if($str1{$i} != $str2{$i}) {
  22.      $threshold++;
  23.     }
  24.    }
  25.   }
  26.  }
  27.  return $threshold;
  28. }

So you can now see how it checks words, it’s not really difficult but also could be much more intelligent. So now lets start with our search method, “PreformSearch”. This will be a simple method that just checks the threshold and if it is within are acceptable limits we will store the word in an array, after we have sorted through the entire string we then return the array.

First lets set up the method and it’s arguments, as well as are array to store are matches.

  1. function PreformSearch($search, $string, $threshold = 1, $caseSensitive = false) {
  2.  $matches = array();
  3. }

Ok we have that now lets start adding some searching abilities into are new function / method.
We are going to check that the string to search is actually a string and is longer then 0 characters.

  1. if(isset($string) &amp;&amp; strlen($string) > 0) {
  2.  
  3. }
  4. return $matches;

Now that is out of the way, we can now break up the string, loop though it and check for are matches.

  1. $words = explode(" ", $this->string);
  2.  
  3. foreach($words as $word) {
  4.         if(CompareStrings($search, $word, $caseInsensitive) <= $threshold) {
  5.                 $matches[] = $word;
  6.         }
  7. }

There, that is all that is needed, so lets see the whole thing all together.

  1. function PreformSearch($search, $threshold = 1, $caseSensitive = false) {
  2.  $matches = array();
  3.  
  4.  if(isset($this->string) &amp;&amp; strlen($this->string) > 0) {
  5.   $words = explode(" ", $this->string);
  6.  
  7.   foreach($words as $word) {
  8.    if(CompareStrings($search, $word, $caseInsensitive) <= $threshold) {
  9.                                 $matches[] = $word;
  10.                         }
  11.   }
  12.  }
  13.  return $matches;
  14. }

and there it is. That is all that is needed for a very simple fuzzy string search using PHP.
So as you can see the above functions give you a base to start a much more sophisticated search then what is seen
here.

Below is a download to a FuzzySearch class, and a couple of test’s using it.

Fuzzy Search for PHP (166)

Posted in PHP, Software.

SpellChecker.

I am currently in the process of writing my own spell checking library, pretty much just because it’s a good learning experince and because I can. Anyway it seems to work pretty good so far, it is quite simple though uses the following steps to accomplish spell checking.

  1. Check current word in dictionary/list of words.
  2. If no exact match is found(case insensitive or not) then it starts matching.
  3. Matching the words involves going though each word in list and comparing the strings.
  4. Strings are compared by a CompateStrings method that rates string2 against string1 on a 100 point scale.
  5. Words that come withing a certain point limit of string1 will be added to a list of possible suggestions and returned.

This all seems to work pretty good, quite quickly for how it does it, but then I have not done any 10,000+ word dictionary / list searches yet, but I will soon and update with some speed results.

But back to the CompareStrings method, this method gives both strings 100 points, and rates string2 against string1 it first gets how many points each char are worth, afterwards compares each char in string1 to string2 a certain points per char are lost for each character that does not match, afterwards it checkers for the lengths and then multiplies the points per char to the difference in chars and returns the score that string2 got. Pretty simple, but pretty effective so far.

Anyways I will post a downlod to the current version quite soon, I have still got to implement a couple of things, maybe also make suggestion searches a little better.

Posted in .NET, C#, Software, code..

NotificationBar - Free .NET control.

So I got a free control here for you. It is a pretty simple control, completly in C#. It is a notification/information bar, like that found in IE when you try to download something.

NotificationBar Example.Screenshot of notification bar and demo under linux.

Features of this control include.

  • LGPL License.
  • Easy to use.
  • Works on Mono.
  • Automatically resizes to fit text.
  • Can play system sound when shown.
  • Can flash control any number of times for any number of milliseconds.
  • Can show a ContextMenuStrip when clicked.
  • Useful for when you don’t want to show a MessageBox but want to give the user some info.
  • Uses .NET 2.0.
  • Written in C#.

It comes with a demo project and you can download it here - NotificationBar.zip (350)

Posted in .NET, C#, Software, code..

Hello world!

Well, here is my first post on my new blog / site (Code for thought).

So to get started, my name is Cory. I like to write code, dabble in electronics and mostly anythng that has to do with computers. On this blog in future posts you will find things such as C#/.NET code as well as controls for .NET. You may also find some PHP, C/C++, as well as just other random topics.

So welcome and hopefully you’ll come back later for more.

Posted in Personal, Uncategorized. Tagged with , , , , .