Updates from April, 2010 Toggle Comment Threads | Keyboard Shortcuts

  • Ali BaderEddin 12:24 am on April 16, 2010 Permalink | Reply  

    OpenGL Frame Rate 

    Calculating the frames per second in our Graphics application makes sense when we are displaying animation, which is simply a collection of images displayed rapidly and in sequence.When we watch a video\movie, the usual number of frames displayed in a second is 24. Our eyes can’t see all the 24 frames one by one in a single second, and that’s why we get the illusion of something moving, rotating, or growing in size.

    In this post, we are going to create an OpenGL app that animates an object and calculates the frames per second for that animation.


    To make this calculation, we need to find a way to keep track of the number of frames and time elapsed. The key here is to do the calculation in the GLUT idle function (callback function passed to glutIdleFunc), which is called only when our application is not busy doing something else (such as drawing the current frame). So every time the idle function is called, we increment the frame count, check the time elapsed, and if the time is greater than or equal to 1 second, we calculate the FPS.

    //  This function is called when OpenGL\GLUT is not working on
    //  something else... It is mainly used for animation...
    //  It's like the timers but time intervals are dependent on how busy
    //  the app is, instead of having a constant value set by the user.
    void idle (void)
        //  Animate the object
        //  Calculate FPS
        //  Call display function (draw the current frame)
        glutPostRedisplay ();

    As you can see in the code above, the idle function is animating the object, calculating the FPS, then triggering the display function (callback function passed to glutDisplayFunc) by calling glutPostRedisplay().

    The display function would basically display the object and text showing the FPS value.

    //  This function is passed to glutDisplayFunc in order to display
    //	OpenGL contents on the window.
    void display (void)
        glClear (GL_COLOR_BUFFER_BIT);
        glutSwapBuffers ();

    To get the time elapsed, we use the glutGet(GLUT_ELAPSED_TIME) function which will get the time passed in milliseconds since the program started or since it was last called. The implementation of calculateFPS would look like this:

    // Calculates the frames per second
    void calculateFPS()
        //  Increase frame count
        //  Get the number of milliseconds since glutInit called
        //  (or first call to glutGet(GLUT ELAPSED TIME)).
        currentTime = glutGet(GLUT_ELAPSED_TIME);
        //  Calculate time passed
        int timeInterval = currentTime - previousTime;
        if(timeInterval > 1000)
            //  calculate the number of frames per second
            fps = frameCount / (timeInterval / 1000.0f);
            //  Set time
            previousTime = currentTime;
            //  Reset frame count
            frameCount = 0;

    Download full source code here. If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library. Toby Howard has a different implementation that is not dependent on GLUT. You can find it here.

    • Omar Ayman 8:03 am on March 31, 2011 Permalink | Reply

      Thanks.. This was really helpful !!

    • Matt Langston 7:40 pm on April 15, 2012 Permalink | Reply

      This was extremely helpful. I am using your code in my openCL final project and have given credit where credit is due in both the source and presentation. Thanks again!

    • To Select your best choice Click Here 3:21 am on July 14, 2014 Permalink | Reply

      It is truly a nice and helpful piece of information. I’m glad that you shared this useful ino with us.
      Please keep us up to date like this. Thanks for sharing.

    • storage businesses for sale in california 3:54 pm on July 16, 2014 Permalink | Reply

      Finding the right house for your family means finding the best nest will
      help you to take care of your kids better.
      In fact you may just adore the procedure of moving.
      They usually provide long distance mover provides services to the
      customer who wants it from them.

    • magnetic screen door as seen on tv 5:37 pm on July 18, 2014 Permalink | Reply

      Howdy! Do you use Twitter? I’d like to follow you if that would be okay.
      I’m definitely enjoying your blog and look forward to new updates.

    • games math 7:32 pm on July 26, 2014 Permalink | Reply

      When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment.
      Is there any way you can remove me from that service?
      Thanks a lot!

    • http://classyowner9750.webs.com/apps/blog 8:05 pm on August 1, 2014 Permalink | Reply

      My spouse and I stumbled over here from a different web address and thought
      I might as well check things out. I like what I see so i
      am just following you. Look forward to finding out about your web
      page for a second time.

    • Latest Android and iOS Game Hacks 2:17 pm on August 10, 2014 Permalink | Reply

      Is there a web site that makes it simple to follow websites and podcasts?
      I don’t have an iPod, does that matter?.

    • receivables funding 6:35 am on August 11, 2014 Permalink | Reply

      When I lived in Britain, my kitchen was full of labour-saving devices,
      but some of the things I used to use just once a month over there, I now see being used every day.
      For those who love cooking but hate the clean-up involved the Scrap Trap is an great tool to keep your counters and floor
      sparkling and uncluttered. These are the essential piece
      of kit to help you quickly mix dough, cream and cake ingredients, and they are available with
      a variety of speeds and attachments to help you get the job done.

    • Cartier Jewelry Replica 9:32 am on August 17, 2014 Permalink | Reply

      of course like your web-site however you need to check the spelling on quite
      a few of your posts. Many of them are rife with spelling
      problems and I in finding it very bothersome to
      tell the truth nevertheless I’ll surely come back again.

    • best kitchen Knives for everyday use 2:22 pm on August 17, 2014 Permalink | Reply

      Try the chef-tested and approved Kyocera ceramic knives (Seattle chefs use tnem at
      home and at work). ca to learn about andd order superior custom granite.
      This being a Square-Enix game, you have something aakin too a
      limit break iin Finhal Fantasy.

    • Comment pirater un compte facebook 3:27 pm on August 21, 2014 Permalink | Reply

      I simply couldn’t depart your website before suggesting that I really enjoyed the usual info a person supply on your guests?
      Is going to be again often to inspect new posts

    • sunloungers.soulcast.com 4:16 am on August 24, 2014 Permalink | Reply

      Wonderful website, just lately been scouting forever for tips
      on the best rattan furnishings for our home and in our patio.
      This website truly helpedgreat blog some great info here

    • steam shower kit 4:17 pm on August 24, 2014 Permalink | Reply

      we not long ago set up our steam shower unit, the best thing we have purchased
      for some time, kids and family members like it so much, simply cannot
      see everyone going back to regular showers ever again

    • Fidelia 2:14 am on August 25, 2014 Permalink | Reply

      Hello my family member! I wish to say that this post is amazing, great written and include approximately all significant infos.
      I would like to see more posts like this .

    • rewards chart 6:58 am on August 26, 2014 Permalink | Reply

      He actually created the Nakshatras, thuus these natives seem to be all knowing andd knmow things witout any methodical practice.
      In thhis stage future members will think about what may be expected off
      tjem when they join the team. The trader ccan run this process
      simultaneously as he will purchase again the US Dollars when the price of
      US Dollars come again at the level which is equal to or lower than 80.

    • top green superfood powder 1:14 am on August 28, 2014 Permalink | Reply

      I got this site from my pal who told me about this website and now this time I am visiting this website and reading very informative posts
      at this time.

    • Alphonso 5:15 am on September 1, 2014 Permalink | Reply

      Yesterday, while I was at work, my sister stole my iphone and tested to
      see if it can survive a forty foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and
      she has 83 views. I know this is entirely off topic but I had to share it with someone!

    • drakopoulos-law.com 7:11 pm on September 2, 2014 Permalink | Reply

      I will right away seize your rss feed as I can’t find
      your e-mail subscription link or newsletter service. Do you have
      any? Please allow me know in order that I could subscribe.


    • football 7:23 pm on September 5, 2014 Permalink | Reply

      I honestly believe that Adrian Peterson, Arian Foster, Ray
      Rice, Marshawn Lynch, or Jamaal Charles should be your focus in the first round.
      The different types of defensive football positions are:
      . There are some excellent websites that offer live football matches, as well as live match scores,
      for one low price.

    • arbonne skin care 5:38 pm on September 6, 2014 Permalink | Reply

      Hello there! Quick question that’s totally off topic.
      Do you know how to make your site mobile friendly? My blog looks weird when browsing from my
      iphone. I’m trying to find a theme or plugin that might be able to resolve this issue.
      If you have any suggestions, please share. Thanks!

    • best coffee maker with grinder and thermal Carafe 5:41 pm on September 6, 2014 Permalink | Reply

      After looking into a number of the articles on your blog, I honestly like your way of blogging.
      I saved as a favorite itt to my bookmark webpage list and will be checking back soon. Please
      visit my web site as well and let me know what you think.

    • intranet.kdvdeluchtballon.nl 9:04 pm on September 8, 2014 Permalink | Reply

      What’s Taking place i am new to this, I stumbled upon this I have found It positively helpful and it has
      aided me out loads. I hope to give a contribution & aid other users like its helped me.
      Great job.

    • Angelita 6:49 pm on September 11, 2014 Permalink | Reply

      Thank you a lot for sharing this with all
      people you actually understand what you are talking about! Bookmarked.
      Kindly also discuss with my web site =).
      We could have a hyperlink change contract among us

    • Running Shoe Reviews - Sports Shoes Direct - Womens running shoes Top running shoes 10:00 pm on September 11, 2014 Permalink | Reply

      What i do not understood is in fact how you’re no longer actually a
      lot more neatly-liked than you might be now.
      You’re very intelligent. You understand thus significantly
      on the subject of this matter, produced me individually consider it from a lot of numerous angles.
      Its like men and women are not fascinated unless it’s one thing to
      accomplish with Lady gaga! Your personal stuffs outstanding.
      Always deal with it up!

    • Boca Raton CPA masks 7:53 pm on September 14, 2014 Permalink | Reply

      Lawyer or attorney Victorianne Musonza, Lawyer At Laws, Licensed in NY And
      NC, Maxwell Law Office, PLLC is accepted to rehearse rules
      in Rhode – Tropical isle and Massachusetts, so the Federal government
      Section Courts, which is a member of the Pub
      of the us Superior Court. When working under GAAP, revenues and gains have completely
      separate definitions. This method pts are crucial inside working with a defined talent management

    • Option Domination Review 10:59 pm on September 15, 2014 Permalink | Reply

      Currently itt sounds like Expression Engine is the
      preferred blogging platform available right now.

      (from what I’ve read) Is that what youu are using on your blog?

    • cost of dental implants 5:07 am on September 16, 2014 Permalink | Reply

      Excellent way of explaining, and good post to take data
      concerning my presentation subject matter, which i am
      going to present in institution of higher education.

    • personal finance blogs 2013 6:09 pm on September 20, 2014 Permalink | Reply

      After exploring a handful of the articles on your web site,
      I seriously like your way of blogging. I saved as a favorite
      it to my bookmark webpage list and will be checking back in the near future.
      Please visit my website as well and let me know what you think.

    • personal finance software for mac 5:47 am on September 21, 2014 Permalink | Reply

      Hey there! I’ve been reading your web site for a while now and finally got the
      bravery to go ahead and give you a shout out from Houston Tx!
      Just wanted to say keep up the good work!

    • Binary Options Trading 2:01 am on September 23, 2014 Permalink | Reply

      Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up what I
      submitted and say, I’m thoroughly enjoying
      your blog. I as well am an aspiring blog blogger but I’m still new to
      everything. Do you have any tips for first-time blog writers?
      I’d certainly appreciate it.

    • family guy the quest for stuff hack 4:27 am on September 26, 2014 Permalink | Reply

      Is your Family Guy The Quest for Stuff Hack is a ‘survival mode’ type Family Guy The
      Quest for Stuff Hack or an ‘endless runner’. In the case of Star Conflict, it seems those who invest the money get a better ‘head start’ on those who don’t.
      Spring, summer, and even fall birthday parties in N.

    • whirlpool steam shower 3:07 pm on September 27, 2014 Permalink | Reply

      Had been in actual fact searching for just an average shower enclosures before I uncovered this page,
      didn’t even know there were any such thing as a ‘steam shower
      enclosure’, really, may very well just have to have one

    • systems that fail, 12:10 pm on October 7, 2014 Permalink | Reply

      This post is worth everyone’s attention. When can I find out more?

    • Jerrod 8:34 am on October 9, 2014 Permalink | Reply

      I recently set up our steam shower unit, finest thing we’ve bought
      in a long while, the children and family members think it’s great, unable
      to see everybody going back to traditional showers again

    • delicious 10:43 am on October 12, 2014 Permalink | Reply

      Hey there! I’ve been reading your site for some time now and
      finally got the courage to go ahead and give you a shout out from
      Lubbock Tx! Just wanted to say keep up the good job!

    • tan 7:07 pm on November 6, 2014 Permalink | Reply

      Only use those that have a color guide, which will help you
      see where you applied the lotion. You can buy swimsuits in floral and island prints to add more fun to your look at the beach.
      Suede is less durable than other varieties of Buffalo
      Leather and is cheaper because many pieces of suede can be split from
      a single piece of the hide.

    • Ulysses 5:52 am on November 27, 2014 Permalink | Reply

      With the growing popularity of the game, the sophistication of the audience has
      also increased. The Diablo 3 site released
      this official FAQ regarding the open beta ‘stress test':.
      Bio – Ware is giving the gaming community a new formula, one that’s as different
      from Wo – W’s model as quantum mechanics is from Newtonian physics.

  • Ali BaderEddin 8:58 pm on April 8, 2010 Permalink | Reply  

    Memory Visualizer 

    “Memory Visualizer” is a program implemented in C++ using the OpenGL library. It allows you to browse and see the contents (in decimal, hex, char and binary formats) of every address in the process address space. It also color maps every byte in memory so we visually get an idea about the most common byte values. A lot of variables (x86-x64, physical vs. virtual memory, etc…) could affect the way we visualize memory, so they are described in detail in the sections that follow.

    The implementation is simple, but it certainly helped me refresh my memory about computer memory. I hope it’ll do the same for you.

    CPU Architecture

    On an x86 machine, general-purpose registers (GPR) are 32-bit wide. Thus, a CPU register can refer to one of 2 ^ 32 possible addresses. Knowing that each address identifies a single byte of storage, on a 32-bit system, we can have a maximum of 4 GB of RAM (physical memory). On an x64 processor, GPRs are 64-bit wide, and thus it’s possible to refer to 2 ^ 64 locations (16 exbibytes). Although it’s possible to refer to that much memory, the largest RAM in the world by far is 2.5 TB ($4.7 million and 10,000 times the size of RAM in your PC. More details here).

    The CPU architecture doesn’t directly affect the size of the virtual address in memory. It’s the targeted platform when compiling our C++ application that does have an impact on the way we are going to visualize memory. When compiling C++ using Visual Studio on a 64-bit Windows operating system, the code is built as a 32-bit application by default. However, we can still build 64-bit applications using Visual Studio (see section below). Using the sizeof operator (results in table below), we can clearly see that a pointer in a 32-bit C++ app has a size of 4 bytes (32 bits) while a pointer in a 64-bit app has a size of  8 bytes (64-bit).

    So if we build our app as 32-bit, we’ll be able to browse virtual memory addresses ranging from address 0 to address 2^32 – 1.  Building that app as 64-bit, we can browse virtual memory addresses from 0 to 2^64 – 1.

    Visual Studio X64

    To build a 64-bit application in Visual Studio, go to Build \ Configuration Manager, in the “Active solution platform” drop-down, select <New…>. Select x64 in the “Type or select the new platform” drop-down. Click OK then rebuild your application. If you don’t see the “x64″ in the drop-down, check this page for installing Visual Studio 64-bit Components.

    Physical Memory vs. Virtual Memory

    Although physical memory is the actual location where data\code is stored, processes in an operating system don’t interact directly with physical memory. Instead, processes operate on virtual memory. Thus, our C++ program will reflect the virtual memory and not the physical memory. Here is a nice diagram that shows the relationship between virtual and physical address spaces.

    A machine of 2 GB of RAM can actually have 4 GB of virtual memory. The extra memory is usually stored on a hard disk drive. Since I/O with a disk is much slower than volatile memory, new and active processes are located in RAM while other non-active processes reside on disk. Based on usage, virtual memory is swapped back and forth between RAM and hard drive to ensure most efficient execution possible. Thus, the total virtual space is limited by both the actual physical space and hard disk space.

    Virtual memory is also dependent on the type of operating system installed on the machine. For example, on a 64-bit Windows Server R2 Enterprise, the virtual memory limit is 2 TB. On a 64-bit Windows 7 Ultimate, the limit is 192 GB. On a 64-bit Vista Ultimate, the limit is 128 GB. However, on a 32-bit Windows 7 Ultimate or Windows Vista Ultimate, the limit is 4 GB. In short, on a Windows Operating system, limits range between 2 GB and 2 TB based on the version of the OS. Full details available here.

    Process Private Address Space

    Although the total virtual address space can get up to 2 TB on Windows Server 2008 R2, this doesn’t mean that each process can take advantage of that much memory. The maximum amount of addressable memory a process can have is dependent on the Operating System and the way the program is compiled. By default, every process takes 2 GB of private address space on any Windows Operating System whatever the processor architecture is. However, a program can be flagged as large address aware during linkage, and in that case, a 32-bit process can take up to 3 GB on a 32-bit Windows (with 4GT enabled) and 4 GB on a 64-bit Windows, while a 64-bit process takes 8 TB on a 64-bit Windows. Full details available here.

    Large Address Aware

    To make a program large address aware in Visual Studio, go to Project \ Properties \ Configuration Properties \ Linker \ System. Set “Enable Large Addresses” to “Support Addresses Larger Than 2 Gigabytes (/LARGEADDRESSAWARE)”.

    Access Violation

    Every process has its own private address space. A process can’t read from the address space of another process. Thus, our Memory Visualizer C++ program will only be able to view the content of virtual memory addresses in its address space. If we try to access the contents of an address (except for shared memory) outside the process private address space, we will get an access violation exception.

    Since in our program we can browse to any address (by changing the value of a pointer p) then view the contents of that address using *p, there is a very high possibility that we end up trying to view the contents outside our address space and thus get an access violation exception.

    By default, in a project compiled with Visual C++, an access violation exception that happens inside a try\catch(…) block is not caught. The reason for this is that Visual C++ has two types of exception handling: Synchronous Exception Handling (/EHs) and Asynchronous Exception Handling (/EHa). The default Exception handling mechanism in Visual C++ 2005 (and later) is synchronous, which means it only handles exceptions thrown by a throw statement. Any hardware exceptions will not be caught by the synchronous model for performance reasons. To get the access violation exceptions caught, I had to change the exception handling model in my VS project to asynchronous. To do so, go to Project \ Properties \ Configuration Properties \ C/C++ \ Code Generation, and change “Enable C++ Exceptions” to “Yes With SEH Exceptions (/EHa)”.

    The Visualization

    With all those memory concepts finally sorted out, we can now get to visualizing it.

    1. A virtual memory address refers to one byte in memory. Thus, we should declare the address pointer as follows:
      unsigned char *currentAddress;
    2. Start with an address inside our process. We can get the address of any primitive type or array declared (stack) or the address of anything initialized on the heap with malloc or new. I chose the address of the argc argument to the main method.
      start_Address = (unsigned char *)&argc;
    3. Show the content of up to 24 addresses at a time.
      for (currentAddress = top_entry; currentAddress < top_entry + 24; currentAddress++)
          //  Code to display current address and its contents
    4. In case an access violation happens while trying to access the contents of an address, show the ‘?’ value in all formats.
      bool av = false;
          currentValue = *currentAddress;
          av = true;
          //  draw '?'
          //  draw currentValue
    5. An address is displayed in hexadecimal. Contents of an address (a byte) is displayed in decimal (value between 0 and 255), as ASCII character (GLUT capable of displaying letters, digits, and few symbols), in hexadecimal format and binary format.
    6. Based on the value of address content, a color is used. More details about color mapping below.


    Color Mapping

    The content of an address (a  byte) can have a value ranging from 0 to 255 (in decimal format). We need to assign a color for each of those values ranging from black to white. The RGB system accepts 256 different values for each of the color components red, green and blue. With 256 values for each color components, the number of possible colors that can be generated is 256 ^ 3 (permutation with repetition). The challenge here is to meaningfully map 16,777,216 possible colors to 256 colors only.

    Color Lookup Table (CLUT)

    A color look-up table (CLUT) is a mechanism used to transform a range of input colors into another range of colors. In our case, we want to transform the 16,777,216 range to a 256 range. We will try to generate more than one color table and see where the visualization looks best.

    Gray Scale

    We will start with the simplest color table. A color looks gray if all the R, G, and B components are equal. When R = G = B = 0, the color is black. As we increase the value of the color components, the color will get lighter (dark gray) and lighter (gray) and lighter (light gray) until it becomes white with R = G = B = 255.

    for(i = 0; i < 256; i++)
        gray[i][0] = i;        //  R
        gray[i][1] = i;        //  G
        gray[i][2] = i;        //  B


    To keep things simple, let’s remove one variable out of the equation. So as if the green component doesn’t exist, think of a way to combine the red and blue components to give a feeling of moving from red to blue as we move from 0 to 255.

    For color 0, use (255, 0, 0), for color 1, use (254, 0, 1), …, for color n use (255 – n, 0, n), … for color 255 use (0, 0, 255).

    for(i = 0; i < 256; i++)
        rb[i][0] = 255 - i;  //  R
        rb[i][1] = 0;        //  G
        rb[i][2] = i;        //  B


    Let’s say that now we would like to put back the green color into the color scale. We can do so by splitting the scale in half. 0 to 127 will represent the move from red to green and 128 to 255 will represent the move from green to blue.

    Color 0 is (255, 0, 0), Color 1 is (253, 2, 0), Color n (where n < 128) is (255 – 2n, 2n, 0). Color 128 is (0, 255, 0), Color 129 is (0, 253, 2) and color n (where n >= 128) is (0, 255 – 2n, 2n).

    for(i = 0; i < 128; i++)
        rgb[i][0] = 255 - 2 * i;  //  R
        rgb[i][1] = 2 * i;        //  G
        rgb[i][2] = 0;            //  B
    for(; i < 256; i++)
        rgb[i][0] = 0;            //  R
        rgb[i][1] = 255 - 2 * i;  //  G
        rgb[i][2] = 2 * i;        //  B


    The conventional 7 colors of a rainbow are red, orange, yellow, green, blue and violet. See Roygbiv.

    for(i = 0; i < 64; i++)
        roygbv[i][0] = 255;
        roygbv[i][1] = i * 4;
        roygbv[i][2] = 0;
    for(; i < 128; i++)
        roygbv[i][0] = 255 - (i * 4);
        roygbv[i][1] = 255;
        roygbv[i][2] = 0;
    for(; i < 192; i++)
        roygbv[i][0] = 0;
        roygbv[i][1] = 255 - (i * 4);
        roygbv[i][2] = i * 4;
    for(; i < 256; i++)
        roygbv[i][0] = i * 4;
        roygbv[i][1] = 0;
        roygbv[i][2] = 255;


    Hot is the transition from black to red to yellow to white.
    for(i = 0; i < 85; i++)
        hot[i][0] = i * 3;
        hot[i][1] = 0;
        hot[i][2] = 0;
    for(; i < 170; i++)
        hot[i][0] = 255;
        hot[i][1] = (i - 85) * 3;
        hot[i][2] = 0;
    for(; i < 256; i++)
        hot[i][0] = 255;
        hot[i][1] = 255;
        hot[i][2] = (i - 170) * 3;


    Cold is the transition from cyan to magenta.

    for(i = 0; i < 256; i++)
        cold[i][0] = i;
        cold[i][1] = 255 - i;
        cold[i][2] = 255;


    Generate random numbers for the R, G, and B components.
    for(i = 0; i < 256; i++)
        random[i][0] = rand() % 256;
        random[i][1] = rand() % 256;
        random[i][2] = rand() % 256;

    Source Code

    To run the app, download the exe from here. The complete source code is available here. If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library.

    • torbj?rn 3:32 pm on April 12, 2010 Permalink | Reply

      Is there anything interesting to look out for when using MemViz? Should I be able to find the CLUT? Or is that part hidden to the MemViz process? Could I write a program that for instance modifies a variable continously and see it in MemViz?

      I found the CLUT-generation of palettes useful :)

      • torbj?rn 3:35 pm on April 12, 2010 Permalink | Reply

        By finding the CLUT, I mean, is it possible to see the values? Forinstance for grayscale LUT:
        R 0
        G 0
        B 0
        R 1
        G 1
        B 1
        From the memory?

  • Ali BaderEddin 9:18 pm on April 1, 2010 Permalink | Reply  

    Xml Editor Control 

    If you have a Windows Forms application that involves Xml editing or viewing, you can use this control to save yourself the effort of formatting the Xml content. For now, only syntax highlighting is implemented. I expect to add more features in the future like spacing, grouping, intellisense, etc…


    Simply add the files (XmlToken.cs, XmlTokenizer.cs, XmlEditor.cs, XmlEditor.designer.cs) to your project then drag and drop the XmlEditor control from the Toolbox into your Windows Form.

    The XmlEditor control currently has three public properties. Use AllowXmlFormatting to enable or disable formatting on the Xml content in the editor. The ReadOnly property tells whether or not to allow the user to change the text. The Text property sets or gets the text of the Xml editor.

    Here is how the control looks like when AllowXmlFormatting = true and ReadOnly = false (default values):


    To color the Xml string, we have to split it into multiple tokens, then color each token based on its type. I have identified the following token types (based on syntax highlighting behavior in Visual Studio 2008):

    • A “Value” is anything between double quotes
    • A “Comment” is anything that starts with <!– and ends with –> (or starts with <!– and is never closed with –>)
    • An “Element” is any letter or digit that falls between < and a space or >
    • An “Attribute” is any letter or digit that falls after a < followed by space and not closed by >
    • An “Escape” is anything that starts with & and ends with ; (For example &quote;)
    • A “SpecialChar” is any character that is not a letter or a digit
    • A “None” is anything else

    The Tokenize() public static method of the XmlTokenizer class does the job of splitting a string into Xml tokens.

    An XmlToken object is a representation of an Xml token with details about the exact text of that token, its location in the string and its type.

    Here is the code in the XmlEditor control that does the syntax highlighting:

    List<XmlToken> tokens = XmlTokenizer.Tokenize(xmlEditor.Text);
    foreach (XmlToken token in tokens)
        xmlEditor.Select(token.Index, token.Text.Length);
        switch (token.Type)
            case XmlTokenType.Attribute:
                xmlEditor.SelectionColor = Color.Red;
            case XmlTokenType.Comment:
                xmlEditor.SelectionColor = Color.DarkGreen;
            //  and so on for the other token types

    Download source and exe.

    • maria judi 5:37 pm on November 15, 2010 Permalink | Reply

      thak u_______

      ths is very useful for my project

    • Ali BaderEddin 8:55 pm on November 15, 2010 Permalink | Reply

      Glad it is..

    • Marco van Tintelen 5:58 am on January 10, 2011 Permalink | Reply

      Very nice!

    • rishi 10:02 am on February 9, 2011 Permalink | Reply

      intellisense: do you have support for that ? If not can you tell me how can I implement it. thanks in advance.

    • Colby Africa 8:32 am on March 4, 2011 Permalink | Reply

      Nice work! Are you okay if I start with this and extend it or is this “as-is” only?

      Thank you!


    • Ali BaderEddin 12:38 am on March 5, 2011 Permalink | Reply

      Sure… Please share the final version that you come up with.

      If you are planning to distribute it, it’s OK as long as you keep reference that it was originally created by me and link to this post in the source code…

    • Joseph Gordon 7:07 am on August 17, 2011 Permalink | Reply

      Great work here. Small performance tip: you have a re-entry issue in your FormatXml method, where changing the selectionColor fires the textbox_changed event, causing another call to FormatXml.

    • W 1:16 pm on February 17, 2012 Permalink | Reply

      Thanks. This is really helpful.

    • Sims 4 Cheats 1:11 pm on July 28, 2014 Permalink | Reply

      Heya just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly.
      I’m not sure why but I think its a linking issue. I’ve tried it
      in two different internet browsers and both show the same results.

    • Hack Jungle Heat 12:03 pm on August 5, 2014 Permalink | Reply

      This is very interesting, You are a very skilled blogger. I have joined your
      feed and look forward to seeking more of your magnificent post.
      Also, I have shared your web site in my social networks!

    • Cookie Clicker Hack 12:56 am on August 6, 2014 Permalink | Reply

      Thank you for every other informative web site.
      Where else could I get that type of info written in such a perfect way?

      I have a venture that I’m just now operating on, and I have been on the look out for such info.

    • tsunade cosplay 10:49 am on August 19, 2014 Permalink | Reply

      If possibly you paint your head’s hair, you may obtain a cost-effective
      hair painting for any couple of bucks, its surely not high-priced in any way, then you may really start off searching great!
      . If you ever generally have the very head of hair coloration then thats a plus and a issue a lot less to bother with.
      In the future you may wish to discover the crucial naruto costume, due to the surplus head of hair which it is actually got all around the throat, you will get a thing kind a
      sister or simply a cosing or almost certainly some girl it
      becomes clear that seems to have purchased a sweater or some element much like what has got the unique head of
      hair details, next the only dilemma leftover may be to position several orange attire have on more than this to be positive the hairs go on top of
      the top rated of this orange t-shirts or dresses making it look
      and also believe that this had been a particular.

    • home skin whitening tips 2:24 am on September 4, 2014 Permalink | Reply

      Nice blog here! Also your site loads up fast! What host are you using?

      Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

    • wihylof.wordpress.com 10:19 am on September 6, 2014 Permalink | Reply

      Just desire to say your article is as surprising.
      The clarity in your post is just nice and i can assume you’re an expert on this subject.

      Fine with your permission let me to grab your feed to keep updated
      with forthcoming post. Thanks a million and please continue the
      rewarding work.

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc

Get every new post delivered to your Inbox.

%d bloggers like this: