Animates a circle

image_pdfimage_print

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
public class AnimateFace : Form {
private int x = 10, y = 10;
private int width = 200, height = 200;

private Button suspend = new Button();
private Button resume = new Button();
private Button abort = new Button();
private Thread t;

public AnimateFace() {
BackColor = Color.White;
abort.Text = “Abort”;
suspend.Text = “Suspend”;
resume.Text = “Resume”;

Controls.Add(suspend);
Controls.Add(resume);
Controls.Add(abort);

int w = 20;
suspend.Location = new Point(w, 240);
resume.Location = new Point(w += 10 + suspend.Width, 240);
abort.Location = new Point(w += 10 + resume.Width, 240);

abort.Click += new EventHandler(Abort_Click);
suspend.Click += new EventHandler(Suspend_Click);
resume.Click += new EventHandler(Resume_Click);

t = new Thread(new ThreadStart(Run));
t.Start();
}
protected void Abort_Click(object sender, EventArgs e) {
t.Abort();
}
protected void Suspend_Click(object sender, EventArgs e) {
t.Suspend();
}
protected void Resume_Click(object sender, EventArgs e) {
t.Resume();
}
protected override void OnPaint( PaintEventArgs e ) {
Graphics g = e.Graphics;
Pen green = new Pen(Color.Green, 3);
Brush red = new SolidBrush(Color.Red);
g.DrawEllipse(green, x, y, width, height);
base.OnPaint(e);
}
public void Run() {
int dx=9, dy=9;
while (true) {
for (int i = 0; i < 30; i++) { x += dx; y += dy; width -= dx; height -= dy; Invalidate(); Thread.Sleep(30); } dx = -dx; dy = -dy; } } public static void Main( ) { Application.Run(new AnimateFace()); } } [/csharp]

Button click action to move a ball

image_pdfimage_print


   


using System;
using System.Drawing;
using System.Windows.Forms;

public class ButtonToMove : Form {
  private int x = 50, y = 50;
  private Button move = new Button();

  public ButtonToMove() {
    move.Text = "Move";
    move.Location = new Point(5,5);
    Controls.Add(move);
    move.Click += new EventHandler(Move_Click);
  }    
  protected void Move_Click(object sender, EventArgs e) {
    x += 9;
    y += 9;
    Invalidate();
  }
  protected override void OnPaint( PaintEventArgs e )   {
    Graphics g = e.Graphics;
    Brush red = new SolidBrush(Color.Red);
    g.FillEllipse(red ,x ,y, 20 ,20);
    base.OnPaint(e);
  }
  public static void Main( ) {
    Application.Run(new ButtonToMove());
  }         
}
           
          


Object collision

image_pdfimage_print

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Form1 : System.Windows.Forms.Form {
private int dx = 4;
private System.Windows.Forms.PictureBox picTarget;
private System.Windows.Forms.PictureBox picBall;
private System.Windows.Forms.Timer timer1;

public Form1() {
InitializeComponent();
}
private void InitializeComponent() {
this.picTarget = new System.Windows.Forms.PictureBox();
this.picBall = new System.Windows.Forms.PictureBox();
this.timer1 = new System.Windows.Forms.Timer(new System.ComponentModel.Container());
this.SuspendLayout();

this.picTarget.BackColor = Color.Red;
this.picTarget.Location = new System.Drawing.Point(160, 240);
this.picTarget.Name = “picTarget”;
this.picTarget.Size = new System.Drawing.Size(56, 56);
this.picTarget.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picTarget.TabIndex = 0;
this.picTarget.TabStop = false;

this.picBall.Image = new Bitmap(“winter.jpg”);
this.picBall.Location = new System.Drawing.Point(24, 136);
this.picBall.Name = “picBall”;
this.picBall.Size = new System.Drawing.Size(32, 32);
this.picBall.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picBall.TabIndex = 1;
this.picBall.TabStop = false;

this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(392, 341);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.picBall,
this.picTarget});
this.Name = “Form1”;
this.Text = “Crasher”;
this.ResumeLayout(false);

}
[STAThread]
static void Main() {
Application.Run(new Form1());
}

