Google
 

Thursday, April 05, 2007

Language C Learning Notes 2

  1. #define
    1. A #define line defines a symbolic name or symbolic constant to be a particular string of characters:
      #define name replacement list
      Thereafter, any occurrence of name (not in quotes and not part of another name) will be replaced by the corresponding replacement text. The name has the same form as a variable name: a sequence of letters and digits that begins with a letter. The replacement text can be any sequence of characters; it is not limited to numbers.
    2. Symbolic constant names are conventionally written in upper case so they can ber readily distinguished from lower case variable names. Notice that there is no semicolon at the end of a #define line.
  2. Macro Substitution
    1. A definition has the form
      #define name replacement text
      It calls for a macro substitution of the simplest kind - subsequent occurrences of the token name will be replaced by the replacement text.
    2. The name in a #define has the same form as a variable name; the replacement text is arbitrary.
    3. Normally the replacement text is the rest of the line, but a long definition may be continued onto several lines by placing a \ at the end of each line to be continued.
    4. The scope of a name defined with #define is from its point of definition to the end of the source file being compiled. A definition may use previous definitions.
    5. Substitutions are made only for tokens, and do not take place within quoted strings.
    6. It is also possible to define macros with arguments, so the replacement text can be different for different calls of the macro.
    7. If you examine the expansion of max, you will notice some pitfalls. The expressions are evaluated twice; this is bad if they involve side effects like increment operators or input and output. For instance
      max(i++, j++) /* WRONG */
      #define max(A, B) ((A) > (B) ? (A) : (B))
      x = max(p+q, r+s);
      will increment the larger twice. Some care also has to be taken with parentheses to make sure the order of evaluation is preserved; consider what happens when the macro
      #define square(x) x * x /* WRONG */
      is invoked as square(z+1).
    8. Names may be undefined with #undef, usually to ensure that a routine is really a function, not a macro:
      #undef getchar
      int getchar(void) { ... }
    9. Formal parameters are not replaced within quoted strings. If, however, a parameter name is preceded by a # in the replacement text, the combination will be expanded into a quoted string with the parameter replaced by the actual argument. This can be combined with string concatenation to make, for example, a debugging print macro:
      #define dprint(expr) printf(#expr " = %g\n", expr)
    10. The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned. For example, the macro paste concatenates its two arguments:
      #define paste(front, back) front ## back
      so paste(name, 1) creates the token name1.
    11. Test Macro usage  

      #include 
      <assert.h>
      #include 
      < setjmp.h>
      #include 
      <stdlib.h >
      #include 
      <stdio.h>
      #include 
      <string.h>
          
      // Test Macro usage    
          
      //
           #undef max
          
      //  Be care to define a macro
          
      // At the end without semicolom, otherwise the semicolom will be at the end of the token
          #define max(A,B)  ((A) > (B) ? (A) : (B))
          
      #define maxName(A,B) ((A) > (B) ? (#A) : (#B))
          
      #undef square
          
      #undef square1
          
      #define square(a) ((a) * (a))
          
      #define  square1(a) (a * a)
          
          
      // #
          #undef dprintf
          
      #define dprintf(expr)  printf(#expr " =%g\n",expr)
          
      //  ##
          #undef paste
          
      #define paste(front,back) front ## back
          
      #undef map
          
      #define map(str) #str
          
      void main()
          {
            
      int a,b,c;
            
      //  Testing max(a,b)  
            printf( "max(a,b):\n");         
            printf(
      "Please input two numbers to compare:\n");
            printf(
      "a=");
            scanf(
      " %i"&a);
            printf(
      "b=");
            scanf(
      " %i",&b);
            printf(
      "Which is bigger, a=%i or b=%i? %s=%i is bigger.\n",a,b, maxName(a,b),max(a,b));    
            
            
      // Testing max(i++,j++)
            printf( "max(i++,j++):\n");
            printf(
      "Please input two numbers to compare:\n");
            printf(
      "a=");
            scanf(
      "%i"& a);
            printf(
      "b=");
            scanf(
      "%i",& b);
            printf(
      "Which is bigger, a=%i or b=%i? %s=%i is bigger.\n ",a,b, maxName(a,b),max(a++,b++ ));            
            printf(
      "Now the a=%i,b=%i.\n" ,a,b);
            
            
            b 
      = 2;
            printf(
      "\nTesting #define square(a) ((a) * (a))\n" );
            printf(
      "Square(%d) = %d\n",b,square(b));
            printf(
      "Square(%d + 1) = %d\n",b,square(b  + 1));
            
            
            printf(
      "\nTesting #define square1(a) (a * a)\n");
            printf(
      "Square1(%d) = %d\n",b,square1(b));
            printf(
      "Square1(%d) = %d\n",b +  1,square1(b +  1));

            
      // Testing  #
            double d =  1.003;
            dprintf(d);
            
      // Testing  ##         
            
      //        char* strd = "Testing";
            
      //        char* str = "Testing";
            double str  = 2.0;
            
      double  strd = 34.0;   
            
      // expected 
            dprintf(str);
            
      //  expected
            dprintf(strd);
            
            printf(
      "%e\n",paste(str,d));
            
            
      // Terminate program
            printf(" Please input any character to end the program:\n");
            
      char* t;
            scanf(
      "%s ",&t); 

          }
  3. Input and Output
    1. The % Format Specifiers:

      The % specifiers that you can use in ANSI C are:

            Usual variable type           Display

      %c        char                     single character
      %d (%i)   int                      signed integer
      %e (%E)   float or double          exponential format
      %f        float or double          signed decimal
      %g (%G)   float or double          use %f or %e as required
      %o        int                      unsigned octal value

      %p        pointer                  address stored in pointer
      %s        array of char            sequence of characters
      %u        int                      unsigned decimal
      %x (%X)   int                      unsigned hex value




