Archive for the ‘C#’ Category

  1. Hello, Connector/NET World!

    Posted on 4月 1st, 2013 by cx20

    Connector/NET

    Connector/NET は、.NET ベースの MySQL 接続用 API である。
    以下は C# による Connector/NET ライブラリを使用した MySQL への接続例となっている。

    ソースコード(C# + Connector/NET + MySQL)

    using System;
    using MySql.Data.MySqlClient;
     
    class Hello
    {
        static void Main( String[] args )
        {
            string conStr = "server=localhost;user id=root;password=P@ssW0rd";
            string sqlStr = "SELECT 'Hello, Connector/NET World!' AS Message";
     
            MySqlConnection con = new MySqlConnection(conStr);
            MySqlCommand  cmd = new MySqlCommand(sqlStr, con);
            con.Open();
            MySqlDataReader reader = cmd.ExecuteReader();
            while( reader.Read() )
            {
                Console.WriteLine( reader.GetName(0) );
                Console.WriteLine( "---------------------" );
                Console.WriteLine( reader[0] );
            }
            reader.Close();
            con.Close();
        }
    }

    コンパイル方法

    C:¥> csc /r:MySql.Data.dll Hello.cs

    実行結果

    MESSAGE
    ---------------------
    Hello, Connector/NET World!
  2. Hello, DirectX(C#) World!

    Posted on 7月 28th, 2012 by cx20

    Win32 DirectX(C#)

    DirectX はマイクロソフトが Wnidows 用に開発したマルチメディア処理用 API である。
    .NET Framework 用の DirectX ライブラリとしては、DirectX SDK より入手可能な Managed DirectX がある。
    以下は C# における Managed DirectX アプリケーション の例となっている。

    ソースコード

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using Microsoft.DirectX;
    using Microsoft.DirectX.Direct3D;
     
    public class HelloForm : Form
    {
        private Device device_;
        private PresentParameters presentParam_;
        private Microsoft.DirectX.Direct3D.Font font_;
     
        public HelloForm()
        {
            this.Size = new Size(640, 480);
            this.Text = "Hello, World!";
        }
     
        public bool InitD3D()
        {
            presentParam_ = new PresentParameters();
     
            presentParam_.Windowed = true;
            presentParam_.SwapEffect = SwapEffect.Discard;
     
            device_ = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, presentParam_);
     
            InitFont();
     
            return true;
        }
     
        private void InitFont()
        {
            FontDescription fd = new FontDescription();
     
            fd.Height = 16;
            fd.FaceName = "MS ゴシック";
     
            font_ = new Microsoft.DirectX.Direct3D.Font(device_, fd);
        }
     
        public void Render()
        {
            if (device_ == null)
            {
                return;
            }
     
            device_.Clear(ClearFlags.Target, Color.Blue, 1.0f, 0);
            device_.BeginScene();
     
            font_.DrawText(null, "Hello, DirectX(C#) World!", 10, 10, Color.White);
     
            device_.EndScene();
            device_.Present();
        }
     
        [STAThread]
        public static void Main()
        {
            using (HelloForm form = new HelloForm())
            {
                form.InitD3D();
                form.Show();
     
                while (form.Created)
                {
                    form.Render();
                    Application.DoEvents();
                }
            }
        }
    }

    コンパイル方法

    C:¥> csc ^
        /target:winexe ^
        /platform:x86 ^
        /r:"C:WindowsMicrosoft.NETDirectX for Managed Code1.0.2902.0Microsoft.DirectX.dll" ^
        /r:"C:WindowsMicrosoft.NETDirectX for Managed Code1.0.2902.0Microsoft.DirectX.Direct3D.dll" ^
        /r:"C:WindowsMicrosoft.NETDirectX for Managed Code1.0.2911.0Microsoft.DirectX.Direct3DX.dll" ^
        Hello.cs

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, DirectX(C#) World!                 |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  3. Hello, Win32 GUI(UWSC) World!

    Posted on 7月 17th, 2012 by cx20

    Win32 GUI(UWSC)

    Win32 アプリケーションは Windows 標準 API である Win32 API を使用した Windows アプリケーションである。
    以下は UWSC にて PowerShell を呼び出す機能により C# を使用した Win32 GUI アプリケーション の例となっている。

    ソースコード(UWSC + PowerShell + C# + Win32)

    Option Explicit
     
    Main()
     
    Procedure Main()
        PowerShell( helloBlock, True, True )
    FEnd
     
    TextBlock helloBlock
        $source = @"
    using System;
    using System.Runtime.InteropServices;
     
    public class Hello
    {
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public int x;
            public int y;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }
     
        delegate IntPtr WndProcDelgate(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WNDCLASSEX
        {
            public uint cbSize;
            public uint style;
            public WndProcDelgate lpfnWndProc;
            public Int32 cbClsExtra;
            public Int32 cbWndExtra;
            public IntPtr hInstance;
            public IntPtr hIcon;
            public IntPtr hCursor;
            public IntPtr hbrBackground;
            public string lpszMenuName;
            public string lpszClassName;
            public IntPtr hIconSm;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct PAINTSTRUCT
        {
            public IntPtr hdc;
            public int fErase;
            public RECT rcPaint;
            public int fRestore;
            public int fIncUpdate;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
            public byte[] rgbReserved;
        }
     
        const uint WS_OVERLAPPED = 0x00000000;
        const uint WS_POPUP = 0x80000000;
        const uint WS_CHILD = 0x40000000;
        const uint WS_MINIMIZE = 0x20000000;
        const uint WS_VISIBLE = 0x10000000;
        const uint WS_DISABLED = 0x08000000;
        const uint WS_CLIPSIBLINGS = 0x04000000;
        const uint WS_CLIPCHILDREN = 0x02000000;
        const uint WS_MAXIMIZE = 0x01000000;
        const uint WS_CAPTION = 0x00C00000; // WS_BORDER | WS_DLGFRAME
        const uint WS_BORDER = 0x00800000;
        const uint WS_DLGFRAME = 0x00400000;
        const uint WS_VSCROLL = 0x00200000;
        const uint WS_HSCROLL = 0x00100000;
        const uint WS_SYSMENU = 0x00080000;
        const uint WS_THICKFRAME = 0x00040000;
        const uint WS_GROUP = 0x00020000;
        const uint WS_TABSTOP = 0x00010000;
     
        const uint WS_MINIMIZEBOX = 0x00020000;
        const uint WS_MAXIMIZEBOX = 0x00010000;
     
        const uint WS_TILED = WS_OVERLAPPED;
        const uint WS_ICONIC = WS_MINIMIZE;
        const uint WS_SIZEBOX = WS_THICKFRAME;
        const uint WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
     
        const uint WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
        const uint WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
        const uint WS_CHILDWINDOW = WS_CHILD;
     
        const uint WM_CREATE = 0x0001;
        const uint WM_DESTROY = 0x0002;
        const uint WM_PAINT = 0x000F;
        const uint WM_CLOSE = 0x0010;
        const uint WM_COMMAND = 0x0111;
     
        const uint COLOR_WINDOW = 5;
        const uint COLOR_BTNFACE = 15;
     
        const uint CS_VREDRAW = 0x0001;
        const uint CS_HREDRAW = 0x0002;
     
        const int CW_USEDEFAULT = -2147483648; // ((uint)0x80000000)
     
        const uint SW_SHOWDEFAULT = 10;
     
        const int IDI_APPLICATION = 32512;
        const int IDC_ARROW = 32512;
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern short RegisterClassEx(ref WNDCLASSEX pcWndClassEx);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr CreateWindowEx(uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool UpdateWindow(IntPtr hWnd);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int TranslateMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DispatchMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern void PostQuitMessage(int nExitCode);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
     
        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr TextOut( IntPtr hdc, int x, int y, string lpString, int nCount );
     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr GetModuleHandle(string lpModuleName);
     
        static IntPtr WndProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam)
        {
            PAINTSTRUCT ps = new PAINTSTRUCT();
            IntPtr hdc;
            string strMessage = "Hello, Win32 GUI(UWSC) World!";
     
            switch (uMsg)
            {
                case WM_PAINT:
                    hdc = BeginPaint( hWnd, out ps );
                    TextOut( hdc, 0, 0, strMessage, strMessage.Length );
                    EndPaint( hWnd, ref ps );
                    break;
                case WM_DESTROY:
                    PostQuitMessage(0);
                    break;
                default:
                    return DefWindowProc(hWnd, uMsg, wParam, lParam);
            }
     
            return IntPtr.Zero;
        }
     
        static int WinMain()
        {
            IntPtr hInstance = Marshal.GetHINSTANCE(typeof(Hello).Module);
            const string CLASS_NAME = "helloWindow";
            const string WINDOW_NAME = "Hello, World!";
     
            WNDCLASSEX wcex = new WNDCLASSEX();
            wcex.cbSize = (uint)Marshal.SizeOf(wcex);
            wcex.style = CS_HREDRAW | CS_VREDRAW;
            wcex.lpfnWndProc = new WndProcDelgate(WndProc);
            wcex.cbClsExtra = 0;
            wcex.cbWndExtra = 0;
            wcex.hInstance = hInstance;
            wcex.hIcon = LoadIcon(hInstance, new IntPtr(IDI_APPLICATION));
            wcex.hCursor = LoadIcon(hInstance, new IntPtr(IDC_ARROW));
            wcex.hbrBackground = new IntPtr(COLOR_WINDOW + 1);
            wcex.lpszMenuName = "";
            wcex.lpszClassName = CLASS_NAME;
            wcex.hIconSm = IntPtr.Zero;
     
            RegisterClassEx(ref wcex);
     
            IntPtr hWnd = CreateWindowEx(
                0,
                wcex.lpszClassName,
                WINDOW_NAME,
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                640,
                480,
                IntPtr.Zero,
                IntPtr.Zero,
                wcex.hInstance,
                IntPtr.Zero);
     
            ShowWindow(hWnd, SW_SHOWDEFAULT);
            UpdateWindow(hWnd);
     
            MSG msg = new MSG();
            while (GetMessage(out msg, IntPtr.Zero, 0, 0) != 0)
            {
                TranslateMessage(ref msg);
                DispatchMessage(ref msg);
            }
     
            return (int)msg.wParam;
        }
     
        [STAThread]
        public static int Main()
        {
            return WinMain();
        }
    }
    "@
        Add-Type -Language CSharp -TypeDefinition $source -ReferencedAssemblies ("System.Drawing", "System.Windows.Forms" )
        [void][Hello]::Main()
    EndTextBlock

    実行方法

    C:¥> uwsc /K hello.uws

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, Win32 GUI(UWSC) World!             |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  4. Hello, Win32 GUI(PowerShell) World!

    Posted on 7月 12th, 2012 by cx20

    Win32 GUI(PowerShell)

    Win32 アプリケーションは Windows 標準 API である Win32 API を使用した Windows アプリケーションである。
    以下は PowerShell にて Add-Type コマンドレット経由で C# を呼び出すことにより Win32 API を使用した GUI アプリケーション の例となっている。

    ソースコード

    $source = @"
    using System;
    using System.Runtime.InteropServices;
     
    public class Hello
    {
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public int x;
            public int y;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }
     
        delegate IntPtr WndProcDelgate(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WNDCLASSEX
        {
            public uint cbSize;
            public uint style;
            public WndProcDelgate lpfnWndProc;
            public Int32 cbClsExtra;
            public Int32 cbWndExtra;
            public IntPtr hInstance;
            public IntPtr hIcon;
            public IntPtr hCursor;
            public IntPtr hbrBackground;
            public string lpszMenuName;
            public string lpszClassName;
            public IntPtr hIconSm;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct PAINTSTRUCT
        {
            public IntPtr hdc;
            public int fErase;
            public RECT rcPaint;
            public int fRestore;
            public int fIncUpdate;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
            public byte[] rgbReserved;
        }
     
        const uint WS_OVERLAPPED = 0x00000000;
        const uint WS_POPUP = 0x80000000;
        const uint WS_CHILD = 0x40000000;
        const uint WS_MINIMIZE = 0x20000000;
        const uint WS_VISIBLE = 0x10000000;
        const uint WS_DISABLED = 0x08000000;
        const uint WS_CLIPSIBLINGS = 0x04000000;
        const uint WS_CLIPCHILDREN = 0x02000000;
        const uint WS_MAXIMIZE = 0x01000000;
        const uint WS_CAPTION = 0x00C00000; // WS_BORDER | WS_DLGFRAME
        const uint WS_BORDER = 0x00800000;
        const uint WS_DLGFRAME = 0x00400000;
        const uint WS_VSCROLL = 0x00200000;
        const uint WS_HSCROLL = 0x00100000;
        const uint WS_SYSMENU = 0x00080000;
        const uint WS_THICKFRAME = 0x00040000;
        const uint WS_GROUP = 0x00020000;
        const uint WS_TABSTOP = 0x00010000;
     
        const uint WS_MINIMIZEBOX = 0x00020000;
        const uint WS_MAXIMIZEBOX = 0x00010000;
     
        const uint WS_TILED = WS_OVERLAPPED;
        const uint WS_ICONIC = WS_MINIMIZE;
        const uint WS_SIZEBOX = WS_THICKFRAME;
        const uint WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
     
        const uint WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
        const uint WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
        const uint WS_CHILDWINDOW = WS_CHILD;
     
        const uint WM_CREATE = 0x0001;
        const uint WM_DESTROY = 0x0002;
        const uint WM_PAINT = 0x000F;
        const uint WM_CLOSE = 0x0010;
        const uint WM_COMMAND = 0x0111;
     
        const uint COLOR_WINDOW = 5;
        const uint COLOR_BTNFACE = 15;
     
        const uint CS_VREDRAW = 0x0001;
        const uint CS_HREDRAW = 0x0002;
     
        const int CW_USEDEFAULT = -2147483648; // ((uint)0x80000000)
     
        const uint SW_SHOWDEFAULT = 10;
     
        const int IDI_APPLICATION = 32512;
        const int IDC_ARROW = 32512;
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern short RegisterClassEx(ref WNDCLASSEX pcWndClassEx);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr CreateWindowEx(uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool UpdateWindow(IntPtr hWnd);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int TranslateMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DispatchMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern void PostQuitMessage(int nExitCode);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
     
        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr TextOut( IntPtr hdc, int x, int y, string lpString, int nCount );
     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr GetModuleHandle(string lpModuleName);
     
        static IntPtr WndProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam)
        {
            PAINTSTRUCT ps = new PAINTSTRUCT();
            IntPtr hdc;
            string strMessage = "Hello, Win32 GUI(PowerShell) World!";
     
            switch (uMsg)
            {
                case WM_PAINT:
                    hdc = BeginPaint( hWnd, out ps );
                    TextOut( hdc, 0, 0, strMessage, strMessage.Length );
                    EndPaint( hWnd, ref ps );
                    break;
                case WM_DESTROY:
                    PostQuitMessage(0);
                    break;
                default:
                    return DefWindowProc(hWnd, uMsg, wParam, lParam);
            }
     
            return IntPtr.Zero;
        }
     
        static int WinMain()
        {
            IntPtr hInstance = Marshal.GetHINSTANCE(typeof(Hello).Module);
            const string CLASS_NAME = "helloWindow";
            const string WINDOW_NAME = "Hello, World!";
     
            WNDCLASSEX wcex = new WNDCLASSEX();
            wcex.cbSize = (uint)Marshal.SizeOf(wcex);
            wcex.style = CS_HREDRAW | CS_VREDRAW;
            wcex.lpfnWndProc = new WndProcDelgate(WndProc);
            wcex.cbClsExtra = 0;
            wcex.cbWndExtra = 0;
            wcex.hInstance = hInstance;
            wcex.hIcon = LoadIcon(hInstance, new IntPtr(IDI_APPLICATION));
            wcex.hCursor = LoadIcon(hInstance, new IntPtr(IDC_ARROW));
            wcex.hbrBackground = new IntPtr(COLOR_WINDOW + 1);
            wcex.lpszMenuName = "";
            wcex.lpszClassName = CLASS_NAME;
            wcex.hIconSm = IntPtr.Zero;
     
            RegisterClassEx(ref wcex);
     
            IntPtr hWnd = CreateWindowEx(
                0,
                wcex.lpszClassName,
                WINDOW_NAME,
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                640,
                480,
                IntPtr.Zero,
                IntPtr.Zero,
                wcex.hInstance,
                IntPtr.Zero);
     
            ShowWindow(hWnd, SW_SHOWDEFAULT);
            UpdateWindow(hWnd);
     
            MSG msg = new MSG();
            while (GetMessage(out msg, IntPtr.Zero, 0, 0) != 0)
            {
                TranslateMessage(ref msg);
                DispatchMessage(ref msg);
            }
     
            return (int)msg.wParam;
        }
     
        [STAThread]
        public static int Main()
        {
            return WinMain();
        }
    }
    "@
    Add-Type -Language CSharp -TypeDefinition $source -ReferencedAssemblies ("System.Drawing", "System.Windows.Forms" )
    [void][Hello]::Main()

    実行方法

    C:¥> powershell -file Hello.ps1

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, Win32 GUI(PowerShell) World!       |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  5. Hello, Win32 GUI(C#) World!

    Posted on 7月 9th, 2012 by cx20

    Win32 GUI(C#)

    Win32 アプリケーションは Windows 標準 API である Win32 API を使用した Windows アプリケーションである。
    以下は C# において Win32 API を使用した GUI アプリケーション の例となっている。

    ソースコード

    using System;
    using System.Runtime.InteropServices;
     
    class Hello
    {
        [StructLayout(LayoutKind.Sequential)]
        struct POINT
        {
            public int x;
            public int y;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public IntPtr wParam;
            public IntPtr lParam;
            public uint time;
            public POINT pt;
        }
     
        delegate IntPtr WndProcDelgate(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WNDCLASSEX
        {
            public uint cbSize;
            public uint style;
            public WndProcDelgate lpfnWndProc;
            public Int32 cbClsExtra;
            public Int32 cbWndExtra;
            public IntPtr hInstance;
            public IntPtr hIcon;
            public IntPtr hCursor;
            public IntPtr hbrBackground;
            public string lpszMenuName;
            public string lpszClassName;
            public IntPtr hIconSm;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct PAINTSTRUCT
        {
            public IntPtr hdc;
            public int fErase;
            public RECT rcPaint;
            public int fRestore;
            public int fIncUpdate;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
            public byte[] rgbReserved;
        }
     
        const uint WS_OVERLAPPED = 0x00000000;
        const uint WS_POPUP = 0x80000000;
        const uint WS_CHILD = 0x40000000;
        const uint WS_MINIMIZE = 0x20000000;
        const uint WS_VISIBLE = 0x10000000;
        const uint WS_DISABLED = 0x08000000;
        const uint WS_CLIPSIBLINGS = 0x04000000;
        const uint WS_CLIPCHILDREN = 0x02000000;
        const uint WS_MAXIMIZE = 0x01000000;
        const uint WS_CAPTION = 0x00C00000; // WS_BORDER | WS_DLGFRAME
        const uint WS_BORDER = 0x00800000;
        const uint WS_DLGFRAME = 0x00400000;
        const uint WS_VSCROLL = 0x00200000;
        const uint WS_HSCROLL = 0x00100000;
        const uint WS_SYSMENU = 0x00080000;
        const uint WS_THICKFRAME = 0x00040000;
        const uint WS_GROUP = 0x00020000;
        const uint WS_TABSTOP = 0x00010000;
     
        const uint WS_MINIMIZEBOX = 0x00020000;
        const uint WS_MAXIMIZEBOX = 0x00010000;
     
        const uint WS_TILED = WS_OVERLAPPED;
        const uint WS_ICONIC = WS_MINIMIZE;
        const uint WS_SIZEBOX = WS_THICKFRAME;
        const uint WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
     
        const uint WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
        const uint WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
        const uint WS_CHILDWINDOW = WS_CHILD;
     
        const uint WM_CREATE = 0x0001;
        const uint WM_DESTROY = 0x0002;
        const uint WM_PAINT = 0x000F;
        const uint WM_CLOSE = 0x0010;
        const uint WM_COMMAND = 0x0111;
     
        const uint COLOR_WINDOW = 5;
        const uint COLOR_BTNFACE = 15;
     
        const uint CS_VREDRAW = 0x0001;
        const uint CS_HREDRAW = 0x0002;
     
        const int CW_USEDEFAULT = -2147483648; // ((uint)0x80000000)
     
        const uint SW_SHOWDEFAULT = 10;
     
        const int IDI_APPLICATION = 32512;
        const int IDC_ARROW = 32512;
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern short RegisterClassEx(ref WNDCLASSEX pcWndClassEx);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr CreateWindowEx(uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool UpdateWindow(IntPtr hWnd);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int TranslateMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DispatchMessage([In] ref MSG lpMsg);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern void PostQuitMessage(int nExitCode);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr BeginPaint(IntPtr hWnd, out PAINTSTRUCT lpPaint);
     
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
     
        [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr TextOut( IntPtr hdc, int x, int y, string lpString, int nCount );
     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr GetModuleHandle(string lpModuleName);
     
        static IntPtr WndProc(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam)
        {
            PAINTSTRUCT ps = new PAINTSTRUCT();
            IntPtr hdc;
            string strMessage = "Hello, Win32 GUI(C#) World!";
     
            switch (uMsg)
            {
                case WM_PAINT:
                    hdc = BeginPaint( hWnd, out ps );
                    TextOut( hdc, 0, 0, strMessage, strMessage.Length );
                    EndPaint( hWnd, ref ps );
                    break;
                case WM_DESTROY:
                    PostQuitMessage(0);
                    break;
                default:
                    return DefWindowProc(hWnd, uMsg, wParam, lParam);
            }
     
            return IntPtr.Zero;
        }
     
        static int WinMain(string[] args)
        {
            IntPtr hInstance = Marshal.GetHINSTANCE(typeof(Hello).Module);
            const string CLASS_NAME = "helloWindow";
            const string WINDOW_NAME = "Hello, World!";
     
            WNDCLASSEX wcex = new WNDCLASSEX();
            wcex.cbSize = (uint)Marshal.SizeOf(wcex);
            wcex.style = CS_HREDRAW | CS_VREDRAW;
            wcex.lpfnWndProc = new WndProcDelgate(WndProc);
            wcex.cbClsExtra = 0;
            wcex.cbWndExtra = 0;
            wcex.hInstance = hInstance;
            wcex.hIcon = LoadIcon(hInstance, new IntPtr(IDI_APPLICATION));
            wcex.hCursor = LoadIcon(hInstance, new IntPtr(IDC_ARROW));
            wcex.hbrBackground = new IntPtr(COLOR_WINDOW + 1);
            wcex.lpszMenuName = "";
            wcex.lpszClassName = CLASS_NAME;
            wcex.hIconSm = IntPtr.Zero;
     
            RegisterClassEx(ref wcex);
     
            IntPtr hWnd = CreateWindowEx(
                0,
                wcex.lpszClassName,
                WINDOW_NAME,
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                640,
                480,
                IntPtr.Zero,
                IntPtr.Zero,
                wcex.hInstance,
                IntPtr.Zero);
     
            ShowWindow(hWnd, SW_SHOWDEFAULT);
            UpdateWindow(hWnd);
     
            MSG msg = new MSG();
            while (GetMessage(out msg, IntPtr.Zero, 0, 0) != 0)
            {
                TranslateMessage(ref msg);
                DispatchMessage(ref msg);
            }
     
            return (int)msg.wParam;
        }
     
        [STAThread]
        static int Main(string[] args)
        {
            return WinMain( args );
        }
    }

    コンパイル方法

    C:¥> csc /target:winexe Hello.cs

    実行結果

    +------------------------------------------+
    |Hello, World!                    [_][~][X]|
    +------------------------------------------+
    |Hello, Win32 GUI(C#) World!               |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    |                                          |
    +------------------------------------------+
  6. Hello, Win32 API(Cobra) World!

    Posted on 6月 23rd, 2012 by cx20

    Win32 API(Cobra)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    Ver0.8 現在、Cobra には Win32 API を直接呼び出す機能は実装されていないが、C# を経由することで、Win32 API を呼び出すことが可能となっている。

    ソースコード(C#)

    using System;
    using System.Runtime.InteropServices;
     
    namespace Win32Lib
    {
        public class Win32
        {
             [DllImport("user32.dll", CharSet=CharSet.Auto)]
             public extern static uint MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
        }
    }

    コンパイル方法(C#)

    C:¥> csc /target:library Win32Lib.cs

    ソースコード(Cobra)

    use Win32Lib
     
    class Hello
     
        def main is shared
            Win32.messageBox( IntPtr.zero, "Hello, Win32 API(Cobra) World!", "Hello, World!", 0 )

    実行方法

    C:¥> cobra hello.cobra

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(Cobra) World!
    ---------------------------
    OK   
    ---------------------------
  7. Hello, COM(C#) World!

    Posted on 5月 17th, 2012 by cx20

    COM(C#)

    COM(Component Object Model)はマイクロソフトの提唱するプログラム部品の仕様である。
    COM を用いて開発された部品であれば言語を問わず利用することができる。
    以下は C# による COM クライアント(事前バインディングならびに実行時バインディング)の例となっている。

    ソースコード(事前バインディング)

    using System;
    using System.Runtime.InteropServices;
    using Shell32;
     
    class Hello
    {
        static void Main(String[] args)
        {
            Shell shell = new Shell();
            Object vRootFolder = (long)ShellSpecialFolderConstants.ssfWINDOWS;
            Folder folder = shell.BrowseForFolder(0, "Hello, COM(C#) World!", 0, vRootFolder);
            if (folder != null)
            {
                Marshal.ReleaseComObject(folder);
            }
            Marshal.ReleaseComObject(shell);
        }
    }

    コンパイル方法(事前バインディング)

    C:¥> SET PATH=C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin;%PATH%
    C:¥> tlbimp %SystemRoot%\system32\shell32.dll /out:Shell32.dll
    C:¥> csc /r:Shell32.dll Hello.cs

    ソースコード(実行時バインディング)

    using System;
    using System.Reflection;
    using System.Runtime.InteropServices;
     
    class Hello
    {
        static void Main(String[] args)
        {
            Type objType = Type.GetTypeFromProgID("Shell.Application"); 
            Object shell = Activator.CreateInstance(objType);
            Object[] param = { 0, "Hello, COM(C#) World!", 0, 36 };
            Object folder = shell.GetType().InvokeMember( 
                "BrowseForFolder", BindingFlags.InvokeMethod, null, shell, param );
            if (folder != null)
            {
                Marshal.ReleaseComObject(folder);
            }
            Marshal.ReleaseComObject(shell);
        }
    }

    コンパイル方法(実行時バインディング)

    C:¥> csc Hello.cs

    実行結果

    +----------------------------------------+
    |Browse For Folder                    [X]|
    +----------------------------------------+
    | Hello, COM(C#) Wolrd!                  |
    |                                        |
    | +------------------------------------+ |
    | |[Windows]                           | |
    | | +[addins]                          | |
    | | +[AppCompat]                       | |
    | | +[AppPatch]                        | |
    | | +[assembly]                        | |
    | |     :                              | |
    | |     :                              | |
    | |     :                              | |
    | +------------------------------------+ |
    | [Make New Folder]    [  OK  ] [Cancel] |
    +----------------------------------------+
  8. Hello, Win32 API(C#) World!

    Posted on 4月 23rd, 2012 by cx20

    Win32 API(C#)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は C# にて DllImport 属性を用いた呼出し例である。

    ソースコード

    using System;
    using System.Runtime.InteropServices;
     
    class Hello
    {
         [DllImport("user32.dll", CharSet=CharSet.Auto)]
         private extern static uint MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
         static void Main(string[] args)
        {
            MessageBox( new IntPtr(0), "Hello, Win32 API(C#) World!", "Hello, World!", 0 );
        }
    }

    「文字セット」に「Auto」を指定した場合は「関数定義」「プラットフォーム」に応じて、呼び出される API 関数名が自動判別される。
    「文字セット」に「Ansi」もしくは「Unicode」を指定した場合それぞれ、末尾が “A” / “W” の API 関数名として自動判別される。

    文字セット指定 関数定義 プラットフォーム 文字変換 判別 API関数名
    Auto MessageBox Windows 9x系 ANSI “A” MessageBoxA
    Auto MessageBox Windows NT系 Unicode “W” MessageBoxW
    Ansi または 省略 MessageBox ANSI “A” MessageBoxA
    Ansi または 省略 MessageBoxA ANSI MessageBoxA
    Unicode MessageBox Unicode “W” MessageBoxW
    Unicode MessageBoxW Unicode MessageBoxW

    また、Win32 データ型と C# データ型の対応は主に以下のようになっている。文字関連の型に関しては文字セット指定が必要なことに注意。

    Win32 データ型 C/C++ データ型 .NET データ型 C# データ型
    HANDLE void * IntPtr
    BYTE unsigned char Byte byte
    SHORT short Int16 short
    WORD unsigned short UInt16 ushort
    INT int Int32 int
    UINT unsigned int UInt32 uint
    LONG long Int32 int
    BOOL int Int32 int
    DWORD unsigned long UInt32 uint
    ULONG unsigned long UInt32 uint
    CHAR char Char (Ansi) char (Ansi)
    WCHAR wchar_t Char (Unicode) char (Unicode)
    LPSTR char * StringBuilder (Ansi)
    LPCSTR const char * String (Ansi) string (Ansi)
    LPWSTR wchar_t * StringBuilder (Unicode)
    LPCWSTR const wchar_t * String (Unicode) string (Unicode)
    FLOAT float Single float
    DOUBLE double Double double

    コンパイル方法

    C:¥> csc Hello.cs

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(C#) World!
    ---------------------------
    OK   
    ---------------------------
  9. Hello, ASP.NET Razor World!

    Posted on 2月 11th, 2012 by cx20

    ASP.NET Razor

    Razor は ASP.NET の新しい Web ページ記述構文である。
    ASP や PHP のように HTML の中にスクリプトを埋め込むように記述できるという特徴がある。
    実際の記述コードの言語としては、C# や Visual Basic(VB.NET)が用いられる。
    実行環境として ASP.NET MVC 3 もしくは WebMatrix が必要。

    ソースコード(C# による Razor 記法)

    @{
        var msg = "ASP.NET Razor";
    }
    <html>
      <head>
        <title>Hello, World!</title>
      </head>
      <body>
        <p>Hello, @msg World!</p>
      </body>
    </html>

    ソースコード(Visual Basic による Razor 記法)

    @Code
        Dim msg = "ASP.NET Razor"
    End Code
    <html>
      <head>
        <title>Hello, World!</title>
      </head>
      <body>
        <p>Hello, @msg World!</p>
      </body>
    </html>

    上記 Razor 記法のコードは、以下の .NET のコードに相当する。実行時に .NET アセンブリにコンパイルされ実行される。

    ソースコード(C#)

    namespace ASP {
        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Linq;
        using System.Net;
        using System.Web;
        using System.Web.Helpers;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.WebPages;
        using System.Web.WebPages.Html;
        using WebMatrix.WebData;
        using WebMatrix.Data;
     
        public class _Page_hello_cshtml : System.Web.WebPages.WebPage {
            public _Page_hello_cshtml() {
            }
     
            protected System.Web.HttpApplication ApplicationInstance {
                get {
                    return ((System.Web.HttpApplication)(Context.ApplicationInstance));
                }
            }
     
            public override void Execute() {
                var msg = "ASP.NET Razor";
                WriteLiteral("<html>rn<head>rn<title>Hello, World!</title>rn</body>rn<body>rn<p>Hello, ");
                Write(msg);
                WriteLiteral(" World!</p>rn</body>rn</html> ");
            }
        }
    }

    実行方法

    1. IIS の公開フォルダ に配置
    2. ブラウザで表示
       http://localhost/doc/hello.cshtml … C# の場合
       http://localhost/doc/hello.vbhtml … VB の場合

    実行結果

    Hello, ASP.NET Razor World!
  10. Hello, C# World!

    Posted on 12月 3rd, 2011 by cx20

    C#

    C# はマイクロソフトが .NET Framework 環境向けに作成したオブジェクト指向プログラミング言語である。当初は COOL となるはずだったが、他の製品で使われている為に変更された。「#」は「++++」を表すとの説がある。
    基本的には Windows 向けの言語だが、UNIX 環境向けの .NET Framework 互換プロジェクト「Mono」により他の OS でも動作できるようになってきている。

    ソースコード

    using System;
     
    class Hello 
    {
        static void Main( string[] args ) 
        {
            Console.WriteLine( "Hello, C# World!" );
        }
    }

    コンパイル&実行方法(Mono)

    $ mcs Hello.cs
    $ mono Hello.exe

    コンパイル&実行方法(.NET Framework)

    C:¥> csc Hello.cs
    C:¥> Hello

    実行結果

    Hello, C# World!