private void timer1_Tick(object sender, System.EventArgs e) {
int newX, newY;
newX = picBall.Location.X + dx;
newY = picBall.Location.Y + dx;

if (newX > this.Width – picBall.Width){
dx = – dx;
}

if (newX < 0){ dx = - dx; } if (picBall.Bounds.IntersectsWith(picTarget.Bounds)){ this.BackColor = Color.Black; } else { this.BackColor = Color.White; } picBall.Location = new Point(newX, newY); } } [/csharp]

Load animated ani file

image_pdfimage_print
   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

public class Form1 : Form
{

  public Form1() {
        InitializeComponent();
    try
    {
      this.Cursor = AdvancedCursors.Create(Path.Combine(Application.StartupPath, "blob.ani"));
    }
    catch (Exception err)
    {
      MessageBox.Show(err.Message);
    }
  }

  private void InitializeComponent()
  {
    this.SuspendLayout();

    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(292, 266);
    this.Text = "Form1";
    this.ResumeLayout(false);
  }


  [STAThread]
  static void Main()
  {
    Application.EnableVisualStyles();
    Application.Run(new Form1());
  }

}

public class AdvancedCursors
{

  [DllImport("User32.dll")]
  private static extern IntPtr LoadCursorFromFile(String str);

  public static Cursor Create(string filename)
  {
    IntPtr hCursor = LoadCursorFromFile(filename);
    
    if (!IntPtr.Zero.Equals(hCursor))
    {
      return new Cursor(hCursor);
    }
    else
    {
      throw new ApplicationException("Could not create cursor from file " + filename);
    }
  }
}


           
          


Using XPath to get string value, integer value and boolean value

image_pdfimage_print
   
 
//---------------------------------------------------------------------
// File: XPathValidator.cs
// 
// Summary: 
//
// Copyright (c) http://bizunitextensions.codeplex.com. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Xml.XPath;
using System.Xml;

namespace BizUnit.Extensions.Utilities
{
  /// <summary>
  /// A utility class which applies XPath expressions to xml files and returns the value
  /// in a variety of data types
  /// </summary>
  public class XPathValidator
  {
    /// <summary>
    /// basic constructor
    /// </summary>
    public XPathValidator()
    {
      //
      // TODO: Add constructor logic here
      //
    }
    /// <summary>
    /// Evaluates the XPath expression and returns a string value
    /// </summary>
    /// <param name="InputXmlFile">full path of the xml file to parse</param>
    /// <param name="XPathString">XPath expression to apply</param>
    /// <returns>string</returns>
    public string GetStringValue(string InputXmlFile,string XPathString)
    {
      string retval ;
      object obj = MakeXPathExpression(InputXmlFile,XPathString);
      retval = (string)obj;
      return(retval);
    }

    /// <summary>
    /// Evaluates the XPath expression and returns a integer value
    /// </summary>
    /// <param name="InputXmlFile">full path of the xml file to parse</param>
    /// <param name="XPathString">XPath expression to apply</param>
    /// <returns>int</returns>
    public int GetIntegerValue(string InputXmlFile,string XPathString)
    {
      int retval ;
      object obj = MakeXPathExpression(InputXmlFile,XPathString);
      retval = System.Convert.ToInt32(obj);
      return(retval);
    }

    /// <summary>
    /// Evaluates the XPath expression and returns a bool value
    /// </summary>
    /// <param name="InputXmlFile">full path of the xml file to parse</param>
    /// <param name="XPathString">XPath expression to apply</param>
    /// <returns>bool</returns>
    public bool GetBooleanValue(string InputXmlFile,string XPathString)
    {
      bool retval ;
      object obj = MakeXPathExpression(InputXmlFile,XPathString);
      retval = System.Convert.ToBoolean(obj);
      return(retval);
    }
    private object MakeXPathExpression(string inputXmlFile,string XPathString)
    {
      
      XmlDocument xDoc = new XmlDocument();
      xDoc.Load(inputXmlFile);
      XPathNavigator nav = xDoc.CreateNavigator();
      XPathExpression expr = nav.Compile( XPathString);

      return(nav.Evaluate(expr));
    }
  }
}

   
     


XPath Expression Syntax

image_pdfimage_print
   
 

Expression   Description

/            Starts an absolute path that selects from the root node.

             /Order/Items/Item selects all Item elements that are children of an Items element, 
             which is itself a child of the root Order element.