s

--
Happy day, happy life!

Wednesday, April 04, 2007

Language C Learning Notes 1

File Inclusion
A control line of the form
# include <filename>
causes the replacement of that line by the entire contents of the file filename. The characters in the name filename must not include > or newline, and the effect is undefined if it contains any of ", ', \, or /*. The named file is searched for in a sequence of implementation-defined places.
Similarly, a control line of the form
# include "filename"
searches first in association with the original source file (a deliberately implementation-dependent phrase), and if that search fails, then as in the first form. The effect of using ', \, or /* in the filename remains undefined, but > is permitted.
Finally, a directive of the form
# include token-sequence
not matching one of the previous forms is interpreted by expanding the token sequence as for normal text; one of the two forms with <...> or "..." must result, and is then treated as previously described.
#include files may be nested.

--
Happy day, happy life!

CuTest Example Compiled with error!

I copy the example from the readme file of CuTest.
However, it compiles with error.

The following the updated version:
DETAILED EXAMPLE

Here is a more detailed example. We will work through a simple
test first exercise. The goal is to create a library of string
utilities. First, lets write a function that converts a
null-terminated string to all upper case.

Ensure that CuTest.c and CuTest.h are accessible from your C
project. Next, create a file called StrUtil.c with these
contents:

#include  <assert.h>
#include 
< setjmp.h>
#include 
<stdlib.h >
#include 
<stdio.h>
#include 
<string.h>
// The origianl version has missed the above includes
#include "CuTest.h"
    
    
char* StrToUpper(char*  str) {
        
return str;
    }
    
    
void  TestStrToUpper(CuTest *tc) {
        
char*  input = strdup(" hello world");
        
char*  actual = StrToUpper(input);
        
char*  expected = " HELLO WORLD";
        CuAssertStrEquals(tc, expected, actual);
    }
   
    CuSuite
* StrUtilGetSuite() {
        CuSuite
* suite =  CuSuiteNew();
        SUITE_ADD_TEST(suite, TestStrToUpper);
        
return suite;
    }

Create another file called AllTests.c with these contents:

    #include  "CuTest.h"
    
    CuSuite
*  StrUtilGetSuite();
    
    
void RunAllTests(void ) {
        CuString 
*output = CuStringNew();
        CuSuite
* suite = CuSuiteNew();
        
        CuSuiteAddSuite(suite, StrUtilGetSuite());
    
        CuSuiteRun(suite);
        CuSuiteSummary(suite, output);
        CuSuiteDetails(suite, output);
        printf(
" %s\n", output->buffer);
    }
    
    
int main(void) {
        RunAllTests();
    }

More detail please see its readme file.
--
Happy day, happy life!

Sunday, April 01, 2007

不管你是狮子还是瞪羚,当太阳升起时,你最好开始奔跑。

在非洲,瞪羚每天早上醒来时,
它知道自己必须跑得比最快的狮子还快,

否则就会被吃掉。

狮子每天早上醒来时,
它知道自己必须超过跑得最慢的瞪羚,

否则就会被饿死。


不管你是狮子还是瞪羚,
当太阳升起时,你最好开始奔跑。

摘于<<The World Is Flat>>

--
Happy day, happy life!

Saturday, March 31, 2007

Install DotNetNuke on XP with Sql Express

  1. First follow up the steps in Install DotNetNuke 4.4.0 on Windows XP (The link you have to search the title in blog)
  2. Difference:
    1. Update connectiongstring as
        <connectionStrings>
          
      <!--  Connection String for SQL Server 2005 Express -->
          
      <add name="SiteSqlServer" connectionString ="Data Source=.\SQLEXPRESS;Initial Catalog=DotNetNuke;Integrated Security=True;" providerName ="System.Data.SqlClient" />
          
      <!-- Connection String for SQL Server 2000/2005 
          <add
            name="SiteSqlServer"
            connectionString="Server=(local);Database=DotNetNuke;uid=;pwd=;"
            providerName="System.Data.SqlClient" />
        
      -->
        
      </ connectionStrings>



    2. < appSettings>
          
      <!-- Connection String for SQL Server 2005 Express - kept for backwards compatability - legacy modules    -->
          
      <add  key="SiteSqlServer" value="Data Source=.\SQLEXPRESS;Initial Catalog=DotNetNuke;Integrated Security=True;"  />
          
      <!--  Connection String for SQL Server 2000/2005 - kept for backwards compatability - legacy modules
          <add key="SiteSqlServer" value="Server=(local);Database=DotNetNuke;uid=;pwd=;"/>
          
      -->
        
      </appSettings >

  3. Issues:


--
Happy day, happy life!

Use Windows API in C#

  1. Call API without parameters
    using  System;
    using System.Runtime.InteropServices;
    using  System.Diagnostics;
    using System.Text;

    namespace  _031_Windows_API
    {
        
        
    class WinAPI
        {
            [DllImport(
    " user32", EntryPoint= "GetWindowText")]
            
    public  static extern  int GetWindowText(
                IntPtr hWnd, StringBuilder text, 
    int  count);

            [DllImport(
    "user32" )]
            
    public static  extern int GetWindowTextLength(
                IntPtr hWnd);

        }

        
    /// <summary>
        
    ///  Summary description for Class1.
        
    ///  </summary>
        class Class1
        {
            
    /// <summary>
            
    /// The main entry point for the application.
            
    ///  </summary>
            [STAThread]
            
    static void Main(string [] args)
            {
                Process p 
    = new  Process();
                p.StartInfo.FileName 
    = " Notepad";
                p.Start();
                p.WaitForInputIdle(
    10000 );

                
    int length = WinAPI.GetWindowTextLength (p.MainWindowHandle) + 1;
                StringBuilder caption 
    = new StringBuilder(length);

                
    int result =
                    WinAPI.GetWindowText(
                     p.MainWindowHandle, caption, caption.Capacity);

                
    if (result !=  0)
                {
                    Console.Write
                        (
    " Via Windows API: The caption of the window is ");
                    Console.WriteLine(
    " <{0}>",caption);

                    Console.Write
                        (
    "Via Process object: the caption of the window is " );
                    Console.WriteLine(
    "<{0}>" ,p.MainWindowTitle);
                }
                
    else
                {
                    Console.WriteLine(
    "Either the window has no caption, ");
                    Console.WriteLine(
    "or it cannot be retrieved.");
                }

                
    //p.CloseMainWindow();
                Console.ReadKey();
                
            }
        }
    }

  2. Call Win API with Win API structs
    using  System;
    using System.Runtime.InteropServices;
    using  System.Text;
    using System.Threading;


    ///  <summary>
    /// This version of InputFocus includes additional members and functional
    /// upgrades of existing members.
    ///  
    /// New Members
    /// -----------
    /// FindWindow Windows API function exported as a public member.
    ///  
    /// WindowReady method checks for the existance of
    /// a window of a given classname and caption. Window classnames can be 
    /// determined using Spy++ or similar utility.
    /// 
    /// Upgrades
    /// --------
    /// Set method checks for a zero value input parameter representing 
    /// the window handle before attempting to change input focus. Set also
    ///  polls (up to MaxAttempts times) for positive evidence that input focus
    /// has been changed to the window requested.
    /// 
    /// MaxAttempts property (read/write) allows the user to control
    /// the number of attempts for each polling.
    ///  
    /// SleepPollTime property (read/write) allow the user to control
    ///  the duration of each sleep between polling checks.
    /// 
    /// Static constructor initializes private fields for maximum number of
    /// polling attempts per method call, and duration of the sleep between
    /// polling attempts.
    /// 
    /// </summary>
    public class InputFocus
    {
        [DllImport(
    " user32.dll")]
        
    private  static extern  int GetForegroundWindow();

        [DllImport(
    "user32.dll ")]
        
    private static  extern int GetWindowText
            (IntPtr hWnd, StringBuilder text, 
    int count);

        [DllImport(
    "user32.dll ")]
        
    private  static extern int  GetWindowTextLength(IntPtr hWnd);


        [DllImport(
    "user32.dll" )]
        
    private static  extern int SetForegroundWindow(IntPtr hWnd);

        [DllImport(
    "user32.dll")]
        
    public  static extern IntPtr FindWindow( string className, string caption);

        
    public  InputFocus()
        {
            
    //
            
    // TODO: Add constructor logic here
            
    //
        }

        
    static InputFocus()
        {
            _maxAttempts 
    =  10;
            _sleepPollTime 
    = 100 ;
        }

        
    public static  bool WindowReady(string className, string  caption)
        {
            
    bool result =  false;
            
    for ( int index = 0 ; index < MaxAttempts; index++)
            {
                
    if (FindWindow(className, caption) == IntPtr.Zero)
                {
                    Console.WriteLine(
    "Window not ready, sleeping  ");
                    Thread.Sleep(SleepPollTime);
                }
                
    else
                {
                    result 
    = true ;
                    
    break;
                }
            }
            
    return  result;
        }

        
    public static  bool Set(IntPtr hWnd)
        {
            
    bool windowInFocus  = false;
            Console.Write(
    "Attempting to set focus to window with handle ");
            Console.WriteLine(hWnd);

            
    if (hWnd != IntPtr.Zero)
            {
                
    for (int index  = 0; index <  MaxAttempts; index++)
                {
                    windowInFocus 
    =  SetForegroundWindow(hWnd) != 0  ? true : false ;
                    
    if (!windowInFocus)
                    {
                        Console.WriteLine(
    "Failed to focus. Attempt {0}" , index);
                        Thread.Sleep(SleepPollTime);
                    }
                    
    else
                    {
                         Console.WriteLine(
    "Focus achieved");
                        
    break;
                    }
                }
            }
            
    return  windowInFocus;
        }

        
    public static  bool Set(System.IntPtr hWnd, string caption)
        {
            
    return (Set(hWnd) && CurrentWindow  == caption) ?  true : false;
        }

        
    public  static string CurrentWindow
        {
            
    get
            {
                IntPtr hWnd 
    = IntPtr.Zero ;
                hWnd 
    = (IntPtr)GetForegroundWindow();
                
    int  nChars = GetWindowTextLength(hWnd) +  1;
                StringBuilder caption 
    = new  StringBuilder(nChars);


                
    if (GetWindowText(hWnd, caption, nChars)  > 0)
                {
                    
    return  caption.ToString();
                }
                
    else
                {
                    
    return null;
                }
            }
        }

        
    private static  int _maxAttempts;
        
    public static  int MaxAttempts
        {
            
    get {  return _maxAttempts; }
            
    set { _maxAttempts  = value; }
        }

        
    private  static int _sleepPollTime;
        
    public  static int SleepPollTime
        {
            
    get { return _sleepPollTime; }
            
    set { _sleepPollTime = value; }
        }
    }

    using System;
    using System.Diagnostics;
    using  System.Windows.Forms;

    namespace _0401_InputFocusUpgrade
    {
        
    /// <summary>
        
    ///  The purpose of this example is to show a slightly more featured
        
    /// version of the InputFocus class and to show that the .MainWindowHandle
        
    /// property of the MSPaint process instance is 0 running under XP Professional.
        
    /// This does not appear to be the case under W2K Server.
        
    /// 
        
    /// Note that we have to use InputFocus.FindWindow to retrieve the handle
        
    /// of the main window of MSPaint.
        
    /// 
        
    /// The action of this particular example is to use Alt-PrintScreen to 
        
    /// grab a bitmap of the window with input focus (in this case, Calculator)
        
    /// and display it in Paint. This can also be accomplished using display 
        
    /// contexts (DC). For an example, see Eric Gunnerson's Win32Window class.
        
    /// 
        
    /// See the comments of the InputFocus class file in this project for more
        
    /// information.
        
    ///  </summary>
        class  Class1
        {
            
    /// <summary>
            
    /// The main entry point for the application.
            
    ///  </summary>
            [STAThread]
            
    static void Main(string [] args)
            {
                
    const string  paintFileName = "mspaint ";
                
    const string  paintCaption = "untitled - Paint ";
                
    const string  paintClassName = "MSPaintApp ";
                
    const string  calcFileName = "calc ";

                Process calc 
    = new  Process();
                calc.StartInfo.FileName 
    = calcFileName;
                calc.Start();
                 calc.WaitForInputIdle(
    10000);

                SendKeys.SendWait(
    " %{PRTSC}");
                Console.Write(
    "Calc Main Window Handle via .MainWindowHandle:  ");
                Console.WriteLine(calc.MainWindowHandle);
                calc.CloseMainWindow();

                Process paint 
    = new Process();
                paint.StartInfo.FileName  
    = paintFileName;
                paint.Start();
                paint.WaitForInputIdle(
    10000 );
                
    if (InputFocus.WindowReady(paintClassName,paintCaption))
                {
                     Console.Write(
    "Paint Main Window Handle via .MainWindowHandle: " );
                    Console.WriteLine(paint.MainWindowHandle);

                    
    if (InputFocus.Set(InputFocus.FindWindow(paintClassName,paintCaption)))
                    {
                        SendKeys.SendWait(
    "^v" );
                    }
                    
    else
                    {
                        Console.WriteLine(
    "Can't bring Paint to focus");
                    }
                }
                
    else
                {
                    Console.WriteLine(
    " Paint window can't be located");
                }


            }
        }
    }

  3. Memory API
    using  System;
    using System.Runtime.InteropServices;


    namespace  _051_Memory_API
    {
        
    //[StructLayout(LayoutKind.Sequential)]
        
    // struct MEMORYSTATUSEX
        
    //{
        
    //    public uint dwLength;
        
    //    public uint dwMemoryLoad;
        
    //     public ulong ullTotalPhys;
        
    //    public ulong ullAvailPhys;
        
    //     public ulong ullTotalPageFile;
        
    //    public ulong ullAvailPageFile;
        
    //     public ulong ullTotalVirtual;
        
    //    public ulong ullAvailVirtual;
        
    //    public ulong ullAvailExtendedVirtual;
        
    //}

        
    // Use this version of the struct to generate an error
        [StructLayout(LayoutKind.Sequential )]
        
    struct MEMORYSTATUSEX
        {
            
    public  ulong dwLength;
            
    public  ulong dwMemoryLoad;
            
    public ulong  ullTotalPhys;
            
    public ulong  ullAvailPhys;
            
    public ulong ullTotalPageFile;
            
    public ulong ullAvailPageFile;
            
    public ulong ullTotalVirtual;
            
    public ulong ullAvailVirtual;
            
    public  ulong ullAvailExtendedVirtual;
        }
     
        
    /// <summary>
        
    ///  Summary description for Class1.
        
    ///  </summary>
        class Class1
        {
            [DllImport(
    "kernel32.dll")]
            
    static extern  bool GlobalMemoryStatusEx( ref MEMORYSTATUSEX lpBuffer);

            [DllImport(
    "kernel32.dll")]
            
    static  extern int GetLastError();

            
    /// <summary>
            
    /// The main entry point for the application.
            
    ///  </summary>
            [STAThread]
            
    static unsafe void  Main(string[] args)
            {
                MEMORYSTATUSEX m 
    =  new MEMORYSTATUSEX();
                m.dwLength 
    = ( uint)sizeof(MEMORYSTATUSEX);
                
    bool success = GlobalMemoryStatusEx( ref m);

                
    if (success)
                {
                    displayMemoryData(m);
                }
                
    else
                {
                    Console.WriteLine(
    " Error Number " +  GetLastError());
                }
                Console.ReadKey();
                
            }

            
    private  static void displayMemoryData(MEMORYSTATUSEX m)
            {
                Console.WriteLine (
    "{0,-30}{1}", "dwLength",m.dwLength);
                Console.WriteLine(
    "{0,-30}{1}%"," dwMemoryLoad",m.dwMemoryLoad);
                Console.WriteLine(
    " {0,-30}{1} MB","ullTotalPhys ",m.ullTotalPhys/1024/ 1024);
                Console.WriteLine(
    "{0,-30}{1} MB ","ullAvailPhys" ,m.ullAvailPhys/1024/1024 );
                Console.WriteLine(
    "{0,-30}{1} MB" ,"ullTotalPageFile",m.ullTotalPageFile /1024/1024);
                 Console.WriteLine(
    "{0,-30}{1} MB", "ullAvailPageFile",m.ullAvailPageFile/ 1024/1024);
                Console.WriteLine(
    "{0,-30}{1} MB"," ullTotalVirtual",m.ullTotalVirtual/1024 /1024);
                Console.WriteLine(
    "{0,-30}{1} MB ","ullAvailVirtual ",m.ullAvailVirtual/1024/ 1024);
                Console.WriteLine(
    "{0,-30}{1} MB ","ullAvailExtendedVirtual" ,m.ullAvailExtendedVirtual/1024/1024 );
            }
        }
    }

    using  System;
    using System.Runtime.InteropServices;


    namespace  _051_Memory_API
    {
        [StructLayout(LayoutKind.Sequential)]
        
    struct MEMORYSTATUSEX
        {
            
    public uint dwLength;
            
    public  uint dwMemoryLoad;
            
    public  ulong ullTotalPhys;
            
    public ulong  ullAvailPhys;
            
    public ulong  ullTotalPageFile;
            
    public ulong ullAvailPageFile;
            
    public ulong ullTotalVirtual;
            
    public ulong ullAvailVirtual;
            
    public ulong ullAvailExtendedVirtual;
        }

        
    // Use this version of the struct to generate an error
        
    //[StructLayout(LayoutKind.Sequential )]
        
    //struct MEMORYSTATUSEX
        
    //{
        
    //    public ulong dwLength;
        
    //    public ulong dwMemoryLoad;
        
    //    public ulong ullTotalPhys;
        
    //     public ulong ullAvailPhys;
        
    //    public ulong ullTotalPageFile;
        
    //     public ulong ullAvailPageFile;
        
    //    public ulong ullTotalVirtual;
        
    //    public ulong ullAvailVirtual;
        
    //    public ulong ullAvailExtendedVirtual;
        
    //}
     
        
    /// <summary>
        
    ///  Summary description for Class1.
        
    ///  </summary>
        class Class1
        {
            [DllImport(
    "kernel32.dll", SetLastError  = true)]
            
    static extern bool  GlobalMemoryStatusEx( ref MEMORYSTATUSEX lpBuffer);

            
    ///  <summary>
            
    /// The main entry point for the application.
            
    /// </summary>
            [STAThread]
            
    static void  Main(string[] args)
            {
                MEMORYSTATUSEX m 
    = new MEMORYSTATUSEX();
                m.dwLength 
    =  (uint)Marshal.SizeOf(m);
                
    bool  success = GlobalMemoryStatusEx(ref  m);

                
    if (success)
                {
                    displayMemoryData(m);
                }
                
    else
                {
                    Console.WriteLine(
    "Error Number  " + Marshal.GetLastWin32Error());
                }
                
            }

            
    private static  void displayMemoryData(MEMORYSTATUSEX m)
            {
                Console.WriteLine(
    "{0,-30}{1} ","dwLength ",m.dwLength);
                Console.WriteLine(
    "{0,-30}{1}% ","dwMemoryLoad" ,m.dwMemoryLoad);
                Console.WriteLine(
    "{0,-30}{1} MB" ,"ullTotalPhys",m.ullTotalPhys /1024/1024);
                Console.WriteLine(
    "{0,-30}{1} MB", "ullAvailPhys",m.ullAvailPhys/ 1024/1024);
                Console.WriteLine(
    " {0,-30}{1} MB"," ullTotalPageFile",m.ullTotalPageFile/1024 /1024);
                Console.WriteLine(
    " {0,-30}{1} MB","ullAvailPageFile ",m.ullAvailPageFile/1024/ 1024);
                Console.WriteLine(
    "{0,-30}{1} MB ","ullTotalVirtual" ,m.ullTotalVirtual/1024/1024 );
                Console.WriteLine(
    "{0,-30}{1} MB" ,"ullAvailVirtual",m.ullAvailVirtual /1024/1024);
                 Console.WriteLine(
    "{0,-30}{1} MB", "ullAvailExtendedVirtual",m.ullAvailExtendedVirtual /1024/1024);
            }
        }
    }

  4. Windows Message
    using  System;
    using System.Runtime.InteropServices;
    using  System.Diagnostics;
    using System.Windows.Forms;
    using  System.Text;
    using System.Collections;

    namespace  _045_ID_Oracle
    {
        
    public enum windowTypes :  uint
        {
            GW_HWNDFIRST 
    =  0,
            GW_HWNDLAST 
    = 1 ,
            GW_HWNDNEXT 
    = 2,
            GW_HWNDPREV 
    = 3,
            GW_OWNER 
    = 4,
            GW_CHILD 
    =  5,
            GW_ENABLEDPOPUP 
    =  6,
        };

        
    /// <summary>
        
    /// Summary description for Class1.
        
    /// </summary>
         class Class1
        {
            [DllImport(
    "user32.dll ")]
            
    private static  extern IntPtr GetWindow(IntPtr hWnd, windowTypes uCmd);

            [ DllImport(
    " user32.dll") ]
            
    private  static extern IntPtr GetNextDlgTabItem
                (IntPtr hDlg, IntPtr hCtl, 
    bool bPrevious);

            [ DllImport(
    "user32.dll ") ]
            
    public  static extern int  GetDlgCtrlID(IntPtr hCtl);

            [ DllImport(
    "user32.dll" ) ]
            
    private static  extern int GetDlgItemText(
                IntPtr hDlg,
                
    int nIDDlgItem,
                StringBuilder lpString,
                
    int nMaxCount
                );

            [ DllImport(
    "user32.dll") ]
            
    private static  extern IntPtr GetNextDlgGroupItem
                (IntPtr hDlg, IntPtr hCtl, 
    bool bPrevious);


            
    /// <summary>
            
    /// The main entry point for the application.
            
    ///  </summary>
            [STAThread]
            
    static void Main(string [] args)
            {
                
    string formatter =  "{0,-20}{1,-20:x}{2,-20}";

                Process np 
    = new Process();
                np.StartInfo.FileName  
    = "notepad ";
                np.Start();
                np.WaitForInputIdle(
    10000);

                 SendKeys.SendWait(
    "dummy text");
                 np.WaitForInputIdle(
    10000);
                SendKeys.SendWait(
    " ^f");
                np.WaitForInputIdle(
    10000);
                SendKeys.SendWait(
    "dummy text" );

                IntPtr hDlg 
    = 
                    GetWindow(np.MainWindowHandle, windowTypes.GW_ENABLEDPOPUP);

                ArrayList controlHandles 
    = new ArrayList();

                
    if (hDlg != IntPtr.Zero)
                {

                    IntPtr firstHandle 
    = GetNextDlgTabItem(hDlg, IntPtr.Zero, false);
                    IntPtr hCtl 
    = firstHandle;

                    
    if (hCtl !=  IntPtr.Zero)
                    {
                        
    // tab through all of the controls on this form
                        do 
                        {
                            
    // if this control is part of a group, get all the group members
                            IntPtr subHandle = hCtl;
                            
    do
                            {
                                
    // don't allow duplicates
                                if ( !controlHandles.Contains(hCtl))
                                {
                                    controlHandles.Add(hCtl);
                                }
                                hCtl 
    = GetNextDlgGroupItem(hDlg, hCtl, false);
                            } 
    while (hCtl != subHandle);
                            hCtl 
    = GetNextDlgTabItem(hDlg, hCtl, false);
                        } 
    while (hCtl != firstHandle);

                         Console.WriteLine(formatter,
    "Caption", "ID value in Hex", "Handle");
                        Console.WriteLine(formatter,
    "-------"," ---------------","------ ");

                        StringBuilder caption 
    =  new StringBuilder();
                        
    foreach (IntPtr handle  in controlHandles)
                        {
                            
    int Id  = GetDlgCtrlID(handle);
                            GetDlgItemText(hDlg, Id, caption, caption.Capacity); 
                            Console.WriteLine(formatter,caption,Id,handle);    
                        }
                    }
                }
                Console.ReadKey();
                np.Kill();
            }
        }
    }

    using  System;
    using System.Diagnostics;
    using System.Windows.Forms ;
    using System.Runtime.InteropServices;
    using  System.Text;
    using System.Threading;

    namespace  CheckBoxWithID
    {
        
    /// <summary>
        
    /// Summary description for Class1.
        
    ///  </summary>
        class  Class1
        {

            
    public enum ids :  int {
                MatchCase 
    =  0x411, Direction = 0x430 , Up = 0x420, Down  = 0x421}

            
    public  enum windowTypes : uint
            {
                GW_HWNDFIRST 
    = 0,
                GW_HWNDLAST 
    = 1,
                GW_HWNDNEXT 
    =  2,
                GW_HWNDPREV 
    =  3,
                GW_OWNER 
    = 4 ,
                GW_CHILD 
    = 5,
                GW_ENABLEDPOPUP 
    = 6,
            };

            [DllImport(
    "user32.dll")]
            
    private  static extern  int SendNotifyMessage(
                IntPtr hWndControl,     
    // handle to destination control
                uint msg,                 // message ID
                IntPtr wParam,             // checkbox/radio button state
                StringBuilder lParam);   // pointer to null terminated string

            [DllImport(
    "user32.dll")]
            
    private  static extern  int PostMessage(
                IntPtr hWndControl,     
    // handle to destination control
                uint msg,                 // message ID
                IntPtr wParam,             // checkbox/radio button state
                StringBuilder lParam);   // pointer to null terminated string

            
    private const uint  BM_SETCHECK = 0x00F1;
            
    private const int  BST_CHECKED = 0x0001;
            
    private const int  BST_UNCHECKED = 0x0000;
            
    public enum buttonSetting : int  {on = BST_CHECKED, off = BST_UNCHECKED}

            [ DllImport(
    "user32.dll") ]
            
    private static extern  IntPtr GetWindow (IntPtr hWnd, windowTypes uCmd);

            [ DllImport(
    "user32.dll" ) ]
            
    public static  extern IntPtr GetDlgItem(
                IntPtr hDlg, 
    int  nIDDlgItem );


            
    /// <summary>
            
    /// The main entry point for the application.
            
    ///  </summary>
            [STAThread]
            
    static void Main(string [] args)
            {
                Process p 
    = new  Process();
                p.StartInfo.FileName 
    = " notepad";
                p.Start();
                p.WaitForInputIdle(
    10000 );

                SendKeys.SendWait(
    "Dummy Input" );
                p.WaitForInputIdle(
    10000);
                SendKeys.SendWait(
    " ^f");
                p.WaitForInputIdle(
    10000);

                IntPtr hDlg 
    = GetWindow(
                    p.MainWindowHandle, windowTypes.GW_ENABLEDPOPUP);

                IntPtr hCtl 
    = GetDlgItem(hDlg, (int)ids.MatchCase);
                RadioAndCheckBoxClick(hCtl,  buttonSetting.on);

                hCtl 
    = GetDlgItem(hDlg, (int )ids.Up);
                RadioAndCheckBoxClick(hCtl, buttonSetting.on);

                hCtl 
    = GetDlgItem(hDlg, ( int)ids.Down);
                RadioAndCheckBoxClick(hCtl, buttonSetting.off);

                Thread.Sleep(
    5000 );
                Console.ReadKey();
                p.Kill();

            }

            
    public  static void RadioAndCheckBoxClick(IntPtr hCtl, buttonSetting state)
            {
                PostMessage(        
    // SendNotifyMessage will work too
                    hCtl,             // handle to destination control     
                    BM_SETCHECK,     // message ID     
                    (IntPtr)state,     // new state for radio button or checkbox   
                    null            // = 0; not used, must be zero 
                    );
            }
        }
    }

    using  System;
    using System.Diagnostics;
    using System.Runtime.InteropServices ;
    using System.Windows.Forms;
    using System.Text ;
    using System.Threading;
    using System.Collections ;

    namespace _043_Button_Click
    {
        
    ///  <summary>
        
    /// Summary description for Class1.
        
    /// </summary>
        class Class1
        {

            
    ///  <summary>
            
    /// The main entry point for the application.
            
    /// </summary>
            [STAThread]
            
    static void  Main(string[] args)
            {
                
    const  int NORMALWAIT =  10000;
                Process p 
    =  new Process();
                p.StartInfo.FileName 
    =  "notepad";
                p.Start();
                p.WaitForInputIdle(NORMALWAIT);

                
    // Bring up the "About Notepad Window"
                SendKeys.SendWait("%h");
                 p.WaitForInputIdle(NORMALWAIT);
                SendKeys.SendWait(
    "a" );
                p.WaitForInputIdle(NORMALWAIT);

                
    // Locate the Dialog Box
                IntPtr hWnd =
                    ControlHelper.GetDialog(p.MainWindowHandle, 
    "About Notepad");

                
    if (hWnd != IntPtr.Zero)
                {
                    
    // locate the OK button, and click it
                    IntPtr buttonHwnd  = ControlHelper.GetItemHandleByCaption(hWnd,"OK" );
                    
    if (buttonHwnd !=  IntPtr.Zero)
                    {
                        Console.WriteLine(
    "About to click the OK button ");
                        Thread.Sleep(NORMALWAIT
    /3 );
                        ControlHelper.ButtonClick(buttonHwnd);
                        Console.WriteLine(
    "Done clicking the OK button ");
                        Thread.Sleep(NORMALWAIT
    / 3);
                    }
                }

                p.CloseMainWindow();

            }
        }

        
    class  ControlHelper
        {
            
    // Enumeration used to find the dialog box
            public enum windowTypes :  uint
            {
                GW_HWNDFIRST 
    = 0 ,
                GW_HWNDLAST 
    = 1 ,
                GW_HWNDNEXT 
    = 2,
                GW_HWNDPREV 
    = 3,
                GW_OWNER 
    = 4,
                GW_CHILD 
    =  5,
                GW_ENABLEDPOPUP 
    =  6,
            }

            
    // Constant value representing the Button Click Windows Message
            private  const uint BM_CLICK =  0x00F5;

            
    // Windows API DLL Imports
            [DllImport("user32.dll ")]
            
    private static  extern IntPtr GetWindow(IntPtr hWnd, windowTypes uCmd);

            [DllImport(
    " user32", EntryPoint= "GetWindowText")]
            
    public  static extern  int GetWindowText(
                IntPtr hWnd, StringBuilder text, 
    int  count);

            [DllImport(
    "user32" )]
            
    public static  extern int GetWindowTextLength(
                IntPtr hWnd);

            [ DllImport(
    "user32.dll") ]
            
    public static extern  int GetDlgCtrlID(IntPtr hwndCtl);

            [ DllImport(
    " user32.dll") ]
            
    private  static extern IntPtr GetNextDlgTabItem
                (IntPtr hDlg, IntPtr hCtl, 
    bool bPrevious);

            [ DllImport(
    "user32.dll ") ]
            
    private static  extern int GetDlgItemText(
                IntPtr hDlg,
                
    int nIDDlgItem,
                StringBuilder lpString,
                
    int  nMaxCount
                );

            [DllImport(
    "user32.dll ")]
            
    private static  extern int SendNotifyMessage(
                IntPtr hWnd,
                
    uint Msg,
                IntPtr wParam,
                StringBuilder lParam
                );

            [DllImport(
    "user32.dll")]
            
    private static extern  int PostMessage(
                IntPtr hWnd,
                
    uint  Msg,
                IntPtr wParam,
                StringBuilder lParam
                );

            [ DllImport(
    "user32.dll ") ]
            
    private  static extern IntPtr GetNextDlgGroupItem
                (IntPtr hDlg, IntPtr hCtl, 
    bool bPrevious);

            
    // Wrappers for the Windows API functions

            
    public static  string WindowCaption(IntPtr hWnd)
            {
                
    int  length = GetWindowTextLength(hWnd) +  1;
                StringBuilder caption 
    = new  StringBuilder(length);

                
    int result =
                    GetWindowText(hWnd, caption, caption.Capacity);
                
    if (result  != 0)
                {
                    
    return caption.ToString();
                }
                
    else
                {
                    
    return "";
                }
            }

            
    public static IntPtr GetDialog(IntPtr hWnd,  string caption)
            {
                IntPtr hDlg 
    =  GetWindow(hWnd, windowTypes.GW_ENABLEDPOPUP);
                
    if (hDlg !=  IntPtr.Zero && WindowCaption(hDlg) == caption)
                {
                    
    return hDlg;
                }
                
    else
                {
                    
    return IntPtr.Zero;
                }
            }

            
    // Get all of the control handles on the designed dialog box
            public static IntPtr[] GetHandles(IntPtr hDlg)
            {
                ArrayList controlHandles 
    = new  ArrayList();
                IntPtr[] result 
    = null ;

                
    if (hDlg != IntPtr.Zero)
                {
                    IntPtr firstHandle 
    = GetNextDlgTabItem(hDlg, IntPtr.Zero, false );
                    IntPtr hCtl 
    = firstHandle;

                    
    if  (hCtl != IntPtr.Zero)
                    {
                        
    //  tab through all of the controls on this form
                        do  
                        {
                            
    // if this control is part of a group, get all the group members
                            IntPtr subHandle = hCtl;
                            
    do
                            {
                                
    // don't allow duplicates
                                if ( !controlHandles.Contains(hCtl))
                                {
                                    controlHandles.Add(hCtl);
                                }
                                hCtl 
    = GetNextDlgGroupItem(hDlg, hCtl, false);
                            } 
    while (hCtl != subHandle);
                            hCtl 
    = GetNextDlgTabItem(hDlg, hCtl, false);
                        } 
    while (hCtl != firstHandle);


                    }
                    result 
    = (IntPtr[])controlHandles.ToArray(typeof (IntPtr));
                }
                
    return result;
            }

            
    public  static IntPtr GetItemHandleByCaption(IntPtr hDlg,  string caption)
            {
                IntPtr[] itemHandlesArray 
    = GetHandles(hDlg);
                IntPtr result 
    = IntPtr.Zero;

                
    foreach (IntPtr hCtl  in itemHandlesArray)
                {
                    
    string  s = GetDialogItemText(hDlg,hCtl);
                    
    if  (caption == s)
                    {
                        result 
    =  hCtl;
                        
    break;
                    }
                }
                
    return  result;
            }

            
    public static  string GetDialogItemText(IntPtr hDlg, IntPtr hCtl)
            {
                StringBuilder lpString 
    = new StringBuilder();
                
    int id = GetDlgCtrlID(hCtl);
                GetDlgItemText(hDlg, id, lpString, lpString.Capacity );
                
    return lpString.ToString();
            }

            
    public  static void ButtonClick(IntPtr hCtl)
            {
                PostMessage(        
    // SendNotifyMessage will work too
                    hCtl,            // handle to destination control     
                    BM_CLICK,        // message ID     
                    IntPtr.Zero,    // = 0; not used, must be zero    
                    null            // = 0; not used, must be zero 
                    );
            }


        }
    }


--
Happy day, happy life!