//           Starts a relative path that selects nodes anywhere.

             //Item/Name selects all the Name elements that are children of an Item element, 
             regardless of where they appear in the document.

@            Selects an attribute of a node.

             /Order/@id selects the attribute named id from the root Order element.

*            Selects any element in the path.

             /Order/* selects both Items and Client nodes because both are contained by a root 
             Order element.

|            Combines multiple paths.
             
             /Order/Items/Item/Name|Order/Client/Name selects the Name nodes used to describe 
             a Client and the Name nodes used to describe an Item.

.            Indicates the current (default) node.

             If the current node is an Order, the expression ./Items refers to the related 
             items for that order.

..           Indicates the parent node.

             //Name/.. selects any element that is parent to a Name, which includes the Client 
             and Item elements.

[ ]          Define selection criteria that can test a contained node or attribute value.

             /Order[@id="1999-01-30.195496"] selects the Order elements with the indicated 
             attribute value.

             /Order/Items/Item[Price > 50] selects products above $50 in price.

             /Order/Items/Item[Price > 50 and Name="Laser Printer"] selects products that match 
             two criteria.

starts-with  This function retrieves elements based on what text a contained element starts with.

             /Order/Items/Item[starts-with(Name, "C")] finds all Item elements that have a 
             Name element that starts with the letter C.

position     This function retrieves elements based on position.

             /Order/Items/Item[position ()=2] selects the second Item element.

count        This function counts elements. You specify the name of the child element to count or 
             an asterisk (*) for all children.

             /Order/Items/Item[count(Price) = 1] retrieves Item elements that have exactly one 
             nested Price element.
           
         
     


XmlQuery Example

image_pdfimage_print
   
 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;

class Form1 : Form {
    private XmlDocument mDocument;
    private XmlNode mCurrentNode;

    public Form1() {
        InitializeComponent();

        mDocument = new XmlDocument();
        mDocument.Load("XPathQuery.xml");
        mCurrentNode = mDocument.DocumentElement;
        ClearListBox();
    }

    private void DisplayList(XmlNodeList nodeList) {
        foreach (XmlNode node in nodeList) {
            RecurseXmlDocumentNoSiblings(node, 0);
        }
    }

    private void RecurseXmlDocumentNoSiblings(XmlNode root, int indent) {
        if (root == null)
            return;

        if (root is XmlElement) {
            listBoxResult.Items.Add(root.Name.PadLeft(root.Name.Length + indent));

            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild, indent + 2);
        } else if (root is XmlText) {
            string text = ((XmlText)root).Value;
            listBoxResult.Items.Add(text.PadLeft(text.Length + indent));
        } else if (root is XmlComment) {
            string text = root.Value;
            listBoxResult.Items.Add(text.PadLeft(text.Length + indent));

            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild, indent + 2);
        }
    }

    private void RecurseXmlDocument(XmlNode root, int indent) {
        if (root == null)
            return;
        if (root is XmlElement) {
            listBoxResult.Items.Add(root.Name.PadLeft(root.Name.Length + indent));
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild, indent + 2);
            if (root.NextSibling != null)
                RecurseXmlDocument(root.NextSibling, indent);
        } else if (root is XmlText) {
            string text = ((XmlText)root).Value;
            listBoxResult.Items.Add(text.PadLeft(text.Length + indent));
        } else if (root is XmlComment) {
            string text = root.Value;
            listBoxResult.Items.Add(text.PadLeft(text.Length + indent));
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild, indent + 2);
            if (root.NextSibling != null)
                RecurseXmlDocument(root.NextSibling, indent);
        }
    }

    private void ClearListBox() {
        listBoxResult.Items.Clear();
    }
    private void radioButtonSelectRoot_CheckedChanged(object sender, EventArgs e) {
        mCurrentNode = mCurrentNode.SelectSingleNode("//books");
        ClearListBox();
        RecurseXmlDocument(mCurrentNode, 0);
    }

    private void buttonClose_Click(object sender, EventArgs e) {
        Application.Exit();
    }

    private void buttonExecute_Click(object sender, EventArgs e) {
        if (textBoxQuery.Text == "")
            return;
        try {
            XmlNodeList nodeList = mCurrentNode.SelectNodes(textBoxQuery.Text);
            ClearListBox();
            DisplayList(nodeList);
        } catch (System.Exception err) {
            MessageBox.Show(err.Message);
        }
    }

    private void radioButtonSelectAllAuthors_CheckedChanged(object sender, EventArgs e) {
        XmlNodeList nodeList = mCurrentNode.SelectNodes("//book/author");
        ClearListBox();
        DisplayList(nodeList);
    }

    private void radioButtonSelectSpecificAuthor_CheckedChanged(object sender, EventArgs e) {
        XmlNodeList nodeList = mCurrentNode.SelectNodes("//book[author=&#039;J&#039;]");
        ClearListBox();
        DisplayList(nodeList);
    }

    private void radioButtonSelectAllBooks_CheckedChanged(object sender, EventArgs e) {
        XmlNodeList nodeList = mCurrentNode.SelectNodes("//book");
        ClearListBox();
        DisplayList(nodeList);
    }

    private void radioButtonSetBookAsCurrent_CheckedChanged(object sender, EventArgs e) {
        mCurrentNode = mCurrentNode.SelectSingleNode("book[title=&#039;C#&#039;]");
        ClearListBox();
        RecurseXmlDocumentNoSiblings(mCurrentNode, 0);
    }

    private void radioButtonSetBooksAsCurrent_CheckedChanged(object sender, EventArgs e) {
        mCurrentNode = mCurrentNode.SelectSingleNode("//books");
        ClearListBox();
        RecurseXmlDocumentNoSiblings(mCurrentNode, 0);
    }

    private void radioButtonSelectAllChildren_CheckedChanged(object sender, EventArgs e) {
        XmlNodeList nodeList = mCurrentNode.SelectNodes("*");
        ClearListBox();
        DisplayList(nodeList);
    }
    private void InitializeComponent() {
        this.radioButtonSelectRoot = new System.Windows.Forms.RadioButton();
        this.radioButtonSelectAllChildren = new System.Windows.Forms.RadioButton();
        this.radioButtonSetBooksAsCurrent = new System.Windows.Forms.RadioButton();
        this.radioButtonSetBookAsCurrent = new System.Windows.Forms.RadioButton();
        this.radioButtonSelectAllBooks = new System.Windows.Forms.RadioButton();
        this.radioButtonSelectSpecificAuthor = new System.Windows.Forms.RadioButton();
        this.radioButtonSelectAllAuthors = new System.Windows.Forms.RadioButton();
        this.textBoxQuery = new System.Windows.Forms.TextBox();
        this.buttonExecute = new System.Windows.Forms.Button();
        this.buttonClose = new System.Windows.Forms.Button();
        this.listBoxResult = new System.Windows.Forms.ListBox();
        this.SuspendLayout();
        this.radioButtonSelectRoot.AutoSize = true;
        this.radioButtonSelectRoot.Location = new System.Drawing.Point(13, 234);
        this.radioButtonSelectRoot.Size = new System.Drawing.Size(72, 17);
        this.radioButtonSelectRoot.Text = "Select root";
        this.radioButtonSelectRoot.CheckedChanged += new System.EventHandler(this.radioButtonSelectRoot_CheckedChanged);

        this.radioButtonSelectAllChildren.AutoSize = true;
        this.radioButtonSelectAllChildren.Location = new System.Drawing.Point(163, 282);
        this.radioButtonSelectAllChildren.Size = new System.Drawing.Size(104, 17);
        this.radioButtonSelectAllChildren.Text = "Select all children";
        this.radioButtonSelectAllChildren.CheckedChanged += new System.EventHandler(this.radioButtonSelectAllChildren_CheckedChanged);

        this.radioButtonSetBooksAsCurrent.AutoSize = true;
        this.radioButtonSetBooksAsCurrent.Location = new System.Drawing.Point(163, 258);
        this.radioButtonSetBooksAsCurrent.Size = new System.Drawing.Size(120, 17);
        this.radioButtonSetBooksAsCurrent.Text = "Set Books as current";
        this.radioButtonSetBooksAsCurrent.CheckedChanged += new System.EventHandler(this.radioButtonSetBooksAsCurrent_CheckedChanged);

        this.radioButtonSetBookAsCurrent.AutoSize = true;
        this.radioButtonSetBookAsCurrent.Location = new System.Drawing.Point(163, 234);
        this.radioButtonSetBookAsCurrent.Size = new System.Drawing.Size(115, 17);
        this.radioButtonSetBookAsCurrent.Text = "Set Book as current";
        this.radioButtonSetBookAsCurrent.CheckedChanged += new System.EventHandler(this.radioButtonSetBookAsCurrent_CheckedChanged);

        this.radioButtonSelectAllBooks.AutoSize = true;
        this.radioButtonSelectAllBooks.Location = new System.Drawing.Point(13, 306);
        this.radioButtonSelectAllBooks.Size = new System.Drawing.Size(96, 17);
        this.radioButtonSelectAllBooks.Text = "Select all books";
        this.radioButtonSelectAllBooks.CheckedChanged += new System.EventHandler(this.radioButtonSelectAllBooks_CheckedChanged);

        this.radioButtonSelectSpecificAuthor.AutoSize = true;
        this.radioButtonSelectSpecificAuthor.Location = new System.Drawing.Point(13, 282);
        this.radioButtonSelectSpecificAuthor.Size = new System.Drawing.Size(137, 17);
        this.radioButtonSelectSpecificAuthor.Text = "Select by specific author";
        this.radioButtonSelectSpecificAuthor.CheckedChanged += new System.EventHandler(this.radioButtonSelectSpecificAuthor_CheckedChanged);

        this.radioButtonSelectAllAuthors.AutoSize = true;
        this.radioButtonSelectAllAuthors.Location = new System.Drawing.Point(13, 258);
        this.radioButtonSelectAllAuthors.Margin = new System.Windows.Forms.Padding(3, 1, 3, 3);
        this.radioButtonSelectAllAuthors.Size = new System.Drawing.Size(102, 17);
        this.radioButtonSelectAllAuthors.Text = "Select all authors";
        this.radioButtonSelectAllAuthors.CheckedChanged += new System.EventHandler(this.radioButtonSelectAllAuthors_CheckedChanged);

        this.textBoxQuery.Location = new System.Drawing.Point(13, 330);
        this.textBoxQuery.Size = new System.Drawing.Size(385, 20);

        this.buttonExecute.Location = new System.Drawing.Point(323, 234);
        this.buttonExecute.Text = "Execute";
        this.buttonExecute.Click += new System.EventHandler(this.buttonExecute_Click);

        this.buttonClose.Location = new System.Drawing.Point(405, 13);
        this.buttonClose.Text = "Close";
        this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);

        this.listBoxResult.FormattingEnabled = true;
        this.listBoxResult.Location = new System.Drawing.Point(13, 13);
        this.listBoxResult.Size = new System.Drawing.Size(385, 212);

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(492, 362);
        this.Controls.Add(this.listBoxResult);
        this.Controls.Add(this.buttonClose);
        this.Controls.Add(this.buttonExecute);
        this.Controls.Add(this.textBoxQuery);
        this.Controls.Add(this.radioButtonSelectAllAuthors);
        this.Controls.Add(this.radioButtonSelectSpecificAuthor);
        this.Controls.Add(this.radioButtonSelectAllBooks);
        this.Controls.Add(this.radioButtonSetBookAsCurrent);
        this.Controls.Add(this.radioButtonSetBooksAsCurrent);
        this.Controls.Add(this.radioButtonSelectAllChildren);
        this.Controls.Add(this.radioButtonSelectRoot);

        this.Text = "XPath Queries";
        this.ResumeLayout(false);
        this.PerformLayout();

    }



    private System.Windows.Forms.RadioButton radioButtonSelectRoot;
    private System.Windows.Forms.RadioButton radioButtonSelectAllChildren;
    private System.Windows.Forms.RadioButton radioButtonSetBooksAsCurrent;
    private System.Windows.Forms.RadioButton radioButtonSetBookAsCurrent;
    private System.Windows.Forms.RadioButton radioButtonSelectAllBooks;
    private System.Windows.Forms.RadioButton radioButtonSelectSpecificAuthor;
    private System.Windows.Forms.RadioButton radioButtonSelectAllAuthors;
    private System.Windows.Forms.TextBox textBoxQuery;
    private System.Windows.Forms.Button buttonExecute;
    private System.Windows.Forms.Button buttonClose;
    private System.Windows.Forms.ListBox listBoxResult;
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

}