SharpDevelop 界面


SharpDevelop 安裝流程
一、安裝：
   1.安裝.NET framework SDK
   2.安裝SharpDevelop=>安裝後第一次開啟=>參考安裝注意事項
   3.繁體中文：依據中文化檔案說明處理
   4.開啟SharpDevelop=>Tools=>option＝>設定UI為BIG5=>確定
   5.重新開啟SharpDevelop程式
   6.安裝OK
二、使用Sharpdevelop：
   1.開啟新專案=>C#=>windows專案
   2.全選ebook程式碼=>貼上=>執行
   ※這是無用其他元件的程式執行方式


SharpDevelop 安裝注意事項

*安裝前準備工作：

 (1)下載Microsoft𦲷 .NET Framework 1.1 版可轉散發套件(23714 KB)：

    請選擇「繁體中文版」下載， 網址：

    http://www.microsoft.com/downloads/details.aspx?FamilyId=262D25E3-F589-4842-8157-034D1E7CF3A3&displaylang=en

    .NET Framework 1.1 版可轉散發套件包含了執行以 .NET Framework 開發的應用程式所

    需的一切項目。

 (2)下載Microsoft𦲷 .NET Framework SDK 1.1 版(119493 KB)：

    請選擇「繁體中文版」下載，網址：

         http://www.microsoft.com/downloads/details.aspx?FamilyId=9B3A2CA6-3647-4070-9F41-A333C6B9181D&displaylang=en

    Microsoft𦲷 .NET Framework 軟體開發套件 (Software Development Kit，SDK) 1.1 版

    包含了開發人員撰寫、建置、測試和部署 .NET Framework應用程式所需的一切項目

    (文件、範例和命令列工具及編譯器) 。安裝 .NET Framework SDK 之前，您必須先安裝

        .NET Framework 1.1 版可轉散發套件。

 (3)SharpDevelop(簡稱#Develop) 官方網站：

    分為安裝檔與原始碼下載，使用者只需下載「安裝檔」即可。

    安裝檔(4914 KB)：http://www.icsharpcode.net/OpenSource/SD/Download/GetFile.aspx?What=Setup

    官方網址：http://www.icsharpcode.net/OpenSource/SD/Download/

*如果你有前一版的SharpDevelop，請先刪除“.ICSharpCode”資料夾，
此資料夾在使用者application data資料夾中。
*第一次使用：依據畫面，先建立資料庫
注意事項：若不建立資料庫，則無法實現以下功能：
1.程式碼自動提示視窗。
2.表單視窗設計編輯，將不會顯示。


SharpDevelop 技巧提示
Topic | Issue
New Class Wizard | Maintain or write a new New Class wizard (see new src\AddIns\Wizards\NewClassWizard and new file dialog)
Pretty Printer | Finish the pretty printer (see SharpRefactory in src\Libraries\SharpRefactory)
Optimize addin-tree loading speed | Currently XML DOM is used to load the addin tree but using the XmlTextReader directly would speed up the loading if you want to take this job see the Core in src\Main\Core)
Optimize project loading speed | Currently XML DOM is used to load the projects and combines but using the XmlTextReader directly would speed up the loading if you want to take this job see the Base project in src\Main\Base (especially Internal\Project)
Debugger | Help us with the debugger. We have started a debbug but we need help. C++ skills are required. For a debugger example look in the Microsoft.NET/SDK/v1.1/Tool Developers Guide/Samples/debugger directory. But don't take ANY code from there (licensing problems).
Subversion plugin | Subversion is a version control system that is used for the #develop development. But we need a plugin for that. Don't wrap the command line client instead use the subversion libraries. There is already a project for Visual Studio.NET called Ankh you should take their NSvn sources. The Ankh plugin and the underlying Subversion interop sources should be a good starting point.
Project Converter | Write a C# Builder project converter. You can plug in into the project converter infrastructure. (see src\AddIns\Misc\ProjectImporterExporter)
Backend Bindings | Maintain the Java backend binding
Translation | Help to translate #D contact Christoph Wille, christophw@alphasierrapapa.com regarding this issue (even report spelling errors)
ReportBugs | If you find bugs report them to Mike Krueger, mike@icsharpcode.net try to report the same bug again and again this increases the chance that it gets done sooner


SharpDevelop RC2的BUG注意：
1.「AxImp.exe轉換COM元件」為NET視覺元件，使用時，
視窗設計與程式碼編輯器切換，會造成「NET視覺元件」，
被移除現象。
解決方式：不儲存，關閉專案，在開啟。
若切換至程式碼編輯器，則會被修改，無該視覺元件。
2.「AxImp.exe轉換COM元件」為NET視覺元件安裝後，
因SharpDevelop RC2開啟新專案或SharpDevelop RC2關閉，
找不到NET視覺元件的錯誤訊息出現。
解決方式：
(a)輕微：SharpDevelop RC2關閉，再開啟即可。
(b)持續錯誤：SharpDevelop RC2開啟元件管理，移除元件後，
關閉 SharpDevelop RC2，再開啟。
(表示該元件，建議不以視覺化元件方式使用！)
3.SharpDevelop RC2專案命名，英文字之間建議不使用空白字元，
會造成無法編譯現象。
4.SharpDevelop RC2程式碼編輯器，復原功能，不能太多次，
亦造成程式碼混亂。

其他問題，可以到此先問問看：
 http://www.icsharpcode.net/OpenSource/SD/Forum/forum.asp?FORUM_ID=25

或
Windows Forms ActiveX Control Importer (Aximp.exe)
 http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfWindowsFormsActiveXControlImporterAximpexe.asp

或
Cannot Add ActiveX Control to Toolbox
 http://support.microsoft.com/default.aspx?scid=kb;en-us;320780

該網站的#D原始碼，可用#D開啟...亦可參考
 http://www.icsharpcode.net/OpenSource/SD/


SharpDevelop 1.0 修正摘要
#develop 1.0.0.1550 (9/12/2004)
  • Bug fix in output / task pane for compilation
  • Translation updates

#develop 1.0.0.1543 (9/11/2004)

  • Ctrl+Space for VB.NET
  • Direct import of VS.NET .csproj and .vbproj files
  • Code converter improvements
  • NUnit 2.2 integrated
  • Bug fixes

#develop Fidalgo RC3 (8/23/2004)

  • Configuration selection added to toolbar
  • New Class Wizard rewrite
  • C# to VB.NET conversion (and vice versa) fixes
  • Bug fixes across the board

#develop Fidalgo RC2 (6/27/2004)

  • Bug fixes (details see Subversion change log)
  • Code completion: bug fixing, regression checks
  • Setup: register file types, GAC assembly install, size

#develop Fidalgo RC1 (6/16/2004)

  • Entire project conversion VB.NET to C# and vice versa
  • Project import now works for ASP.NET projects
  • Bug fixes (details see Subversion change log)
  • Performance improvements (details see Subversion change log)
  • New setup: OS restrictions are enforced (Windows 2000+)

#develop Fidalgo Beta 1 (5/5/2004)

  • Ctrl+Space completion
  • Folding fully integrated
  • NUnit integration (via a pad)
  • Assembly Analyzer
  • C++.NET, ILAsm, WiX backend bindings
  • Mini Class Browser panel added to source views
  • VB.NET to C# converter included
  • Alt+Ins code generator revamped (formerly Ctrl+W)
  • Improvements to File Templates
  • Improvements to VS.NET exporter/importer (VB.NET especially)
  • Printing support added
  • New DockPanel Suite integrated, Magic library entirely removed

0.99b Beta (3/3/2004)

  • Improvements of C# and VB.NET Forms Designers
  • Improvements to VB.NET Code Completion
  • Improvements of the VS.NET Import/Export Feature
  • Install/Uninstall batch files for Nunit and NProf
  • C# Project Options Dialog Changed

0.99 Beta (2/20/2004)

  • VB.NET Forms Designer
  • VB.NET Code Completion
  • Database scout for exploring databases (needs current MDAC on your machine!)
  • C# code completion improvements (eg externs and array return types)
  • Various forms designer related issues fixed such as main menu bugs
  • Tool updates: NAnt, NUnit, NProf, NSIS installer

0.98 Beta (10/23/2003)

  • Rewrite of the text editor
  • Syntax hightlighting definition editor added
  • Code completion db wizard cycles #develop on initial startup (better performance)
  • Improvements to #assembly and assembly scout
  • Icons for menus and toolbars have been changed (in general: lots of UI improvements)
  • Code completion improvements

0.97 Beta (09/12/2003)

  • MagicLibrary menus removed for stability and performance reasons
  • UtilityLibrary toolbars removed and exchanged with CommandBars library
  • Improved #coco parser generator
  • Improved lexer layer
  • Type resolver improved
  • Lots of missing localizations added
  • CSharpParser.dll replaced with #refactory
  • Switched from multiple layout manager to SDI
  • NUnit 2.1 integration
  • NProf integration
  • Forms Designer bug fixes
  • Option panel and project property dialog boxes sport common look and feel
  • IViewContent changes for documents with multiple views
  • Directory layout changes

0.96 Beta (08/23/2003)

  • Faster loading
  • Forms Designer menu editor added
  • C# to VB.NET converter
  • User controls are automatically reloaded in referencing project (on build)
  • Before and After Build scripts added
  • Component selection dropdown added to property grid
  • Property grid context menu
  • Tooltips in task pane
  • File reload (Ctrl+U) prompts for reload
  • Sidebar configuration dialog
  • Assembly Scout reworked

0.95 Beta (04/30/2003)

  • New exception dialog
  • "Module" is now a compile target for both C# and VB.NET
  • Various class browser fixes
  • Improvements in the RegExTk

0.94b Beta (02/03/2003)

  • Works on Windows 98 again (FileSystemWatcher is optional)
  • Keys which are reached via AltGr work now ("@-Bug")
  • Toolbox fixed when multiple forms are open
  • Localized help files work (ms-help URI issue)
  • Core compiles on Mono

0.94 Beta (01/30/2003)

  • Added Code AutoInsert feature (Ctrl+W)
  • Events can now be added via the forms designer
  • .NET Framework SDK help and DirectX 9 help can now be integrated (Markus Palme)
  • Custom controls option for the #develop forms designer (Denis Erchoff)
  • Added Xml Documentation preview feature (Ctrl+Q)
  • Included initial version of a VS.NET solution importer
  • The #develop core has been split out into a separate assembly
  • Basic HTML Editor implemented
  • #Refactory and #ZipLib included in the #develop project
  • Updates to #Unit
  • Project templates expanded to support creating of full-featured combines
  • New Start Page has been added
  • Added Projects and Combines option panel
  • Expanded the toolbar with new icons and design

0.93 Beta (12/19/2002)

  • Assembly scout (object browser) thoroughly reworked by Georg Brandl
  • Regular Expression toolkit allows to generate assemblies (Markus Palme)
  • More templates have been added
  • Bookmark fixes
  • Chinese translations added (traditional & simplified)
  • New Register file types panel in the Options dialogbox
  • Gutter reworked (look & feel)
  • RTF Cut/Copy/Paste
  • Forms Designer: control sizing bugs fixed
  • Lots of small bug fixes

0.92 Beta (10/25/2002)

  • Forms designer refactored
  • Included new NDoc version
  • 'Long delay' bug when opening large non C# projects fixed
  • Enum code completion crash bug fixed
  • The cursor+tab keys now work in the forms designer (Cut/Copy/Paste too)
  • The core now recognizes a load sequence
  • Bugfixes in the COM reference import code
  • New VBFormattingStrategy
  • Forms Designer: new XmlGenerator - XML Form format changed
  • Java/VB.NET project structures refactored
  • Removed #cvs and #ziplib from the source tree (SharpCvs no longer supported)

0.91 Beta (9/22/2002)

  • Improvements to the forms designer (Cut/Copy/Paste works, Format menu, selection, context menus)
  • Improvements to the type resolver for code completion
  • Setting the startup project works
  • Search & Replace has been refactored
  • Find in Files added
  • Wildcard search strategy added
  • COM Reference panel fixed
  • Observed file save methods implemented
  • Regular Expressions Toolkit (see Tools menu)
  • VB.DOC integration (Markus Palme)

0.90 Beta (9/5/2002)

  • Code Completion and Method Insight added
  • Improvements to the Forms Designer: C# and VB.NET code generation
  • COM References are integrated, thanks to Poul Staugaard
  • Reflection Parser Layer and persistence
  • Added IME support, thanks to Shinsaku Nakagawa
  • Help browser is improved, now shipping with #ziplib help too
  • Code Completion Database Wizard added
  • Changed the csc/vbc exe path get routine (used to use the registry)
  • Ambiences added
  • IsValidFileName added to FileUtilityService
  • Option dialogs and wizards changed in style and size
  • Text area control refactoring

0.89 Beta (8/18/2002)

  • Initial implementation of a Windows Forms Designer (help appreciated)
  • Support for Mono: you can now choose either csc.exe or mcs.exe, as well as the execution environment
  • Folding is re-integrated
  • XML formatting strategy
  • Object browser was refactored by Markus Palme
  • #develop help is integrated with a help browser
  • Project options dialog redesigned
  • Toolbar is now more functional
  • C# backend binding: treat warnings as errors passed to csc.exe
  • Parser refactoring and new parser data structures
  • NDoc works reliably in exe and source distributions
  • Namespace cleanups
  • Project browser refactoring allows for more varied backend bindings
  • Project file format changed to match new project subsystem

0.88b Beta (5/29/2002)

  • Limit of 2178 lines per file is removed
  • GAC assemblies correctly included in build runs
  • Tool Scout reworked
  • Read-only attributes on files or backup copies no longer throw exceptions
  • Save dirty files bug fixed for SDI
  • GAC assemblies correctly display in object browser
  • Search in open files and project fixed

0.88a Beta (4/24/2002)

  • Regular expression search added
  • Code completion and Class Scout are back for C#
  • Path dependency removed - C# compiler is automatically located
  • Load/Save options panel (line terminators for other platforms now supported)
  • #unit has been integrated (powerful unit testing framework)

0.87c Beta (2/20/2002)

  • Setup program for SharpDevelop (thanks to Brent R. Matzelle)
  • New Class Wizard from Donald Kackman
  • New SDI layout preview (try it in Tools/Options/Menu Style)
  • Bug fixes (details in ChangeLog.txt)

0.87b Beta (2/3/2002)

  • The "state" of text files is saved & restored. (bookmarks, caret, highlighting, etc.)
  • External tools working on all OS's
  • PHP and C++ syntax highlighting added
  • Bugs fixed that were present in .87a

0.87a Beta (1/22/2002)

  • New internal TextRepresentation data structure
  • New search & replace data structure
  • Preview of add-in infrastructure

0.85 Milestone (12/14/2001)

  • Class Browser reintroduced
  • Export project to HTML (see samples here )
  • NANT included to build SharpDevelop
  • Visual CVS preview
  • UI changes: VS.NET-style flat status bar added, standard UI to internal Web browser
  • Bug fixes: fixed many exception-generating scenarios

0.80 Milestone (9/28/2001)

  • New options dialog boxes (IDE and project)
  • 'Deploy Project' functionality added
  • Side bar with drag&drop support (actually called Toolbar)
  • Included DOC.NET, a documentation generator for C# programs
  • Linked with the Alexandria library for new GUI features
  • SharpDevelop configuration is now saved in user's Application Data folder instead of My Documents
  • For more detailed changes, see ChangeLog.txt in the docs folder

0.75 Beta, Interim Beta (8/3/2001)

  • Preview of Code Completion (works with Framework classes only)
  • Testing framework compatible with NUnit integrated
  • Integrated CVS support via NetCvsLib
  • Translations for German, French, Spanish and more (see docs/languages/ folder)
  • Workspace state is now saved with project
  • Combines ("super projects") added (can contain other projects)
  • Comment tag inserter added (use /* or /// comments and you'll see)
  • Unicode now supported
  • Performance enhancements
  • Volume labels are displayed in the File Scout
  • Reloading files from disk works with Ctrl+U
  • All Yes/No/Cancel dialog boxes are gone
  • For more detailed changes, see ChangeLog.txt in the docs folder

0.70 Beta, .NET SDK Beta 2 Release (6/20/2001)

  • Entirely new File and Project Template architecture
  • Localization of the UI to German, Italian and Portugese
  • Language Modules, supporting C# and VB.NET
  • Standard, Office 2000 and VS.NET-style menus
  • Docking toolbar/window support
  • Reference browser
  • Internal Web browser
  • Bugfixes, more exception handling code

0.60beta Milestone 1 (2/7/2001)

  • File Scout added
  • Class Scout added
  • Replace dialog is working
  • HTML/XML viewer included
  • Dialogs for New File & New Project
  • Rudimentary resource file editor included
  • Syntax coloring for "embedded" languages
  • Tons of bugfixes

0.52beta (12/15/2000)

  • file filter is now configurable
  • form start positions are now saved in the config file
  • some minor bug fixing & spell checking ...

0.51beta

  • Tip of the day box added
  • Options became one menu item (the seperate options aren't removed, because I tested this not thoroughly ...)

0.5beta

  • some syntax highlighting bugs fixed
  • line number view is a separate class / bookmarks are shown when line numbers are turned off
  • Menu item icons (very important for stability & speed and it looks fine)

0.41beta - some bugfixes :
  • project loading bug fixed
  • empty file load bug fixed
  • window menu bug fixed
  • some more bugs fixed, which I can't remember
  • new word count dialog, menu item descriptions

0.4beta

  • new/updated event system, same base class for : MenuActions, EditActions and Plugins
  • basic plugin support
  • XML definitions for MenuActions / EditActions
  • the paths in your project file are now relative, you can copy your project to any location, from now on the Sharp Develop project file is part of the distribution. (old projects are converted automatically)

0.3beta

  • More complex syntax highlighting, now supports highlighting for HTML and XML and is able to support a wide range of highlighting schemes.
  • faster scrolling routines
  • Mouse wheel support
  • FileWatcher added (the prompt for reload thing, when a file has been changed)
  • HTML exporter
  • In the Project Explorer should now work:
    • adding a new directory (isn't created until you put a file in it)
    • renaming files/directories
    • adding files

0.2alpha

  • Customizeable Tool menu
  • Updates in: Project Explorer, Find dialog
  • Bookmarks
  • Code templates
  • XML files for config / projects
  • Default libraries (the compiler doesn't notability slow down if I include ALL (I hope) DLL's, no more "which DLL do I need ?" questions, if I forgot to include some DLL's write me (omni_brain@hotmail.com) you can find the definition in the "SharpDevelop-options.xml" file)
  • Compile error output window - now you can see (and jump to) your erros in the IDE itself
  • many various little menu options & bugfixes
  • Syntax highlighting is now configurable (through XML file options/Syntax.xml)

09/11/2000 - Project Start


用 NDoc 來產生文件

NDOC- http://ndoc.sourceforge.net/ 是一個幫助你把 xx.dll 以及 xx.dll.xml 這兩個檔案 或者是從vs.net.sln中導入 來產生線上文件和 xx.chm 的工具。

基本的用法是在 #D 的專案屬性裡，編譯那裡選擇文件輸出為 xx.dll.xml ，然後編譯。那麼程式中的註解編譯後就成 xx.dll.xml 了。

用 NDOC Add 這個 xx.dll 和 xx.dll.xml 然後修改下面的一些選項，就可以compile了。通常這個會編譯到一個單獨的 doc\ 中。裡面有一打堆的 .html 和 .hhp 等一些檔案 。 當然還有 xx.chm 檔案（要先安裝 HTMLHELP ）。

效果如下：

http://www.contextboundmodel.net/doc/index.html

編譯出來的chm如下

http://www.contextboundmodel.net/doc/cbm.chm


什麼是Unit Tests(單元測試)？

簡單點說，單元測試就是測試代碼撰寫者依據其所設想的方式執行是否產生了預期的結果。

在程式設計過程中會有許多種測試，單元只是其中的一種，單元測試並不能保證程式是完美無缺的，但是在所有的測試中，單元測試是第一個環節，也是最重要的一個環節。單元測試是一種由程式師自行測試的工作。

NUnit是一個為Net準備的自動化單元測試框架，它的作用就是幫助你方便的完成單元測試工作，同鼎鼎有名的JUnit一樣，都是xUnit家族的成員。它的下載位址是：http://www.nunit.org。它的兄弟姐妹還有：nunitasp: http://nunitasp.sourceforge.net( for Asp.Net) 和csUnit

NUnit Framework(NUnit 單元測試框架)簡介

NUnit 2.1是非常不一樣的版本。其他的xUnit家族版本通常都有一個base class（基礎類），你要寫的test classes(測試用例)都得inherit(繼承)自這個base class。不幸的是，這對很多的程式語言來說就造成很大的限制。比如說，Java及C#就只能允許single inheritance(單一繼承)。也就是說，如果你想要refactor(重構)你的Unit Tests程式碼的話，你會遇到一些的限制；除非你引進一些複雜的inheritance hierarchies(類別繼承層級)。

有了.NET之後一切又不同了，.NET引進了一個新的程式開發的概念 ─ Attributes(屬性)，解決了這個煩人的問題。Attributes讓你可以在你的程式碼之上再加入metadata(元資料，描述程式碼的資料)。一般來說Attributes不會影響到主要程式碼的執行，其功能是在你所寫程式碼之上添加了額外的資訊。Attributes主要使用在documenting your code(注釋你的程式碼)，但是Attributes也可以用來提供有關Assembly的額外資訊，其他的程式就算沒有見過這個Assembly，也可以使用這些資訊。這基本上就是NUnit 2.1所作的事。

在NUnit 2.1有一個Test Runner Application(負責執行Unit Tests的程式)，這個Test Runner會掃描你已經compile(編譯)好的程式碼，並且從Attribute?堶悸器D哪些classes是test classes，哪些methods是需要執行的test methods. 然後，Test Runner使用.NET的Reflection技術（在.NET Framework中提供了System.Reflection命名空間，這樣就使得我們可以方便的獲得.NET元件的資訊。當你想獲得正在使用的元件的詳細資訊，或者在運行期間查詢一個元件資訊的時候，這個功能將變的十分有用）來執行這些test methods。因為這個原因，你就不再需要讓你的test classes繼承自所謂的common base class。你唯一需要作的事，就是使用正確的Attribute來描述你的test classes及test methods。

NUnit提供了許多不同的attributes，讓你可以自由的寫你想要的unit tests。這些attributes可以用來定義test fixtures(見下一段解釋)、test methods，以及setup及teardown的methods(預備及善後工作的methods)。除此之外，還有其他的attributes可以來設定預期發生的exceptions，或者要求Test Runner跳過某些test method不執行。

TestFixture Attribute簡介
TestFixture attribute主要是用在class上，其作用是標誌該class含有需要執行的test methods。當你在一個class的定義里加上這個attribute，Test Runner就會檢查該class，看看這個class是否含有test methods。底下這段程式碼示範了如何使用TestFixture Attribute。(本文中所有程式碼都是用C#寫成，但是你應該知道，NUnit也是用於其他的.NET程式語言，包括VB.NET。請參見NUnit的相關檔。

namespace UnitTestingExamples
{
using System;
    using NUnit.Framework;
[TestFixture]
    public class SomeTests
    {
    }
}

使用TextFixture Attribute的class需要符合另一項唯一附加的限制，就是需要有一個public的default constructor(或者是沒有定義任何的constructor，這其實是相同的意思)。

TestFixtureSetUp 和TestFixtureTearDown簡介

這兩個主要用在TestFixture?堶情A其作用是提供一組函數執行任何測試運行之前（TestFixtureSetUP）和最後一個測試執行後（TestFixtureTearDown）。每一個TestFixture只能有一個TestFixtureSetUp方法和TestFixtureTearDown方法。如果一個以上的TestFixtureSetUp和TestFixtureTearDown方法，可以通過編譯但是不會執行。注意一個TestFixture可以擁有一個TestFixtureSetUp和一個SetUp，也可以擁有一個TestFixtureTearDown和一個TearDown方法。
TestFixtureSetUp 和 TestFixtureTearDown 被用在不方便使用SetUp和TearDown方法。

一般情況使用 SetUp 和TearDown attributes。

底下這段程式碼示範了如何使用TestFixtureSetUp/TestFixtureTearDown

namespace UnitTestingExamples
{
using System;
    using NUnit.Framework;
[TestFixture]
public class SomeTests
{
[TestFixtureSetUp]
public void RunBeforeAllTests()
{
Console.WriteLine( “TestFixtureSetUp” );
}
[TestFixtureTearDown]
public void RunAfterAllTests()
{
Console.WriteLine( “TestFixtureTearDown” );
}
[SetUp]
public void RunBeforeEachTest()
{
Console.WriteLine( “SetUp” );
}
[TearDown]
public void RunAfterEachTest()
{
Console.WriteLine( “TearDown” );
}
[Test]
public void Test1()
{
Console.WriteLine( “Test1” );
}
}
}

程式的輸出將是下面的結果：

TestFixtureSetUp
SetUp
Test1
TearDown
SetUp
Test2
TearDown
TestFixtureTearDown

如果Test2單獨執行輸出的結果將是：

TestFixtureSetUp
SetUp
Test2
TearDown
TestFixtureTearDown

Test Attribute簡介

Test attribute主要用來標示在text fixture中的method，表示這個method需要被Test Runner application所執行。有Test attribute的method必須是public的，並且必須return void，也沒有任何傳入的參數。如果沒有符合這些規定，在Test Runner GUI之中是不會列出這個method的，而且在執行Unit Test的時候也不會執行這個method。上面的程式碼示範了使用這個attribute的方法。

SetUp 和 Teardown Attributes簡介

在寫Unit Tests的時候，有時你會需要在執行每一個test method之前(或之後)先作一些預備或善後工作。當然，你可以寫一個private的method，然後在每一個test method的一開頭或最末端呼叫這個特別的method。或者，你可以使用我們要介紹的SetUp及Teardown Attributes來達到相同的目的。如同這兩個Attributes的名字的意思，有Setup Attribute的method會在該TextFixture中的每一個test method被執行之前先被Test Runner所執行，而有Teardown Attribute的method則會在每一個test method被執行之後被Test Runner所執行。一般來說，Setup Attribute及Teardown Attribute被用來預備一些必須的objects(物件)，例如database connection、等等。上面的程式碼示範了使用這個attribute的方法。

ExpectedException Attributes簡介

有的時候，你希望你的程式在某些特殊的條件下會產生一些特定的exception。要用Unit Test來測試程式是否如預期的產生exception，你可以用一個try..catch的程式區段來catch(捕捉)這個exception，然後再設一個boolean的值來證明exception的確發生了。這個方法固然可行，但是太花費功夫。事實上，你應該使用這個ExpectedException attribute來標示某個method應該產生哪一個exception，如同下面的範例所示：

namespace UnitTestingExamples
{
    using System;
    using NUnit.Framework;
[TestFixture]
    public class SomeTests
    {
   [Test]
   [ExpectedException(typeof(InvalidOperationException))]
        public void Test1()
   {
            // Do something that throws an InvalidOperationException
        }
}
}

如果上面的程式被執行的時候，如果一旦exception發生，而且這個exception的type(類型資訊)是InvalidOperationException 的話，這個test就會順利通過驗證。如果你預期你的程式碼會產生多個exception的話，你也可以一次使用多個ExpectedException attribute。但是，一個test method應該只測試一件事情，一次測試多個功能是不好的做法，你應該儘量避免之。另外，這個attributes並不會檢查inheirtance的關係，也就是說，如果你的程式碼產生的exception是繼承自InvalidOperationException 的subclass(子類化)的話，這個test執行的時候將不會通過驗證。簡而言之，當你使用這個attribute的時候，你要明確的指明所預期的exception是哪個type(類型資訊)的。

Ignore Attributes簡介
這個attribute你大概不會經常用的，但是一旦需要的時候，這個attribute是很方便使用的。你可以使用這個attribute來標示某個test method，叫Test Runner在執行的時候，略過這個method不要執行。使用這個Ignore attribute的方法如下：

namespace UnitTestingExamples
{
    using System;
    using NUnit.Framework;

    [TestFixture]
    public class SomeTests
    {
        [Test]
        [Ignore("We're skipping this one for now.")]
        public void TestOne()
        {
            // Do something...
        }
    }
}

如果你想要暫時性的comment out一個test method的話，你應該考慮使用這個attribute。這個attribute讓你保留你的test method，在Test Runner的執行結果?堶情A也會提醒你這個被略過的test method的存在。

NUnit Assert Class簡介
除了以上所提到的這些用來標示測試程式所在的attributes之外，NUnit還有一個重要的class你應該要知道如何使用。這個class就是Assert class。Assert class提供了一系列的static methods，讓你可以用來驗證主要程式的結果與你所預期的是否一樣。Assert class代替了舊的Assertion class，下面是這個類的方法：

Assert.IsTrue( bool );
Assert.IsFalse( bool );
Assert.IsNull( bool );
Assert.IsNotNull( bool );
Assert.AreSame( object, object )
Assert.AreEqual( object, object );
Assert.AreEqual( int, int );
Assert.AreEqual( float, float, float );
Assert.AreEqual( double, double, double );
Assert.Fail();

使用這個類的示例如下：

namespace UnitTestingExamples
{
    using System;
    using NUnit.Framework;

    [TestFixture]
    public class SomeTests
    {
    [Test]
    public void TestEventLengthString()
    {
      // Should return true
      bool bResult1 = Class1.CheckPalindrome("ABCCBA");
      Assert.IsTrue(bResult1);
      // Should return false
      bool bResult2 = Class1.CheckPalindrome("ABCDBA");
      Assert.IsFalse(bResult2);
    }
    [Test]
    public void TestOddLengthString()
    {
      //should return true;
      Assert.IsTrue(Class1.CheckPalindrome("ABCDCBA"));
      // Should return false
      Assert.IsFalse(Class1.CheckPalindrome("ABCDEBA"));
    }
}
}

執行你的Tests

好，現在我們已經討論過寫Unit Tests的基本步驟及方法，現在讓我們來看看如何執行你所寫的Unit Tests。事實上非常簡單。NUnit?堶惘釣潃茪w經寫好的Test Runner applications：一個是視窗GUI程式，一個是console XML(命令列)程式。你可以自由選擇你所喜歡的方式，基本上是沒有什麼差別的。
如果你要使用視窗GUI的Test Runner app，你只需要執行該程式，然後告訴它你要執行的test method所在的assembly位置。這個包含有你所寫test methods的assembly是那一個class library(或是executable，*.dll或*.exe) assembly，其中含有前面談到的Test Fixtures。當你告訴Test Runner你的assembly所在的位置，Test Runner會自動load這個asembly，然後把所有的class及test methods都列在視窗的左欄。當你按下’Run’按鍵時，你就會自動執行所有列出來的test methods。你也可以double click其中的一個test class，或是一個test method之上，這樣會自動只執行該class或是該method。
底下是視窗GUI Test Runner執行時的樣子：

在一些的情況下，特別是你想要在你自己寫的build script中加入Unit Testing的情況下，你大概不會使用GUI Test Runner。在這個自動執行build script的情況下，你一般會把你build的結果貼在網頁，或寫入log file?堶惘s作紀錄，以供程式開發人員、經理或是客戶可以藉由檢查這個紀錄知道詳細情況。在這個情況，你可以用NUnit 2.1的console Test Runner application。這個Test Runner可以傳入assembly的位置當參數，其測試執行結果是一個XML字串。你可以用XSLT或是CSS把這個XML結果轉換成HTML，或是其他你想要的格式。如果你需要用到這個功能的話，請查看NUnit檔中有關console Test Runner application的資料。


NUnitV.2 tutorial
Nunit V.2 for People Who Can't Cook

Description:
In this article you will discover how to use how to use NUnit V.2 efficiently with your .Net projects.For your information this article was created with NUnitV.2 RC2 (which you can get here) and VS.Net 7.0.

Introduction:
Before I get going I have to say that I don’t automate the complete process anymore (yes I do have to use the mouse now for testing), since I feel the benefits of automasation are not offsetting the cost of having to modify your programming environment for every project. So the described setup will be relatively straight forward.

A lot of things have changed from Version 1 and I must say that it is now relatively easy to get an efficient workflow with NUnit2. The main advantages of NUnit 2 are:
-Now your TestFixture does not need to inherit from TestCase anymore. That means that we don’t have to write any ugly constructors anymore.
-NUnit2 can automatically find all TestCases in a compilation unit.

0.Create your project
Create a new C# project in VS.Net and now go in the “solution explorer”.

1.Add the NUnit reference

Right click on the reference line and click on add a reference.

Now click on Browse.

Navigate to your NUnitV2 directory and go into the bin subdirectory. For me this directory is in “C:\Program Files\NUnit V2.0\bin”.Select nunit.framework.dll and click OK.

2. Add your TestCase
Now we can finally proceed to write some code. In order to get the basic skeleton setup for NUnit you need to add two things

First you need to add the reference in your code to the NUnit namespace:

using NUnit.Framework;

Additionally you need to add your testing class to your source file:

[TestFixture]//telling NUnit that this class contains test functions
public class MyTestClass
{
[Test]//telling NUnit that this function should be run during the tests
public void TestFunction()
{
//add here your Assertions
}

}
Compile your project by clicking F7.

3.Starting NUnit-GUI
OK now we will start the NUnit-GUI application which you can find under your windows programs menu or in the “C:\Program Files\NUnit\bin” directory.

Now go under File->Open and navigate to your projects “bin” directory. In other words to need to supply NUnit with the executable of your project in order to run the containing tests.

Select the exe or dll file of your compiled project (it will have the same name as your project) and click Open.

You will immediately notice that NUnit2 is looking through the complete compilation unit and finds any TestFixtures. In our case the TestFixture is called MyTestClass and the only test is TestFunction.

4.Testing with NUnit-GUI
Click on the “Run” button.

You will see a green bar which tells you that all tests succeeded. To change this let us rewrite our function to this:

[Test]//telling NUnit that this function
should be run during the tests
public
void TestFunction()
{
//add here your Assertions
Assertion.Assert(1==0);
}

Compile your project with this new code and switch to NUnit-GUI. You will notice that NUnit has noticed that the executable has changed and it has reloaded it for you. Now simply click run again.

In order to fix this broken test you would simply change the assertion and go back to NUnit-GUI and hit the run button.

OK this is already it. There is not much more to explain since the creators of NUnitV.2.0 have done a pretty good job in designing this new version.

For your information, the workflow to use NUnit2 is something like this
0.Startup NUnit-GUI
1.Write a test
2.Compile your project
3.Switch to NUnit-GUI (it will recognize automatically that your executable has changed and reload it)
4.Hit the Run button
5.Write necessary code to get test to run and go back to Step 1

Granted this is not as smooth as with NUnit1, but it is connected with much fewer hassles and feels a bit cleaner than the previous process.

If you have any questions or comments email me under kalina@octuraNOSPAM.com. (without the NOSPAM).
http://www.tangent-studios.com/programming/csharp/


Web Development with SharpDevelop, Web Matrix, and DBGCLR

(SharpDevelop與Web Matrix和DBGCLR一起寫ASP.NET)

Visual Studio.NET 2003 makes development a whole lot easier than it ever was before.  But what if you have to develop a web application and you do not have the power of VS.NET 2003 available to you?

I would hate to be without Intellisense (I’m spoiled), debug support, and many of the other features that VS.NET 2003 provides.  There is a way to accomplish this developmental challenge with the following three tools:

SharpDevelop , the free open source .NET IDE, has just been released as Fidalgo RC1 (6/16/2004).  This development environment does not support debugging, or ASP.NET development.  However, SharpDevelop is a great product and it is worth getting excited about.

SharpDevelop’s IDE is very similar to VS.NET 2003; it even has a version of Intellisense.  I felt right at home here.

Web Matrix , the free ASP.NET IDE was released by Microsoft to support ASP.NET development.  This IDE does not support debugging, Windows development, Intellisense, and many other niceties of Visual Studio.NET 2003.

DebugCLR (DbgCLR.exe) is available in the .NET Framework SDK or with Visual Studio.  This tool allows the developer to step into managed code without the need of Visual Studio.NET.

Code snippets in this example are in C#, but can be modified for VB.NET.

Configuring the Solution in SharpDevelop

SharpDevelop has a similar notion of a solution called Combines.  These combines can contain multiple projects.

I’ve created a project folder for SharpDevelop here: C:\Projects_SharpDevelop and set my default location to this directory from Tools > Options:

Adding a combine:

File > New Combine:

Select a C#, or VBNET Class Library project and call it WebDemo2:

SharpDevelop will create a new class file called MyClass.cs by default.  Delete this file, we will not use it.

This next step is very important.  Set the project output path to C:\Projects_SharpDevelop\WebDemo2\bin.  The bin folder may not exist, so you will need to create it.  To accomplish this, right click on the project, select Project Options > Configurations > Output and set the output path.

Next, add a new file to the project by right clicking on the WebDemo2 project, Add >New File:

Choose a new C# or VB.NET file (depending on what type of Combine you’ve created) and call it MyCodeBehindClass.aspx.cs.

Drop the .aspx from the class name.  This class should inherit from Page.  It should look like this:

Delete the constructor.  It is not needed.

Add the following using statements:

and the following code:

Press F8 to build the Combine.

Configuring the Solution in Web Matrix

Open Web Matrix.

To create a new project which is essentially a shortcut to the directory, click File > New Project and choose Folder ShortCut:

Enter the directory path that points to the SharpDevelop Combine: C:\Projects_SharpDevelop\WebDemo2.

You will notice a new shortcut is created in the Workspace sidebar on the right.  Expand the shortcut to see the files that exist from SharpDevelop.

Create a new aspx file.  Right click the shortcut and click Add New File, select ASP.NET Page, and name it MyWebForm.aspx:

Next, click the “All” tab at the bottom of the new file, and replace the existing page directive with this one:

This directive can be all in one line.  I wrapped it for this walk through.

Click the “Design” tab at the bottom and drag on a TextBox by expanding the web control's group and selecting the TextBox control from the toolbar to your left.

Click on the play icon on the toolbar or press F5.  Make sure the web path is the same as the Combine location:

I am using the built-in web server provided by Web Matrix (this will display an icon in the taskbar).  You can also use IIS.  This is the main reason we changed the output path of the project.  The web application expects the dlls to be in a bin directory, not bin\debug or bin\release.

The page will run and display the TextBox with the string set in the SharpDevelop class file:

LEAVE THE BROWSER OPEN FOR DEBUGGING

Debugging the Combine

To debug the application, launch DbgCLR.exe.  The quickest way to find this application is to do a search.  If you have VS.NET 2003 installed, the default location is: C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\GuiDebug\DbgCLR.exe.

Open the MyCodeBehindClass.aspx.cs from File > Open > File or CTLR+O.

Set a break point on the following line:

Next, choose the process to step into.  If you are running this example in IIS, choose the aspnet_wp.exe process.  If you are using the Web Matrix web server, choose WebServer.exe.

Click Tools > Debug Processes or CTLR+ALT+P and choose the appropriate process to step into and click Select.  Then close.

Now, refresh the web browser.  You will be taken to the break point:

Why do this?  I always have had this fascination with doing things the hard way.  If you’re anything like me, you might do this just because you can.

Take some time to get familiar with SharpDevelop and Web Matrix.  They both have their own feel.

Additional resources:

SharpDevelop:
 http://www.sharpdevelop.com/OpenSource/SD/WhatsNew.aspx
http://www.sharpdevelop.com/OpenSource/SD/Forum/

Web Matrix:
 http://www.asp.net/webmatrix/faq.aspx
http://www.asp.net/Forums/ShowForumGroup.aspx?tabindex=1&ForumGroupID=4


SharpDevelop .NET 官方下載網站與中文化
#develop (short for SharpDevelop) .NET免費開發工具-多國語言版
官方網站：
 http://www.icsharpcode.net/OpenSource/SD/

#develop (short for SharpDevelop) is a free IDE for C# and VB.NET
projects on Microsoft's .NET platform.

SharpDevelop RC2/3 開發工具-繁體中文修正檔
http://delphi.ktop.com.tw/topic.asp?TOPIC_ID=54279
SharpDevelop RC3 開發工具-繁體中文修正檔(第1次修正)
http://delphi.ktop.com.tw/topic.asp?TOPIC_ID=55374
除覆蓋BIG5修正檔以外，在IDE環境選項，修改
程式碼編輯器設定：檔案編碼-->選擇編碼：繁體中文(Big5)


網路學習資源
  • Microsoft Windows Form 快速入門教學課程
  • WinFX 247 : .NET v1.1.4322 Library
  • Windows Forms .NET官方網站
  • Microsoft Newsgroups
  • Longhorn SDK
  • World of .NET
  • Windows Forms FAQ
  • C# Tutorial
  • C# Station Tutorial
  • .NET 247
  • DOBON.NET [日本網站]
  • WoodenSoldier Software [日本網站]
  • TWP .NET User Group
  • Move to .NET User Group
  • Microsoft C#程式語言和通用語言架構CLI通過ISO/IEC標準認證
  • ECMA-334 C# Language Specification
  • ECMA and ISO/IEC C# and Common Language Infrastructure Standards
  • MSDN C# Language Specification
  • .NET Framework 首頁
  • Microsoft Visual C# .NET 首頁
  • Microsoft ASP.NET 快速入門教學課程
  • Web Services介紹
  • 別再掉進DLL地獄的陷阱裡(DLL Hell)~.NET解決之道
  • 利用ASP.NET Web Matrix Project開發Web應用程式
  • C#(C Sharp)的語法到底比較像C++還是Java
  • 藍色小舖討論區 C#(ASP.NET) 討論區
  • 微軟技術社群
  • 是否能讓JAVA 和 .NET框架共存
  • 新一代分散式應用軟體架構－.NET
  • LabMice.net


何謂 Combine
Combine程式中以「合併」稱呼，但亦可稱謂「方案總管」，
就是各個小專案的統合管理，它是SharpDevelop的「MetaFile」。


SharpDevelop-自制MDI範本(MDIFormsProject.xpt)
儲存位置 C:\Program Files\SharpDevelop\data\templates\project\CSharp
範本內容如下：

<?xml version="1.0"?>
<Template originator   = "Mike Krueger"
          created      = "06/10/2001"
          lastModified = "02/01/2003">

    <!-- Template Header -->
    <TemplateConfiguration>
        <Name>${res:Templates.Project.WindowsApplication.Name}(MDI)</Name>
        <Category>C#</Category>
        <Icon>C#.Project.Form</Icon>
        <LanguageName>C#</LanguageName>
        <Description>${res:Templates.Project.WindowsApplication.Description}(MDI)</Description>
    </TemplateConfiguration>

    <!-- Actions -->
    <Actions>
        <Open filename = "MDIForm.cs"/>
    </Actions>

    <Combine name = "${ProjectName}" directory = ".">
        <Options>
            <StartupProject>${ProjectName}</StartupProject>
        </Options>

        <Project name = "${ProjectName}" directory = ".">

            <Options Target = "WinExe" PauseConsoleOutput = "False" />

            <Files>
                <File name="MDIForm.cs"><![CDATA[${StandardHeader.C#}
using System;
using System.Windows.Forms;

namespace DefaultNamespace
{
    /// <summary>
    /// Description of MDIForm.
    /// </summary>
    public class MDIForm : System.Windows.Forms.Form
    {
        public MDIForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
            //===new ChildForm===
            //Form1 ChildForm=new Form1();
            //ChildForm.MdiParent=this;
            //ChildForm.Show();
        }

        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new MDIForm());
        }

        #region Windows Forms Designer generated code
        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent()
        {
            //
            // MDIForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Text = "MDIForm";
            this.Name = "MDIForm";
            this.IsMdiContainer=true;
        }
        #endregion
    }
}]]></File>
        <File name="AssemblyInfo.cs">
            <![CDATA[using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following
// attributes.
//
// change them to the information which is associated with the assembly
// you compile.

[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all values by your own or you can build default build and revision
// numbers with the '*' character (the default):

[assembly: AssemblyVersion("1.0.*")]

// The following attributes specify the key for the sign of your assembly. See the
// .NET Framework documentation for more information about signing.
// This is not required, if you don't want signing let these attributes like they're.
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
]]></File>
            </Files>
        </Project>
    </Combine>
</Template>

使用說明：
MDIForm建立後，在建立Form1，
MDIForm設定如下，來開啟Form1子視窗：
//===new ChildForm===
Form1 ChildForm=new Form1();
ChildForm.MdiParent=this;
ChildForm.Show();

================================
■Form1子視窗，使用時看成物件，
用完記得釋放！
SharpDevelop-範本(***.xpt)
範本編修時不能用中文..使用時，會出現錯誤！


[SharpDevelop] VC7(VS2003)的sln專案與SharpDevelop 的cmbx專案之互相轉換

一、將VC7(VS2003)的sln專案轉成SharpDevelop 的cmbx專案：
1.開啟SharpDevelop
2.選擇 檔案選單-->匯入專案(Import Project)
3.專案匯入(project to import)：選擇sln檔
4.輸出路經(Output location) ：選擇cmbx專案儲存的資料夾
5.按「Start按鈕」開始轉換
6.完成

二、將SharpDevelop 的cmbx專案轉成VC7(VS2003)的sln專案：
1.開啟SharpDevelop
2.選擇 檔案選單-->匯出專案(Export Project)
3.輸出路徑(Output location)：選擇sln專案儲存的資料夾
4.輸出格式(Output format) ：預設轉換的類型
5.輸出選項設定(Export)：選擇所需的轉換方式(單一專案或全部專案)
6..按「Start按鈕」開始轉換
4.完成
程式碼以外，參考到的DLL，在編譯前，記得加入到專案的「參考」中。


在部署專案中加入.NET framework
如果你想要在你的Visual Studio .NET 安裝和部署專案中包含 .NET Framework，請參照下面的範例：

Microsoft .NET Framework Setup.exe Bootstrapper Sample

 http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/MSDN-FILES/027/001/830/msdncompositedoc.xml

你可以在 Microsoft 網站上下載 .NET Framework，你也可以在Visual Studio .NET 安裝媒體中找到，關於 .NET Framework redistributable package 的進一步資訊，請參考下面的文件：
 308488 INFO: Download and Install the .NET Framework


把.NET程式部署到沒有安裝.NET Framwork的機器上
摘要
本文討論了如何使用Windows Installer技術發佈.NET程式，以及如何使用native程式碼判斷目標機器上是否安裝有.NET Framework; 如果沒有，將自動安裝.NET Framework然後安裝作者自己的.NET程式。
目錄
  • 本文內容
  • 製作自己的安裝程式
  • 發佈.NET Framework
  • 製作自己的native安裝程式
  • 使用方法
  • 總結
  • 作者
本文內容
1． 使用VS.NET來製作安裝程式。
2． 如何把.NET Framework 部署到目標機器。
3． 如何使用Native程式碼把.NET Framework和自己的安裝程式製作為一個統一的安裝程式。
該程式做到如果目標機器上沒有.NET Framework，將自動安裝.NET Framework然後再自動安裝作者自己的程式。
製作自己的安裝程式
在VS.NET中，我們可以通過建立"Setup and Deployment Projects"專案，非常靈活方便的把自己的.NET程式製作為Windows Installer檔案。
比如，我們可以很方便的定制下面這些選項：
1． 是否在桌面上放置快捷方式。
2． 註冊自己的檔案類型，可以通過雙擊該檔案來使用自己的程式打開。
3． 註冊表的處理
在下面的MSDN站點，我們可以獲得在VS.NET中通過Setup and Deployment Projects來製作自己的安裝程式的示例：
http://msdn.microsoft.com/library/en-us/vsintro7/html/vbconDeploymentScenarios.asp
發佈.NET Framework
.NET Framework 1.0提供一個用來重新部署.NET的exe檔案：
Dotnetfx.exe. 它包含了Common Language Runtime和其它.NET程式執行時必不可少的內容。
我們可以從下面的站點下載該exe檔案：
http://msdn.microsoft.com/downloads/sample.asp?url=/MSDN-FILES/027/001/829/msdncompositedoc.xml
同時，我們也可以在VS.NET安裝CD或者DVD中找到該檔案。
我們可以通過多種方式來通過執行Dotnetfx.exe把.NET Framework部署到目標機器上：
1． 通過Microsoft Systems Management Server部署。
2． 通過Active Directory部署。
3． 使用第三方工具。
具體的信息，我們可以參閱下面的文章：
http://msdn.microsoft.com/library/en-us/dnnetdep/html/redistdeploy.asp
製作自己的native安裝程式
如果我們要把自己的.NET程式發佈到目標機器上，同時我們不確定該目標機器是否已經安裝了.NET Framework, 那我們就需要自己設計一段unmanaged程式碼，來判斷目標機器是否安裝了.NET Framework, 如果沒有，則執行Dotnetfx.exe安裝.NET Framework, 然後利用Windows Installer安裝自己的程式。
在MSDN的下面網頁上，我們可以獲得一個使用unmanaged C++實現的安裝程式和它的源程式碼：
http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/001/830/msdncompositedoc.xml
1． 在CSettings class中，通過讀取"settings.ini",獲得您自己的MSI安裝檔案和dotnetfx.exe的路徑，以及其他您自己的設置。
（比如.NET Framework的語言版本）
GetCaptionText(void)
GetDialogText(void)
GetErrorCaptionText(void)
GetIniName(void)
GetProductName(void)
Parse()函數用來解析settings.ini檔案。
2． 在Main.cpp檔案中，全局函數FxInstallRequired()判斷是否要在目標機器上安裝.NET Framework.
FxInstallRequired()會檢測下面的註冊表鍵值和dotnetfx.exe的版本和語言設置。
HKLM\SOFTWARE\Microsoft\.NETFramework\policy\v1.0
3．如果需要安裝.NET Framework, 在全局函數ExecCmd()中調用下面的命令silent安裝dotnetfx.exe：
dotnetfx.exe /q:a /c:"install /l /q"
4。 在ExecCmd()全局函數中調用下面的命令安裝您自己的MSI檔案：
msiexec /i <your MSI file> REBOOT=ReallySuppress
使用方法
如果我們使用上面的native程式碼作為自己的安裝程式，那麼我們可以通過下面的步驟把自己的.NET程式和它結合在一起：
1．把您自己的.NET程式製作成為Windows Installer (.MSI)檔案。
2．打開"settings.ini"檔案，在"Msi" key中設置您自己的.NET程式的MSI檔案路徑和檔案名；
在"FxInstallerPath" Key中，設置dotnetfx.exe的路徑。具體的參數信息，您可以從下面文章中得到：
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetdep/html/redistdeploy.asp
3. 把"setup.exe", "settings.ini", "dotnetfx.exe"和您自己的MSI安裝檔案，發送到目標機器上，
然後執行"setup.exe", 安裝程式會自動檢測是否有.NET Framwork, 如果沒有，將首先執行dotnetfx.exe。
通過上述步驟，您可以將自己的.NET程式成功的部署到沒有安裝.NET Framwork環境的機器上。
總結
通過上述步驟，您可以將自己的.NET程式成功的部署到沒有安裝.NET Framwork環境的機器上.


#D 工具選單-->自動產生程式碼(用於新增事件)
-->選擇後按[Enter]輸入鍵-->產生完成


VC# 程式進入點寫法
[STAThread]
static void Main()
 {
    Application.Run(new Form1());
 }

#D 程式進入點寫法
 [STAThread]
 public static void Main(string[] args)
 {
    Application.Run(new Form1());
  }
1.但一般編譯時，都可以正常執行！
2.不能正常執行，請修改為＃D的程式進入點宣告方式：
   public static void Main(string[] args)


關於VC#的STL(Standard Template Library)
VC#內建STL，而SharpDevelop並無STL。
若程式看到
         using STL.Generic;
以STL為名稱空間，表示該程式是使用VC#，在SharpDevelop則無法編譯。


.NET Framework 簡介

. NET 是微軟繼其 DNA(Distributed interNet Applications) 架構之後，所提出下一代的分散式軟體應用架構，它的發展方向是要建構一個使用網際網路開放標準 ( 如： HTTP 、 XML 、 SOAP… 等 ) 的應用程式開發與執行的環境，使任何人從任何地方，在任何時間使用任何裝置都能存取網際網路上得資源與服務。

在微軟的規劃下，.NET 包含了五大發展的主軸

  • 個人電腦與智慧型裝置： Longhorn、Windows XP、Pocket PC、Windows CE 、 Stinger 手機 OS
  • 使用者體驗： Passport
  • Web Service： 藉由 XML 及 SOAP 讓應用軟體能以 Internet 為平台，運用 XML 的格式來傳遞。
  • 伺服器： Windows.NET Server 、Longhorn Server
  • 開發工具： Visual Studio.NET、C#.NET、VisualBasic.NET

整個.NET 的Framework包含了下列元素

  • 遵守CLS規範的語言與開發工具，例如 VB, C#, J#, C++
  • 共通語言規範(Common Language Specification ; CLS)
  • 共通語言執行環境(Common Language Runtime ; CLR)
  • 基礎類別程式庫(Base Class Library ; BCL)

.NET應用程式有2大類

  • Win Form：指的是一般在使用者電腦中執行的應用程式
  • Web Form：指的便是ASP.NET

.NET Framework 1.1內建在Windows Server 2003的核心，所以在效能方面比.NET Framework 1.0高出一半以上。.

安裝

開發 | 執行 | 安裝套件
V |  | Microsoft Data Access Components 2.7版
V | V | Microsoft .NET Framework 可轉散發套件 (Redistributable)1.1 版
V |  | Microsoft .NET Framework 軟體開發套件 (Software Development Kit，SDK) 1.1 版
V |  | Microsoft .NET Framework 繁體中文語言套件 ( langpack ) 1.1 版

若需要執行J#, 則要另外安裝下列套件

Microsoft Visual J# .NET可轉散發套件 1.1 版
Microsoft Visual J# .NET可轉散發繁體中文語言套件 1.1 版


下載最新版的.NET Framework
下載點：
NET Framework首頁
http://msdn.microsoft.com/netframework/default.asp
How to Get the Microsoft .NET Framework
  http://msdn.microsoft.com/netframework/downloads/howtoget.asp
NET Framework最新版網頁
http://msdn.microsoft.com/netframework/downloads/sp/download.asp
備註：
1.本書使用 .NET Framework 1.1 sp1。
2.相關.NET Framework 應用，請參考幫助檔。
3.瀏覽.NET Framework幫助檔的Microsoft HELP 2.0格式工具：
  下載：H2Viewer V1.3.4.0


Java Framework 與NET Framework比較
  • Java Framework和.NET Framework之間的比較十分常見。雖然可以瞭解 Java 平台提供了.NET 將面對的主要競爭基礎，.NET 的範圍卻比較大。.NET不僅提供可讓應用程式開發與執行的骨架，它還涵蓋了開發工具與供應用程式使用、範圍廣泛的伺服端產品。
  • .NET Framework 大致上等同於 Java 平台，由一組類別庫與一個和 Java 虛擬機器相似的執行環境組成。Java 將這兩個項目以 Java 程式語言規格結合在一起，而 .NET Framework 則是設計成支援多種語言，包括 C# 以及修改過的 Visual Basic 和 Visual C++，因此並不包含單一的語言規格。
  • 就程式語言的角度來比較 ( C# VS Java )
    • C#：A simple, modern, object-oriented, type-safe, versionable, compatible, and flexible language(Microsoft C# product manager : Tony Goodhew)
    • Java：A simple, object-oriented, distributed, interpreted, robust, secure, architecture, neutral, portable, high performance, multithreaded, and dynamic language (Sun Microsystems的Jame Gosling and Henry McGilton)
J2EE Feature | .NET Framework | 備註
Java | Multi-language | Cobol, Build into SQL Server
JVM | CLR |
JDK | .NET Framework SDK |
JavaBeans | .NET class |
EJB | .NET class with COM+ |
JSP/Servlet | ASP.NET | Web control vs. Taglib and Faces
JMS | System.Messaging / MSMQ |
EJB Message Beans | COM+ QC |
JNLP (WebStart) | No-touch Deployment |
RMI-over-IIOP | .NET Remoting |
JNDI | ADSI |
JAXP … | System.XML and web services | ADO.NET XMLReader
JSR-175 – coming in JDK 1.5 | Code Attributes |
JavaMail | System.Web.Mail |


共通語言執行環境(Common Language Runtime:CLR) 簡介
傳統的程式編譯方式是將原始程式碼直接編譯成電腦能直接執行的原生碼 (Native Code) ，以執行檔的形式儲存，但是這樣會產生某台機器上編譯過的可執行檔在另一台機器不一定能正常執行。

而在 .NET Framework 環境下，一個 .NET 應用程式的原始碼會先透過 CLR 編譯器編譯，如果沒有語法上的錯誤，就會被加上 Metadata 引擎所產生的 Metadata ，與原始碼產生的中介語言 (Intermediate Language ， IL) ，一起放在目的格式檔案中，通常是指可執行檔 (EXE) 或是動態連接檔 (DLL) ，如果在編譯過程需要用到其他程式庫，中間會再經過一個連結程式 (Linker) 來完成組合程式碼的動作。而在實際執行時，如果應用程式沒有預先被編譯成可被電腦直接執行的原生碼 (Native Code) ，則系統會啟動一個即時編譯器 (Just In Time Compiler ， JIT Compiler) ，將執行檔中的中介語言轉換成原生碼並交由作業系統執行。如此，不論是使用那一種支援 .NET 程式語言撰寫的程式，所產生的中介語言皆相同。將此中介程式碼放置於已安裝 Microsoft .NET Framework 的電腦上均可正常執行，不論其所採用的 CPU 是 Intel-based 、 alpha… 或甚至是不同的作業系統。

  • 相對於Java的Virtual Machine, .NET稱為CLR
  • 相對於 Java 的 Bytecode , .NET 稱之為以 IL (Intermediate Language) )語言的Managed Code
  • CLR將Managed Code以JIT(Just In Time) 及時編譯後執行
Metadata

Metadata在此指的是描述程式執行時所需要的資訊，是所有相關資料的資訊區。

例如：程式內所包含或引用的類別、記憶體資源的配置、 IL 編譯成原生碼所需的資訊及安全管理等。


CLR Profiler (v2.0) 下載

The CLR Profiler allows developers to see the allocation profile of their manage applications.

http://www.microsoft.com/downloads/details.aspx?FamilyId=86CE6052-D7F4-4AEB-9B7A-94635BEEBDDA&displaylang=en

Overview

The CLR Profiler includes a number of very useful views of the allocation profile, including a histogram of allocated types, allocation and call graphs, a time line showing GCs of various generations and the resulting state of the managed heap after those collections, and a call tree showing per-method allocations and assembly loads.

System Requirements

  • Supported Operating Systems: Windows 2000, Windows 98, Windows 98 Second Edition, Windows ME, Windows NT, Windows Server 2003, Windows XP

The CLR Profiler requires the .NET Framework


Managed 執行程序
Managed 執行程序包括下列步驟：
  1. 選擇編譯器。

  2. 若要取得 Common Language Runtime 提供的好處，您必須使用一個或多個以 Runtime 為目標的語言編譯器。

  3. 編譯您的程式碼為 Microsoft Intermediate Language (MSIL)。

    編譯會將您的原始程式碼轉譯成 MSIL，並產生必要的中繼資料。

  4. 編譯 MSIL 為機器碼。

    在執行期間，Just-in-Time (JIT) 編譯器會將 MSIL 轉譯成機器碼。在這個編譯 (Compilation) 期間，程式碼必須傳遞會檢查 MSIL 和中繼資料的驗證程序，以查明程式碼是否可以被確定為型別安全的。

  5. 執行程式碼。

    Common Language Runtime 提供基礎結構，讓執行以及可在執行期間使用的各種服務能夠運作。


自動記憶體管理
自動記憶體管理是 Common Language Runtime 在 Managed 執行期間所提供的一項服務。
Common Language Runtime 的記憶體回收行程會管理應用程式記憶體的配置和釋放。
這表示開發人員在開發 Managed 應用程式時，不需要撰寫程式碼來執行記憶體管理工作。
自動記憶體管理可排除一些常見的問題，例如，忘記釋放物件而造成記憶體遺漏 (Memory Leak)，或嘗試存取已經釋放物件的記憶體。


基礎類別程式庫(Base Class Library:BCL) 簡介
.NET Framework 包含了一組豐富的類別庫讓程式設計人員使用 ，包含
  • 呈現基本資料型態和例外（exception）
  • 支援 I/O 與網路
  • 支援各種型態的反射（reflection）
  • 支援平台與應用程式安全防護
  • 與底層的作業系統整合
  • 為建構 GUI 程式提供服務
  • 提供資料庫存取能力
  • 支援 XML Web 服務的開發
.N et Fr amework 所有的功能幾乎都會透過一組受控管的型別—稱為基礎類別程
式庫（Base Cl ass Libr ary ，簡稱BCL）—公開出來。
因為這些型別都與CLS相容，所以它們都可由任何的.N ET 程式語言來加以取用。
BCL 型別會成群地放置在命名空間中，並透過.NET 平台中的一組配件（DLL s）加以匯出。
當您在C#應用程式中使用這些型別時，您需在編譯時參照適當的配件。
為了能夠在.Net 平台中更有效率地使用C#，了解預定之類別程式庫的一般能力，
是件很重要的事。然而，這些程式庫實在太大，無法一一在書中做完整的討論，
因為它包含了將近4,500 個型別，並組成120 個命名空間，以及匯出成40 個不同的
配件。

相對地，在本章中，我們將提供整個BCL 的概述（劃分成不同的領域）並提供相
關型別以及命名空間的參考，以此為基礎您可以自行在.NET Fr amewor k 之SDK
中探索完整的細節。
可藉以探索BCL 的有用工具包括.NET Fr amework 的SD K 文件、WinCV.exe 類別
瀏覽器，以及IL Asm.exe 反組譯器（di sassembl er ）。


核心型別
「核心型別」（cor e type）被包含在S y s t e m 命名空間中。
這個命名空間是BCL 的重心，其中包含：類別、介面，以及所有其它型別所依賴的屬性。
BCL 的根源是O b j e c t 型別，所有其它的.NET 型別都是由它衍生而來的。
其它的基礎型別有
V a l u e T y p e （str uct 的基礎型別）、
E n u m （enum 的基礎型別）、
C o n v e r t （用於基礎型別間的轉換）、
E x c e p t i o n （所有例外事件的基礎型別）
，以及預先定義之數值型別的boxed 版本。
整個BC L 所使用介面，像是I C l o n e a b l e 、I C o m p a r a b l e 、I f o r m a t t a b l e 及I c o n v e r t i b l e ，
都會在此處定義。延伸的型別，譬如D a t e T i m e 、T i m e S p a n 及D B N u l l ，也都可使用。
其它的類別包括：單一或多重委派的支援、基本數學運算、屬性，以及例外處置。
與字串有關的更進一步資訊，參見S t r i n g 命名空間。


文字
BCL 提供豐富的文字處理功能。重要的型別包括：S t r i n g 類別（可處理固定不
變的字串）、S t r i n g B u i l d e r 類別（可提供處置字串的運算，並支援可辨認語系
（locale-awar e）的比對運算及多重的字串編碼格式（ASCI I 、Uni code 、UT F-7 與
UTF-8）），以及一組支援正規表示式的類別。
System.Text
System.Text.RegularExpressions

位於其它命名空間的重要型別還包括S y s t e m . S t r i n g


集合
B CL 提供了一組通用的資料結構，譬如A r r a y L i s t 、D i c t i o n a r y 、
H a s h t a b l e 、Q u e u e 、S t a c k 、B i t A r r a y 以及其它。標準化的設計樣式
（desi gn pat t er n）使用了共通的基礎型別（common base t ype）與公開的介面
（publ ic int er f ace），這讓BCL 可以一致化地處置預先定義的集合型別，以及使用
者自訂的集合型別。
至於更詳細的資訊，請參考以下的命名空間：
System.Collections
System.Collections.Bases
位於其它命名空間的重要型別還包括S y s t e m . A r r a y 。


串流與I / O
BCL 對標準輸入、輸出及錯誤之串流的存取提供了良好的支援。它也提供了相關
類別，可用以進行二進位格式檔及文字格式檔的I /O（輸出/入）、註冊檔案系統之
例外事件的通知，以及存取一個使用者自訂的安全儲存區，也就是所謂的I solated St orage
至於更詳細的資訊，請參考以下的命名空間：
System.IO
System.IO.IsolatedStorage
System.Console


網路
BCL 支援了一組層級式的類別，可使用不同的抽象層級藉由網路進行溝通，這些
抽象層級包括：對原始socket 的存取；對TCP 、UDP 及HTTP 等協定支援；一個
以URI 及串流為基礎的、高階的r equest /r espons e 機制；以及一個可插入
（pluggable）的協定處理器。
至於更詳細的資訊，請參考以下的命名空間：
System.Net
System.Net.Sockets
位於其它命名空間的重要型別還包括S y s t e m . I O . S t r e a m 。


執行緒
BCL 提供了豐富的支援，可建立多重執行緒的應用程式，包括：執行緒及執行緒
集區（pool ）的管理；執行緒同步機制，譬如：監控、mut exe 【編註：mut ext（互
斥；對立）是指執行緒之間為避免r ace condi ti on（競爭狀況）所使用的機制。】、
事件、r eader /wr it er 鎖定，等等；以及存取底層作業平台的功能，譬如：I /O 完成
埠及系統時鐘。
至於更詳細的資訊，請參考以下的命名空間：
System.Threading
System.Timers
System.Timers.Design
位於其它命名空間的重要型別還包括S y s t e m . T h r e a d - S t a t i c A t t r i b u t e 。


安全
BCL 提供了一組類別，可以處理.NET 執行期之「程式碼存取安全模型」（Code
Acces s Secur i ty model ）的所有元素，包括：安全政策、安全原則、使用權限設
定，以及證據。這些類別也支援加密演算法，譬如：DES 、3DES 、RC2 、RSA 、
DSig 、MD5 、SHA1 ，以及可對串流進行轉換的Base64 編碼。
至於更詳細的資訊，請參考以下的命名空間：
System.Security
System.Security.Cryptography
System.Security.Cryptography.X509Certificates
System.Security.Cryptography.Xml
System.Security.Permissions
System.Security.Policy
System.Security.Principal


反射（R e f l e c t i o n ）
.N ET 執行期非常仰賴中介資料（m et adata）的存在，以及其動態檢查與處理「中
介資料」的能力。BCL 揭露了一組抽象的類別，它們會鏡射（mi rr or ）出應用程式
裡一些重要的元素（配件、模組、型別與成員）並且為BCL 型別與新型別提供快
速建立實例的支援。
至於更詳細的資訊，請參考以下的命名空間：
System.Reflection
System.Reflection.Emit
位於其它命名空間的重要型別還包括：
System.Type
System. Activator
System.AppDomain.


序列化（S e r i a l i z a t i o n ）
BCL 所提供的支援還包括對任意「物件圖形」（obj ect gr aph）與「串流」（s t ream）
進行序列化的轉換。這項序列化功能可透過檔案或網路儲存並傳送複雜的資料結
構。預設的「序列化函式」（s er iali zer ）提供了bi nar y 及XML 為主的格式編排，
但可透過用者自訂的「編排函式」（f or mat ter ）來加以延伸。
至於更詳細的資訊，請參考以下的命名空間：
System.Runtime.Serialization
System.Runtime.Serialization.Formatters
System.Runtime.Serialization.Formatters.Soap
System.Runtime.Serialization.Formatters.Binary
位於其它命名空間的重要型別還包括：
System.NonSerializedAttribute
System.SerializableAttribute


遠端服務（R e m o t i n g ）
遠端服務是分散式應用程式的的基石，而且BCL 還提供了優異的支援，可執行或
接收遠端的方法呼叫。遠端呼叫可以是同步的或非同步的；支援r equest /r espons e
架構或單向模式；可透過多種傳輸協定（TCP 、HTT P 及SMTP）；並可被進行多
種格式的序列化（SOAP 及bi nar y）。遠端服務之基礎建設支援了多重的啟動模
型、租賃為主（l eas e-based）的物件生命期、分散式物件的身份、透過參照型別或
數值型別的「物件封送」（obj ect marshall i ng），以及訊息的截取。這些型別可透過
使用者自訂的「通道」（channel ）、「序列化函式」（s er i al i zer ）、「代理程式」
（proxy），以及「呼叫環境」（call context ）做進一步的延伸。
至於更詳細的資訊，請參考以下的命名空間：
System.Runtime.Remoting
System.Runtime.Remoting.Channels.Core
System.Runtime.Remoting.Channels.HTTP
System.Runtime.Remoting.Channels.MetadataServices
System.Runtime.Remoting.Channels.SMTP
System.Runtime.Remoting.Channels.TCP
System.Runtime.Remoting.Services
位於其它命名空間的重要型別還包括：
System.AppDomain
System.CallContext
System.ContextBoundObject
System.ContextStaticAttribute
System.MarshalByRefObject


Web 服務
從邏輯上來看，w eb 服務只是r emot i ng（遠端服務）的一個實例。事實上，BCL
對於web 服務的支援被視為ASP .NET 的一部份，而且它跟CLR 的r emoti ng 基礎
設施大部份是分開的。BCL 提供有專門的類別及屬性，可用於描述與發佈web 服
務，找出有何種web 服務被陳列在特定的端點（URI）上，並可叫用w eb 服務的
方法。
至於更詳細的資訊，請參考以下的命名空間：
System.Web.Services
System.Web.Services.Description
System.Web.Services.Discovery
System.Web.Services.Interop
System.Web.Services.Protocols


資料存取
BCL 包含了一組類別，可用以存取資料來源，並可管理複雜的資料集；這就是所
謂的ADO .NET 。這些類別在.NET 平台中將取代Wi n32 之ADO 的角色。ADO+
同時支援了連接及非連接的操作、多重資料提供者（包含非關聯性的資料來源），
以及與XML 之間的序列化轉換。
至於更詳細的資訊，請參考以下的命名空間：
System.Data
System.Data.ADO
System.Data.ADO.Interop
System.Data.CodeGen
System.Data.Design
System.Data.Internal
System.Data.SQL
System.Data.SQLTypes


XML
BCL 針對X ML 1.0 、XML schemas 以及XML 命名空間提供了廣泛的支援，它提供
了兩項個別的XML 剖析模組（一個以DO M2 為主的模型，與一個SA X2 之pull
mode 的變體）以及XSL/T 、X Pat h 與SOAP 1.1 的實作。
至於更詳細的資訊，請參考以下的命名空間：
System.Xml
System.Xml.Serialization
System.Xml.Serialization.IO
System.Xml.Serialization.Schema
System.Xml.XPath
System.Xml.Xsl


圖形
BCL 中包含了支援圖形影像處理的類別；這就是所謂的GDI+。這些類別相當於
Wi n32 的GDI ，並且支援：畫筆（brush）、字型（f ont）、位元映像（bi tmap），文
字處理（text render ing）、基本描繪（dr awi ng pr i mi ti ve）、影像轉換，以及預覽列
印（pr int-pr evi ew）等功能。
至於更詳細的資訊，請參考以下的命名空間：
System.Drawing
System.Drawing.Design
System.Drawing.Drawing2D
System.Drawing.Imaging
System.Drawing.Printing
System.Drawing.Text


豐富的用戶端應用程式
BC L 中包含了建立典型GU I 應用程式的支援。這項支援稱作Wi nd ow s 表格
（Wi ndows For m），而且它的組成為：一份表格套件、一組預先定義好的GUI 元件
集，以及一個RAD 設計者工具適用的元件模型。這些類別提供了多種程度的抽象
化，從低階的訊息迴圈處理器（m es sage-loop handl er ）類別到高階的版面配置管
理員（layout manager ）及視覺化繼承（visual i nher i t ance）。
至於更詳細的資訊，請參考以下的命名空間：
System.WinForms
System.WinForms.ComponentModel
System.WinForms.ComponentModel.COM2Interop
System.WinForms.Design
System.WinForms.PropertyGridInternal


Web 為主的應用程式
BCL 中包括了建立Web 為主之應用程式的支援。這項支援稱作Web 表格（Web
For m），而且它的組成為：一份伺服端的表格套件（它可產生HTML 使用者介
面）、一組預先定義的G UI wi dgets ，以及一個RAD 設計者工具適用的元件模型。
BC L 也包含了一組類別，可用以管理「對談狀態」（s essi on st ate）、安全、快取
（caching）、偵錯、追蹤、當地語系化（local i zat i on）、組態設定，以及Web 為主之
應用程式的部署。最後要說明的是，BCL 還包含了可產生或使用w eb 服務的類別
及屬性。這些功就是所謂的A SP .N ET ，它
將完全取代Wi n32 的ASP 。
至於更詳細的資訊，請參考以下的命名空間：
System.Web
System.Web.Caching
System.Web.Configuration
System.Web.Handlers
System.Web.Hosting
System.Web.Security
System.Web.SessionState
System.Web.UI
System.Web.UI.Design
System.Web.UI.Design.Util
System.Web.UI.Design.WebControls
System.Web.UI.Design.WebControls.ListControls
System.Web.UI.HtmlControls
System.Web.UI.WebControls
System.Web.UI.WebControls.Design
System.Web.Util


全球化（G l o b a l i z a t i o n ）
BCL 提供了支援全球化的類別，它可用以支援字碼頁（code-page）的轉換、可處
理當地語系（local e-awar e）的字串操作、時間/日期的轉換，以及使用資源檔集中
當地語系化（l ocal i zat ion）的工作。
至於更詳細的資訊，請參考以下的命名空間：
System.Globalization
System.Resources


組態（C o n f i g u r a t i o n ）
BCL 還提供.NET 組態系統的存取，這包括：一個針對使用者（per -user ）或針對
應用程式（per -appli cat i on）的組態模型（其可繼承相關的組態設定），以及一個交
易式安裝程式（tr ans cat ed ins t al ler ）的架構。相關的類別可同時使用這項組態架
構，並且可加以延伸。
至於更詳細的資訊，請參考以下的命名空間：
System.Configuration
System.Configuration.Assemblies
System.Configuration.Core
System.Configuration.Design
System.Configuration.Install
System.Configuration.Interceptors
System.Configuration.Internal
System.Configuration.Schema
System.Configuration.Web


進階的元件服務
BCL 提供了建立COM+服務的支援，譬如：分散式交易、JI T 的啟動、物件集區
（object pool i ng）、佇列以及事件。BCL 還包含了透過既存之訊息佇列架構
（MSMQ）進行穩定的、非同步的、單向訊息存取的類型。BCL 同時包含了可用以
存取現有名錄服務（Acti ve Dir ector y）的類別。
至於更詳細的資訊，請參考以下的命名空間：
Microsoft.ComServices
System.DirectoryServices
System.Messaging
System.Messaging.Design


配件（A s s e m b l y ）
BCL 所提供的屬性，可在配件中標記相關的資訊，譬如：標的機器之作業系統與
處理器、配件的版本，以及其它的資訊。
至於更詳細的資訊，請參考以下的命名空間：
System.Runtime.CompilerServices
System.Runtime.CompilerServices.CSharp


診斷與偵錯
BCL 還包含了以下的類別：支援「多重聽眾」（mult il i st ener ）的偵錯追蹤；存取事
件日誌檔，存取行程、執行緒，以及堆疊框的資訊；並且具備製造及使用效能計數
器的能力。
至於更詳細的資訊，請參考以下的命名空間：
System.Diagnostics
System.Diagnostics.Design
System.Diagnostics.SymbolStore


與未受控管之程式碼的互通性
.NET 執行期與未受控管之程式碼的互通性，可透過COM 、COM+及原生的Wi n32
API 呼叫來實施。BCL 提供了一組類別及屬性可支援此項功能，包括：精確地控管
物件的生命期，以及建立使用者定義的自訂封送處理器（mars hal ler ）以處理特定
的互通性狀況。
至於更詳細的資訊，請參考以下的命名空間：
System.Runtime.InteropServices
System.Runtime.InteropServices.CustomMarshalers
System.Runtime.InteropServices.Expando
Microsoft.Win32.Interop
Microsoft.Win32.Interop.Trident
位於其它命名空間的重要型別還包括S y s t e m . B u f f e r 。


元件與工具的支援
在.NET 的執行期間，元件與類別的差異在於，元件具有額外的「中介資料」
（metadat a）及其它措施，可協助元件表格套件的使用，譬如Wi ndows 表格及Web
表格。BCL 所提供之類別及屬性，可同時建立元件以及建立使用元件的工具。這
些類別也包含了產生及編譯C#、Js cri pt 及VB.NET 原始碼的能力。
至於更詳細的資訊，請參考以下的命名空間：
System.CodeDOM
System.CodeDOM.Compiler
System.ComponentModel
System.ComponentModel.Design
System.ComponentModel.Design.CodeModel
System.ComponentModel.Interop


執行期的措施
BCL 所提供的類別可控制執行期的行為。標準的例子是那些可用來控制「資源回
收器」（gar bage col lect or ）的類別，以及那些提供強及弱之參照支援的類別。
至於更詳細的資訊，請參考S y s t e m 命名空間。
位於其它命名空間的重要型別還包括
S y s t e m . R u n t i m e . I n t e r o p S e r v i c e s . G C H a n d l e 。


原生的作業系統措施
BCL 除了可以控制現有的NT 服務以及見建立新服務外，也能夠存取特定之原生
Wi n32 措施，譬如Wi ndows r egi s t r y 以及Wi ndows （WMI）。
至於更詳細的資訊，請參考以下的命名空間：
Accessibility
Microsoft.Win32
System.Core
System.Management
System.ServiceProcess


WMI(Windows管理規範)
WMI（Windows管理規範：Windows Management Instrumentation）是Microsoft基於Web的企業管理（WBEM）的實現，同時也是一種基於標準的系統管理介面。Windows 2000或以後的版本默認安裝了WMI。而Windows NT4.0雖然支援WMI，但WMI核心元件並沒有隨著NT4.0一起發佈，如果需要WMI，你可以在VS.NET企業構建版中的第五張盤中的“WMI”目錄中找到它。（需要SP4）支援。

也可以在這裡下載 WMI SDK. WMI SDK

NET框架中與WMI規範有關的命名空間有兩個,分別是System.Management和System.Management.Instrumentation兩個命名空間。（Bitmap from CSDN)

System.Management.Instrumentation命名空間提供的類用來設置用戶自定義的應用程式，使得這些應用程式物件能夠符合WMI的規範，而System.Managemen命名空間提供的類物件滛訪問各種管理物件提供了面向物件的編程介面，命名空間System.Management中的成員是很複雜的，下面六個類應該是學習的重點，分別是ConnectionOptions、ManagementScope、ObjectQuery、ManagementObjectSearcher、ManagementObject-Collection和ManagementObject.


程式語言編譯工具
各類程式語言編譯器：
C++ 程式語言：cl.exe
C# 程式語言：csc.exe
JScript 程式語言：jsc.exe
VB.NET 程式語言：vbc.exe
等命令列編譯器。
★其中，C++ 編譯器瞭解新的 Managed Extensions
本節：僅做常用工具介紹，其他請參考幫助檔


Csc.exe (命令列方式編譯C#)

C# 編譯器可由在命令列中，鍵入它的可執行檔名稱 (csc.exe) 來叫用 (Invoke)。如果想從電腦中任一個子目錄叫用 csc.exe，您可能需要調整路徑。

執行 VCVARS32.BAT

vcvars32.bat 檔設定適當的環境變數以啟用命令列建置。

若要執行 VCVARS32.BAT

  1. 在命令提示字元下，變更至您安裝的 \bin 子目錄。
  2. 鍵入 VCVARS32 來執行 VCVARS32.bat。
    警告 VCVARS32.bat 依不同電腦而有差異。請勿以另一部電腦中的 VCVARS32.bat 取代遺失或損毀的 VCVARS32.bat 檔。請重新執行安裝程式取代遺失的檔案。

如需 vcvars32.bat 的詳細資訊，請參閱下列知識庫 (Knowledge Base) 文件：

  • Q248802 : Vcvars32.bat Generates Out of Environment Message

如果目前版本的 Visual Studio 安裝在也有舊版 Visual Studio 的電腦上，您便不應該在同一個命令視窗中執行不同版本的 vcvars32.bat。

C# 編譯器和 C++ 編譯器輸出的不同之處

叫用 C# 編譯器時並不會產生目的檔 (.obj)；而是直接產生輸出檔。基於此點，C# 編譯器並不需要連結器 (Linker)。

命令列語法規則

C# 編譯器程式碼會在解譯作業系統命令列所指定的引數時，使用下列規則：

  • 引數會以空白或定位鍵的泛空白字元 (White Space) 進行分隔。
  • 插入號字元 (^) 不會辨識為逸出字元 (Escape Character) 或分隔符號。這個字元完全由作業系統中的命令列剖析器處理，再傳遞給程式中的 argv 陣列。
  • 由雙引號包夾的字串 ("string") 會解譯成單一引數，不論其內是否包含泛空白字元。有引號的字串可以內嵌到引數中。
  • 前面有反斜線的雙引號 (\") 會解譯為常值雙引號字元 (")。
  • 反斜線會逐字轉譯，除非後面緊接著雙引號。
  • 如果偶數數目的反斜線後面接著雙引號，在 argv 陣列中會用一條反斜線代表一對反斜線，雙引號則轉譯為字串分隔符號。
  • 如果奇數數目的反斜線後面接著雙引號，在 argv 陣列中會用一條反斜線代表一對反斜線，雙引號則使用剩下的反斜線「逸出」，導致 argv中放置常值雙引號 (")。

命令列範例

  • 編譯 File.cs 產生 File.exe：
    csc File.cs
  • 編譯 File.cs 產生 File.dll：
    csc /target:library File.cs
  • 編譯 File.cs 和建立 My.exe：
    csc /out:My.exe File.cs
  • 在啟用最佳化和定義 DEBUG 符號情況下，編譯目前目錄中的所有 C# 檔案。輸出為 File2.exe：
    csc /define:DEBUG /optimize /out:File2.exe *.cs
  • 編譯目前目錄中所有的 C# 檔案，產生 File2.dll 的偵錯版本。不顯示標幟和警告：
    csc /target:library /out:File2.dll /warn:0 /nologo /debug *.cs
  • 將目前目錄中所有的 C# 檔案編譯成 Something.xyz (一個 DLL)：
    csc /target:library /out:Something.xyz *.cs


ILDASM.exe (MSIL 反組譯工具)

MSIL 反組譯工具是 MSIL 組譯工具 (Ilasm.exe) 的附屬工具。Ildasm.exe 使用包含 Microsoft Intermediate Language (MSIL) 程式碼的可攜式執行檔 (PE)，並建立可以做為 Ilasm.exe 的輸入檔的文字檔。

其他功能：請參考幫助檔說明

使用ILDASM.exe 範例：

//Hello World Program HelloWorld.cs
using System;

class HelloWorld
{
     static void Main()
     {
        Console.WriteLine("Hello, world!");
     }
}
Complier it on command line by using csc HelloWorld.cs

Helloworld.exe file will be generated

Now use the command ildasm HelloWorld.exe

You will see a screen like this.

Here you can see all of the Symbols. The table below explains what each graphic symbol means. Some of them you can find in HelloWorld's members.

The tree in this window shows that manifest information contained inside HelloWorld.exe. By double-clicking on any of the types in the tree, you can see more information about the type.

Double-clicking the ".class public auto ansi" entry shows the following information:

Users can see that the HelloWorld type is derived from the System.Object type.

The first method, .ctor, is a constructor. This particular type has just one constructor but other types may have several constructors each with a different signature. If you double-click on the constructor method, a new window appears showing the IL (intermediate language) contained within the method:

The Common Language Runtime is stack based. So, in order to perform any operations, the operands are first pushed onto a virtual stack and then the operator executes. The operator grabs the operands off the stack, performs the desired operation and places the result back on the stack. At any one time, this method will have no more than 8 operands pushed onto the virtual stack. We can see thby looking at the ".maxstack" attribute ( Maximum Stack size ) that appears just before the IL code. In the above code maxstack is shown as 8.

Lets examine the IL code :

IL_0000:  ldarg.0 : Load Object this pointer in stack
IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
IL_0006:  return the value loaded in stack
If user make a double click on main: void()
It will look like this:

If we will examine IL Code:

IL_0000:  ldstr      "Hello, world!"
IL_0005:  call       void [mscorlib]System.Console::WriteLine(class System.String)
IL_000a:  ret
LDSTR: Load String.
First line indicates load String in stack.
Second Line indicates call method System.Console:: WriteLine as the fetch the value from stack put in this method and again put the result in stack.
Third line shows fetch the final value from stack and return it.

There are some advance option also available. The extra options are enabled by running ILDASM with the /ADV ("ADVanced") command-line switch. When /ADV is specified, ILDASM enables additional command-line switches. For the user convenience I will summarize some basic instructions here below.

Instruction | Meaning
LDC | This instruction pushes a hard coded number on the stack.
LDARG and LDARGA | Load argument and load argument address, respectively
LDLOC and LDLOCA | Load local variable and load local variable address, respectively
LDFLD and LDSFLD | Load Object Field and Load Static Field of a Class, respectively
LDELEM | Load an element of an array
LDLEN | Load the length of an array
STARG | Store a value in an argument slot
STELEM | Store an element of an array
STFLD | Store into a field of an object
CEQ | Compare equal
CGT | Compare greater than
CLT | Compare less than
BR | Unconditional branch
BRFALSE and BRTRUE | Branch on false and branch on true, respectively
CONV | Data conversion
NEWARR | Create a zero-based, one-dimensional array
NEWOBJ | Create a new object
BOX | Convert value type to object reference
UNBOX | Convert boxed value type to its raw form
CALL and CALLVIRT | Call a method and call a method associated at runtime with an object, respectively


WinCV.exe (類別檢視器)
所在位置：C:\Program Files\Microsoft.NET\SDK\v1.1\Bin\WinCV.exe
選項功能：請參考幫助檔說明
Windows Form 類別檢視器可以讓您根據搜尋模式快速查閱類別或一系列類別的資訊。這個類別檢視器使用 Common Language Runtime 反映 API 來藉由在型別上反映以顯示資訊。
備註:
從命令列啟動 Wincv.exe，然後在表單上方的文字方塊中輸入全部或部分型別名稱。在表單左邊的清單方塊會根據您所輸入的名稱顯示 Wincv.exe 找到的所有型別清單。System 命名空間 (Namespace) 是隱含在類別名稱中。因此，類別名稱清單中顯示的是型別「Object」，而不是「System.Object」。當您從清單中選取型別，型別定義會顯示在右邊的區域中。型別定義是使用類似 C# 的語法顯示的。不過，請注意，並非所有型別定義在 C# 編譯器中都會像檢視器所顯示的一樣被編譯。下列範例說明如何查閱 ButtonBase 類別的資訊。
若要使用 Wincv.exe 找出型別定義:
  1. 在命令提示字元輸入 wincv。這會載入預設的組件和顯示類別檢視器。
  2. 在表單上方的文字方塊中輸入 Button。
  3. 從顯示在表單左邊的清單方塊中的型別選取 System.Windows.Forms 命名空間中的 ButtonBase 類別名稱。

  • System.Windows.Forms.ButtonBase 的定義便會顯示在右邊的區域

    • 範例
    下列命令會執行 Wincv.exe 並載入 myApp.exe 和要用於瀏覽的預設組件。
    wincv /r:myApp.exe
    下列命令會執行 Wincv.exe 並只載入要用於瀏覽的 myApp.exe。預設組件不會載入。
    wincv /r:myApp.exe /nostdlib+
    下列程式碼是顯示回應檔 myFile.rsp 的內容。使用回應檔可以省去在命令提示字元個別輸入命令的麻煩。
    /r:myAssembly.dll
    /r:myOtherAssembly.dll
    下列命令會讀取回應檔 myFile.rsp，並執行檔案中所指定的命令。
    wincv @myFile.rsp


Winres.exe (資源編輯器)

Windows Form 資源編輯器是視覺化的版面工具，可幫助當地語系化專家將 Windows Form 表單當地語系化。當做 Winres.exe 輸入的 .resx 或 .resources 檔案可以使用視覺化設計環境來建立，例如 Microsoft Visual Studio .NET。如需在 .NET Framework 應用程式中部署資源的詳細資訊，請參閱應用程式中的資源。

winres resourceFile
選項部分：請參考幫助檔說明
備註

Windes.exe 可裝載 Windows Form 表單設計工具和 [屬性] 視窗。您可以使用這些功能來開啟中性文化特性 (Neutral Culture) 的 .resources 或 .resx 檔案，它包含要當地語系化的 Windows Form 表單。在設計工具中，當地語系化人員可編輯控制項標籤以及調整控制項的位置和大小，以配合目標文化特性的標籤。Winres.exe 可讓您將這些修改儲存在目標文化特性已當地語系化的 .resx 或 .resources 檔案中。

Winres.exe 可以讓協力廠商的當地語系化人員重新建立設計階段版本的 Windows Form 表單，並將它當地語系化，而不必存取原始程式碼或 Windows Form 表單上的所有控制項。如果 Winres.exe 無法解析控制項的類型，它會在已當地語系化的 .resx 或 .resources 檔案中建立預留位置控制項。預留位置控制項在 Windows Form 表單上會顯示為規劃視窗。規劃視窗的大小和位置與實際控制項的大小和位置相符。預留位置控制項可使用的所有可當地語系化屬性都會顯示在 [屬性] 視窗中。您對預留位置控制項所做的任何變更都會儲存在實際的控制項中。

注意   請不要使用 Winres.exe 來編輯中性文化特性的字串。Winres.exe 只會將可當地語系化的屬性儲存到目標檔案中。其他資訊全部都會遺失。

在開始將應用程式的 Windows Form 表單當地語系化之前，應該先決定要使用 Visual Studio .NET 或 Winres.exe 作為當地語系化工具。這兩種工具所產生的當地語系化 .resx 檔案不能交換。因此，在您使用其中一個工具開始當地語系化之後，就不能再切換為另外一個工具。

Visual Studio .NET 的優點就是您可以使用它來開發應用程式，以及將應用程式當地語系化。若要將表單當地語系化，在開發完成之後，請將表單的 Localizable 屬性設定為 true，並將它的 Language 屬性變更為想要的目標文化特性。然後編輯字串並調整控制項的位置和大小，以配合目標文化特性的字串。當您儲存當地語系化的 .resx 檔案時，Visual Studio .NET 只會將可當地語系化的屬性 (在目標文化特性中變更的屬性) 寫入檔案中。Visual Studio .NET 會自動在正確的目錄位置中，為當地語系化的 .resx 檔案建立附屬組件。如需使用 Visual Studio .NET 來當地語系化表單的詳細資訊，請參閱 Visual Studio .NET 文件中的＜逐步解說：當地語系化 Windows Form＞。

雖然 Visual Studio .NET 提供整合式的開發和當地語系化環境，但是如果是由協力廠商的當地語系化人員來進行當地語系化，建議您使用的工具就是 Winres.exe。由於 Winres.exe 只是當地語系化工具，因此它可以讓應用程式的程式碼與要當地語系化的表單完全分隔，在管理大型專案時，這樣的功能將會非常的實用。

若要使用 Winres.exe 當地語系化，必須先使用像是 Visual Studio .NET 這類視覺化設計工具開發應用程式。當開發完成時，請將表單的 Localizable 屬性設定為 true，然後將中性文化特性的 .resx 檔案交由協力廠商的當地語系化人員。這個 .resx 檔案包含 Winres.exe 重新建立原始表單的設計階段版本所使用的額外資訊。由於 Winres.exe 和 Visual Studio .NET 所產生的 .resx 檔案內容不同，因此 Winres.exe 無法開啟先前使用 Visual Studio .NET 為目標文化特性當地語系化的 .resx 檔案。例如，Winres.exe 可開啟中性檔案 project1.resx，但是無法開啟由 Visual Studio .NET 產生的當地語系化檔案 project1.fr-FR.resx。同樣地，使用 Winres.exe 為目標文化特性當地語系化的 .resx 檔案與 Visual Studio .NET 也不相容。如果您選擇使用 Winres.exe 作為您的當地語系化工具，您必須使用資源檔產生器 (Resgen.exe)，將當地語系化的 .resx 檔案轉換成 .resources 檔案，然後使用組件連結器 (Al.exe) 或 C# 編譯器 (Csc.exe)，將 .resources 檔案編譯成附屬組件。如需這個程序的詳細資訊，請參閱建立附屬組件。

範例

將和表單關聯的 .resx 或 .resources 檔案當地語系化

  1. 請在命令提示字元處輸入 winres，執行 Winres.exe。
  2. 若要為要當地語系化的表單開啟中性資源，請按一下 [檔案] 功能表上的 [開啟] 命令，並巡覽至要開啟的檔案。或者，您可以在啟動 Winres.exe 時，在命令列指定要開啟的檔案。下列命令會在表單設計工具中啟動 Winres.exe 並載入和 MyResources.resx 關聯的表單。
    winres MyResources.resx

    下列命令會在表單設計工具中啟動 Winres.exe 並載入和 MyResources.resources 關聯的表單。

    winres MyResources.resources
  3. 選取表單上的控制項並變更文字屬性，以反映當地語系化的語言。依照需要移動或調整控制項大小，以配合當地語系化的文字。
  4. 若要儲存 .resx 或 .resources 檔案的當地語系化版本，請按一下 [檔案] 功能表上的 [另存新檔] 命令。工具會顯示 [選取文化特性] 視窗。按兩下適當的文化特性。工具會使用 Runtime 所需的當地語系化資源檔命名慣例來儲存檔案。例如，如果您在德國為德國人當地語系化 MyResources.resources，工具會將檔案儲存為 MyResources.de-DE.resources。如果您在德國為德國人當地語系化 MyResources.resx，工具會將檔案儲存為 MyResources.de-DE.resx。如需資源命名慣例的詳細資訊，請參閱封裝和部署資源。如需 Runtime 所使用的預先定義文化特性名稱清單，請參閱 CultureInfo 類別。


TlbExp.exe(NET轉COM)
Type Library Exporter (TlbExp.exe)

說明：轉換 .NET assembly 到 COM type library
備註：其他請參考幫助檔說明
執行範例：

TlbExp NetComponent.dll ComComponent.tlb


TlbImp.exe(COM轉NET)
Type Library Importer (TlbImp.exe)

說明：轉換 COM type library 到 .NET DLL
備註：其他請參考幫助檔說明
執行範例：
tlbimp ComComponent.tlb NetComponent.dll


gacutil.exe (全域配件註冊工具)
1.GAC (Global Assembly Cache)登入註冊位置：
  %systemroot%\assembly
2.配件註冊方式：
  指令： gacutil -i MyUtil.dll

  備註：其他請參考幫助檔說明

3.取得已註冊配件版本訊息：
  指令：gacutil /l
  例如：
C:\Documents and Settings\ohta>gacutil /l System.Drawing.Design

Microsoft (R) .NET Global Assembly Cache Utility.  Version 1.1.4322.573
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.

The Global Assembly Cache contains the following assemblies:
        System.Drawing.Design, Version=1.0.3300.0, Culture=neutral, PublicKeyTok
en=b03f5f7f11d50a3a, Custom=null
        System.Drawing.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyTok
en=b03f5f7f11d50a3a, Custom=null

The cache of ngen files contains the following entries:
        System.Drawing.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyTok
en=b03f5f7f11d50a3a, Custom=5a00410050002d004e0035002e0031002d003800460044002d00
300030004200340041003300340041000000
        System.Drawing.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyTok
en=b03f5f7f11d50a3a, Custom=5a00410050002d004e0035002e0031002d00380046002d003000
30003400380038003100390043000000

Number of items = 4


PRB: Cannot Add ActiveX Control to Toolbox
(aximp.exe)Cannot Add ActiveX Control to Toolbox
適用於
This article was previously published under Q320780

SYMPTOMS

After you use Aximp.exe to wrap an ActiveX control, you may receive the following error message when you try to add the Ax wrapper to the .NET Framework Components tab in the Customize Toolbox dialog box:
There are no components in fully qualified path to the Ax wrapper dll that can be placed on the toolbox.

CAUSE

By default, the ToolboxItem attribute is set to False in the generated Ax wrapper. A False value for this attribute prevents the control or wrapper from being added to the Toolbox.

RESOLUTION

There are two resolutions to this problem:
  • Import the Control by Using the Development Environment

    The easiest way to avoid this problem is to add the ActiveX control to the Toolbox from the COM Components tab instead of by running Aximp.exe and using the .NET Framework Components tab in the Customize Toolbox dialog box. The development environment generates the wrappers that you need when you add the control through the COM Components dialog box.
  • Manually Change the Attribute Value
    1. NOTE: All of the file names in the commands in step 1 and step 3 must be fully qualified path names.

    2. Run Aximp.exe with the /source switch to generate the Visual C# code for the Ax wrapper for the specified ActiveX control. The file generates the source file, an interop assembly, and an Ax wrapper assembly for the specified control. For example, the following command generates the Visual C# source code (Axmscomdlg.cs) for the Ax wrapper for the Microsoft Common Dialog Control:
      aximp comdlg32.ocx /out:AxMSComDlg.dll /source
    3. Open the Visual C# source file in a text editor such as Notepad, insert the following attribute statement, and then save the .cs source file:
      [System.ComponentModel.ToolboxItemAttribute(true)]
      NOTE: Make sure that you insert the statement after the namespace and before the class definition.

    4. Use the following command to compile the .cs file:

      NOTE: Make sure that you reference the runtime callable wrapper (RCW) assembly:
      csc /t:library /r:MSComDlg.dll /out:AxMSComDlg.dll AxMSComDlg.cs

MORE INFORMATION

Aximp.exe converts a whole ActiveX Control type library at one time and produces a set of assemblies that contain the Common Language Runtime meta data and control implementation for the types that are defined in the original type library. The generated files are named according to the following pattern:
  • Common Language Runtime proxy for COM types: Progid.dll
  • Windows Forms proxy for ActiveX controls (where Ax signifies ActiveX): AxProgid.dll
For the control that is used as an example in this article (Comdlg32.ocx), the files that are created are Mscomdlg.dll and Axmscomdlg.dll.)

Steps to Reproduce the Problem

This problem can be reproduced by using any ActiveX control. The Microsoft Common Dialog Control (Comdlg32.ocx) is used in this example.
  1. Execute the following command from a Visual Studio .NET command prompt:
    aximp comdlg32.ocx /out:AxMSComDlg.dll /source
    NOTE: This command generates the Ax wrapper (Axmscomdlg.dll), the RCW (Mscomdlg.dll), a program database file (Axmscomdlg.pdb), and the Visual C# source file (Axmscomdlg.cs) for the Ax wrapper.

  2. Start a new Visual Basic or Visual C# Windows Application project. By default, Form1 is created.
  3. On the Tools menu, click Customize Toolbox.
  4. Click the .NET Framework Components tab.
  5. Click Browse, and then locate the folder that contains the Ax wrapper that was generated in step 1.
  6. Click to select Axmscomdlg.dll, and then click Open. You receive the error message that is described in the "Symptoms" section.

The information in this article applies to:

  • Microsoft Visual C# .NET (2002)
  • Microsoft Visual Basic .NET (2002)
  • Microsoft Visual J# .NET (2002)


.Net環境的下的程式破解
首先介紹一下.Net環境下的程式形成程序。[參照下圖]

(1)程式員用高級OO語言(C#,VB.Net,VC.Net,Cobol,Python..)編寫程式碼，這些程式碼經過
.Net編譯器（比如Visual Studio.Net），編譯成統一的MSIL(Microsoft Intermediate Language)。NET應用程式是以MSIL的形式出現的，只有在程式執行的時候才通過即時編譯器JIT(Just-In-Time)被編譯為本機程式碼。
(2)程式執行的時候，由JIT裝入程式的MSIL，JIT同時作了很多其他的工作（裝載相應的執行庫，安全檢測。。） 最後JIT將轉化成本地機器碼(EXE或者DLL)。
(3)本地機器碼被裝入記憶體，開始執行。

就是通過這幾個步驟，.net實現了設計語言無關（都轉化成MSIL）；平台無關（執行的
時候根據本地配置，生成相應的機器碼）；安全性（JIT裡面做了很多檢測）。

作為Cracker，可以用.Net Framework SDK自帶的工具進行MSIL和EXE(DLL)之間的互換：
利用FrameworkSDK\Bin\目錄下的ilasm和ildasm，安裝了.Net Framework以後，這兩個程式已經被加為系統路徑，可以在"執行"裡面輸入"ilasm"或者"ildasm"直接打開。

(1)ilasm示例：
下面的命令對 MSIL 檔案 myTestFile.il 進行彙編並產生可執行檔案 myTestFile.exe。
ilasm myTestFile
下面的命令對 MSIL 檔案 myTestFile.il 進行彙編並產生 .dll 檔案 myTestFile.dll。
ilasm myTestFile /dll
下面的命令對 MSIL 檔案 myTestFile.il 進行彙編並產生 .dll 檔案 myNewTestFile.dll。
ilasm myTestFile /dll /output:myNewTestFile.dll
(2)ildasm示例
下面的命令使 PE 檔案 MyHello.exe 的元資料和反彙編程式碼顯示在 Ildasm.exe 的預設 GUI 中。
ildasm myHello.exe
下面的命令對 MyFile.exe 檔案進行反彙編，並將結果 MSIL 彙編程程式文字存儲在 MyFile.il 檔案中。

ildasm MyFile.exe /output:MyFile.il
下面的命令對 MyFile.exe 檔案進行反彙編，並將結果 MSIL 彙編程式文字顯示到控制台視窗中。

ildasm MyFile.exe /text
如果檔案 MyApp.exe 包含嵌入的托管和非托管資源，則下面的命令將產生以下 4 個檔案：MyApp.il、MyApp.res、Icons.resources 和 Message.resources：

ildasm MyApp.exe /output:MyApp.il
下面的命令對 MyFile.exe 的 MyClass 類中的 MyMethod 方法進行反彙編，並將輸出顯示到控制台視窗中。

ildasm /item:MyClass::MyMethod MyFile.exe /text
在上面的示例中，可能有幾個具有不同簽名的 MyMethod 方法。下面的命令對返回類型為 void 且帶有參數 int32 和 System.string 的 MyMethod 方法進行反彙編。

ildasm /item:"MyClass::MyMethod(void(int32,class System.String))" MyFile.exe /text

通過上面分析可知，我們(Cracker)需要分析的對象就是MSIL形式的檔案了，當然估計很快就有不少"混淆器"誕生，讓我們無法從exe中恢復MSIL，不過肯定也會有相應得"反混淆器"被開發出來，所以不必擔憂，嘿嘿~~ [image] 下一貼我將介紹MSIL.

*研究.net可以找一本 Serge Lidin 著的《Inside Microsoft𦲷 .NET IL Assembler 》。
*.NET Interoperability: .NET <-> Win32：
http://www.blong.com/Conferences/BorConUK2002/Interop1/Win32AndDotNetInterop.htm


如何建立有效的.Net軟體註冊保護機制

.Net程式很容易被反編譯出來，也可以通過混淆器來進行一些掩蓋，也可以通過強名稱來保證不被修改。這真是一個矛與盾的問題。

那麼到底怎麼最大限度的保證軟體不被修改、註冊器不容易被編寫。可能真是一個頭痛的問題。

一般的思路大致是：

一、在註冊機制上採用非對稱加密結合數字簽名的方法（這個程序較為複雜，也是我目前沒有弄出來的地方，不過我會努力解決這個問題的，也希望得到高手們的指點）

二、一定要強名稱。關於如何使用強名稱，這個比較容易：一般的步驟是：

     1、在vs.net提供的dos命令視窗裡 用 sn.exe -k 來生成一個鑰匙對。並將之放在專案根目錄下。 如c:\>sn -k c:\YourPrj.snk 然後將YourPrj.snk copy到你的project目錄下。

     2、修改AssemblyInfo.cs，

       [assembly: AssemblyDelaySign(false)]
       [assembly: AssemblyKeyFile("..\\..\\YourPrj.snk")]
       [assembly: AssemblyKeyName("..\\..\\YourPrj.snk")]

      3、rebuild it.這個時候就已經被強名稱保護了。任何對生成的exe或dll進行的修改(無論是IL，或者二進制），都會導致程式將不再執行。

三、通過混淆器對生成的exe或dll進行混淆。推薦採用 http://www.remotesoft.com/salamander/obfuscator/download.html  可以對強名稱保護下的exe或dll進行混淆再重簽名。也就是說，可以得到混淆和強名稱的雙重保護。當然，這裡也就會提出一個問題。就是既然remotesoft的obfuscator可以對強名稱保護下的檔案進行修改（混淆就是大修改了）再重簽到強名稱，雖然它要求YourPrj.snk要保留在project的根目錄下。但我想進行一下替換，應該也是有可能的。因此，從另一角度來思考，這二種方式其實到最後，對於高手來說，都不會是什麼難以對付的問題。其保護功能也就很有限了。


C# 的點滴與連結
仔細閱讀 SDK 文件和檢視後續安裝目錄之後，我相當確定您所能期待的：

  • Visual C++𦲷 (cl.exe)、C# (csc.exe)、JScript𦲷 (jsc.exe) 和 Visual Basic𦲷 (vbc.exe) 的命令列編譯器；其中，C++ 編譯器瞭解新的 Managed Extensions
  • 範例 (有許多以 C# 撰寫) 和建置它們的 nmake.exe
  • 足以支援編譯器和範例的 .NET Runtime 和 .NET Framework
  • 一般的 link.exe
  • 命令列偵錯工具 (cordbg.exe) 和 GUI 偵錯工具 (dbgurt.exe)。
  • 中繼語言 (Intermediate Language，IL) 組譯工具 (ilasm.exe)、反組譯工具 (ildasm.exe) 和驗證程式 (peverify.exe)
  • 應用程式組態和部署、WinForm 設計和檢視、安全性管理以及 JIT 管理的其他工具之裝載
  • 相當完整的文件，有關 Runtime、架構、工具和語言；我對文件提供的數量和品質，印象非常深刻

值得注意的省略：

  • Visual J++𦲷
  • Visual Studio𦲷。這意味著沒有編輯器、沒有整合的偵錯工具和沒有整合的說明 (您可以對這個限制做一點變通，請參閱下文)
  • Microsoft 為每位客戶量身訂做的產品支援和客戶支援

就我所知，我們只支援公開新聞群組的傳播媒介 (我在下文要提到的)，即使那些只是侷限於對等支援和偶爾的 Microsoft 發表。

需求

SDK 需要相當特定的內容來執行：

  • Windows 2000 中，包含有 Internet Information Services (IIS)。如果您已經安裝 Windows 而沒有 IIS，您可以經由控制台的 [新增/移除程式] 窗格來加入。如果您決定省略 IIS，您仍可以安裝 SDK，但您將無法建置 SDK 的所有範例。
  • Internet Explorer 5.5 版 ( http://www.microsoft.com/downloads/release.asp?ReleaseID=32084 )。要是沒有 Internet Explorer 5.5，SDK 將無法安裝。
  • Microsoft Data Access Components (MDAC) 2.6 版 ( http://www.microsoft.com/data/download_260rtm.htm )。您可以安裝 SDK 而不需要這個，但您將無法執行某些範例，或呼叫某些架構元件。

我很幸運，可以使用環境乾淨的電腦來著手、依照指定順序安裝上述軟體，然後安裝 SDK。

SDK 檔案會安裝到兩個主要位置：

  • C:\Program Files\NGWSSDK。就我所見，這是 .NET 和需要它來執行的程式 (例如編譯器) 的主目錄 (Home Directory)。您可以在安裝期間覆寫更改這個位置。
  • C:\WINNT\ComPlus\v2000.14.1812 (假設您的系統根目錄為 C:\WINNT)，其中的 2000.14.1812 根據日期和建置編號進行編碼。這個數字命名法允許多個 .NET 版本的並排安裝。這目錄含有工具、C++ Include 檔、C++ 程式庫檔案、文件和範例。您在安裝期間無法覆寫這個位置。

您應該將 SDK 只安裝在您經得起損失的電腦上。請不要將它安裝在您的主要生產電腦上，除非您樂於教它們當機。並且不要在 Windows 2000 以外 (而這包括 Windows NT?4.0 作業系統) 的任何作業系統上嘗試它，即便朋友的朋友說它行得通。

我們稱這個下載為技術預覽，並有很好的理由來分贈它。它是準備用來給您做實驗和自我教育的，而不是要您的 IT 部門來進行全公司的安裝。還請您相應地調整您的期待。

與 Visual Studio IDE 的整合

假設您已將它備妥，我鼓勵您安裝 Visual Studio 6.0 Integrated Development Environment (IDE)，注意：不是編譯器、不是程式庫、不是任何其他工具，只是 IDE。您可以接著使用 IDE 來編輯您的 C# 檔案、繁衍 (Spawn) C# 編譯器，並逐步追蹤 C# 編譯時期錯誤。遺憾的是，Visual Studio 安裝程式沒有任何單獨安裝 IDE 的選項。您可以做到的最接近地步是：

  • 執行 Visual Studio 安裝程式，並遵循您一般會做的安裝順序。
  • 當有選項出現時，選取「自訂」安裝路徑代替「一般」路徑。
  • 在產生的對話方塊中，取消核取除了 [Visual C++ Developer Studio] 以外的一切選項。
  • 按下 [繼續]，然後讓安裝完成。

這個程序將會安裝 IDE，連同一票其他您不需的東西 (前置資料、程式庫、教學課程和其他工具)。那些東西的一大部份會在新安裝的 VC98 目錄中，您可以安全地將它刪除。

若要讓這一切運作得幾乎不著痕跡，您必須加入自訂工具到 IDE 的工具列。例如，若要建立自訂工具，以建置目前 C# 原始程式檔 (Source File) 並執行已建置的程式，請進行下列步驟：

  • 啟動 Visual Studio 6.0 IDE。
  • 從 [工具] 功能表選取 [自訂...]。
  • 在產生的 [自訂] 對話方塊中選取 [工具] 索引標籤。
  • 捲動到 [功能表內容] 清單的底端，按一下底端的空白行。
  • 在那空白行中輸入 C# &run，然後按下 Enter 鍵。
  • 在 [命令] 欄位中輸入 cmd.exe。
  • 在 [引數] 欄位中輸入 /c csc "$(FilePath)" && "$(FileName)"。
  • 核取標記為 [使用輸出視窗] 的方塊。

如果您已經正確做完這些步驟，對話方塊應該看起來有點像這樣：

現在當您從 [工具] 功能表選取 [C# run] 或輸入 Alt-T Alt-R，IDE 的現用原始程式檔將會編譯。如果編譯 (Compilation) 成功，產生的 C# 可執行檔將會執行，並將其輸出顯示在輸出視窗。如果編譯失敗，編譯器診斷將出現在那相同的輸出視窗。要是發生這種情形，您可以用 F4 逐步執行診斷，因為它們遵循那些在 Visual C++ 6.0 版中的同樣格式。

限制：

  • 這個範例只編譯和連結最前面的原始程式檔。它是用來證明概念，而不是要設計得很穩固或有彈性。實務上，您很可能會建立 Makefile 並執行 nmake 或類似建置工具。
  • 您無法直接在 IDE 內偵錯 C#。您將必須使用 SDK 偵錯工具來代替。我把這點留給讀者當作練習：請建立 IDE 自訂工具，在有用的狀態中繁衍 SDK 偵錯工具的其中一個。
  • 編輯器並不「知道」 C#，因此無法顯示適當的文字格式和語法色彩。您可以藉著指定 C# 的副檔名來做一點變通，好讓編輯器將它聯想成 C++ 檔案。
  • 即時線上說明無法正常工作，因為 Visual Studio 6.0 版的說明系統不知道 C#。

經常提出的話題 (Frequently Flamed Topics，FFT)

我已花上相當大量的時間閱讀您在 .NET 相關 MSDN 專欄和文章上的評論。我也已經漫遊於非 Microsoft Web 網站和新聞群組上 Net 讀物的相關張貼。在我所有的閱讀過程中，我不斷碰到一組共同的抱怨或誤解，還有附屬的一組詆毀言論和宗教戰爭。我想在此說明那些論點的一部分：

  • C# 沒有泛用物件或樣板。許多人都想要它們。我們也是。C# 設計小組正在與來自英國的 Microsoft Research 一起努力將泛用物件整合到語言中。真的很期待未來幾個月可以看到一些這方面 (至少是實驗性的) 的工作進展。請不要期待它會成為我們第一個 C# 版本的標準部份。
  • 不滿意 SDK，某些客戶想要整個 Visual Studio .NET 環境能夠提供下載。各位，我認為新的 Visual Studio 勢必將造成轟動，一旦它發行之後，真的。但此刻，它比起編譯器和其他工具則相對地不穩定。事實上，我在我的 C# 工作上使用前述的 Visual Studio 6.0 setup I，犧牲了一些功能來取得穩定性。一旦我們發行 Visual Studio .NET 的第一個 Beta 版之後，我期待可以開始使用它，因為那將是大部分的人所最可能使用的。
  • 記憶體回收是 .NET Runtime 的一部份。記憶體回收行程支配所有 Managed 物件，不論其來源語言的出身為何；相應地，所有想要 Managed 資料的 .NET 語言 (包括 C#) 都受 Runtime 的記憶體回收行程管制。因些，記憶體回收就其本身而言並不是 C# 的功能，而是 C# 所使用並顯露 (而且可以覆寫) 的 Runtime 功能。
  • 記憶體回收的一個加工品：C# 物件沒有決定性的解構。著手於 C# 的 Java 程式設計人員似乎不太在意這點，然而 C++ 程式設計人員卻發現它令人厭惡。即使 C# 物件允許 C++ 樣式解構，那些物件與 Common Runtime 的其他語言交互操作時將會產生麻煩。

    我們知道很多人想要這個功能，而且我們也正在研究其可能性。若要正確做到這點，必須要對語言和 Runtime 兩方面做出非同小可的變更。即便我們的確要在這裡進行變更 (我要強調是如果，不是何時)，我嚴重懷疑我們將會完全複製 C++ 的行為。
  • .NET Runtime 就傳統的意義上不是 Virtual Machine (VM)。並沒有任何假造的 CPU「在執行」IL。反而，IL 會轉譯為機器碼，它是被當作程式來實際執行的這個機器碼。如我在先前專欄所提及的，IL 至機器碼的轉譯不是在程式安裝時，就是在程式執行時發生。
  • 名稱「C sharp」實際上是按照我專欄的橫幅圖形所顯示的來拼寫的：大寫字母 C 後面接著樂譜的升記號。因為這個符號不存在於 ASCII，我們大部分的人將名稱大致寫成 C#。這個大致的寫法導致詼諧的衍生詞，例如「C hash」、「C pound」和囉嗦的「C octothorpe」(全都根據便利的但不正確的印刷格式)。我個人的喜好是「D flat」，這帶有聰明伶俐和行為端正的雙重特點，但實際上同樣需要非 ASCII 的印刷格式。

其他資源

  • 除了 .NET SDK 的 PDC Preview 版本之外，我們尚且張貼了 PDC 投影片 (http://commnet.pdc.mscorpevents.com/) 和一些視訊錄影 (http://msdn.microsoft.com/events/pdc/tech/webcast.asp。我所看過的講習會中，我特別推薦介紹性的 (http://commnet.pdc.mscorpevents.com/slides/5-313.ppt) 和進階的 (http://commnet.pdc.mscorpevents.com/slides/5-422.ppt) C# 對話、.NET Framework 概觀 (http://commnet.pdc.mscorpevents.com/slides/3-313.ppt) 和語言整合的討論 (http://commnet.pdc.mscorpevents.com/slides/3-314.ppt)。
  • 我們已經建立討論 .NET 的公開新聞群組 ( news://msnews.microsoft.com/ )，包括一個特別專注於 C# 的群組 ( news://msnews.microsoft.com/microsoft.public.net.csharp.general )。我們在網站 ( http://msdn.microsoft.com/net/#newsgroups ) 上也會列出那些群組。
  • DevX 已經建立它自己的一組 .NET 新聞群組 (news://news.devx.com/)，再次包括一個專門針對 C# 的群組 (news://news.devx.com/csharp.general)。它們同時都在提供這些群組作為 NNTP 挑戰的 Web 架構討論板 (http://news.devx.com/)。這些 DevX 群組有相當的流量和 Microsoft 的強力坐鎮。
  • DevX 另外維護有廣泛的清單 (http://www.devx.com/free/press/2000/vsresources.asp) 或剛成立的 Visual Studio .NET 資源入口網站。
  • Developmentor 正在發起強而有力的 .NET 郵件清單 (http://discuss.develop.com/dotnet.html)。就如其他大約 1,500 個人所做的，我訂閱了這個清單。清單的信號對雜訊比率非比尋常地強。跟 DevX 新聞群組的情形一樣，Developmentor 清單擁有大量的 Microsoft 張貼。並受到高度推薦 (DevX 維護郵件清單精彩部份的保存 (http://www.devx.com/free/press/2000/vs-qalist.asp) 作為準 FAQ)。
  • O'Reilly 的編輯 John Osborn 與 C# 主要設計者 Anders Hejlsberg 的訪談 (http://windows.oreilly.com/news/hejlsberg_0800.html) 頗發人深省。

最後提示

數個月以來我一直將 C# 當作背景工作來探索。我也在上個月的 PDC 經歷對 C# 的皈依。有些讀者顯然會發覺這兩個經驗是矛盾的。

直到參加 PDC 為止，我過去一直在相對真空 (遠離 Run-Time 內容) 的環境下觀察 C#。的確，當我們宣佈 C# 時，語言參考手冊並沒有特別提到執行環境 (這是許多人都會注意到的明顯缺點)。

但在 PDC，我終於學到那個內容。再者，我學到內容是如何在一般程式撰寫模型 (Programming Model) 和執行環境內繫結許多種語言 (不僅 C#)。突然，C# 和 .NET 的圖像全部融合在一起。那就是皈依，而它是如此令人折服以致我確實相信 (而且仍然相信)，你們許多人都會經歷到類似的信仰轉換，一旦您到那個地步。

你們許多人，但不是全部，發現 Microsoft 能夠做的很少是對的，或者沒有是對的，並認為我們員工已經喪失了客觀性並出賣了自已的靈魂。如果您抱持這樣的哲學，您現在應該很可能已經停止閱讀我的文章，無論我帶來什麼訊息，您都將對它保持懷疑。

我也認識到，你們之中有相當多的人認為 Microsoft 能夠做的很少是錯的，或者沒有是錯的，並把我們所說的當作福音真理來接受。這種哲學的追隨者也應該停止讀我的東西，因為當我建議要反對 Microsoft 欽定方式時，他們將遭受認知差距的痛苦。

我邀請您們其他的人每個月都回到這裡。既然您可以對這語言玩真的，我將開始針對 C# 和其 Runtime 深入撰寫，特別是在它們關係到 Standard C++ 和其 Runtime 的時候。

Robert Schmidt 是 MSDN 的技術文件作家。其他的主要寫作陣地是 C/C++ Users Journal，他是這家期刊的撰稿編輯和專欄作家。在過去的生涯角色中，他曾經是電台 DJ、野生動物保護者、天文學家、彈子房經營者、私人偵探、送報員和大學助教。


C# 簡 介
  • C# (唸成「C sharp」) 是 Microsoft 新開發的程式語言，用於發展在 .NET 平台上運作的元件式（component-based）Internet 應用程式與服務 ， C# 擁有 C/C++ 的強大功能以及Visual Basic簡易使用的特性，和 C++ 與 Java 一樣亦為物件導向(object- oriented)程式語言；雖然微軟聲稱其C#的語法95%幾乎與C++相同，但C#的語法其實更像Java，由於微軟與昇陽一直以來視彼此為競爭對手，因此在微軟的原文書中對Java這個字幾乎是隻字不提，更確切地說法，C#的語法其實是由C/C++、Visual Basic和Java四種語言融合而成。
  • C# 免除了DLL Hell, 徹底解決了com元件的登錄，註冊與更新時的版本衝突問題，透過config.web管理，將所需元件放置在 /bin目錄下即可， 除了不需要註冊之外，元件也不會有鎖定的情況，因為執行程式時 會複製/bin下找到的DLL，由於載入的是shadow-copy，因此原始的元件可以被任意地替換，即使程式仍在執行也沒有問題。

標準

  • 微軟在2000年6月公布C#，同年8月微軟、惠普和英特爾共同提報 CLI 和 C# 規格至 「歐洲電腦製造商協會」(ECMA) 的程式語言技術委員會（TC39）。這些共同的贊助廠商，連同其他ECMA成員，包括IBM、Fujitsu Software、惠普、客座專家、Plum Hall、Monash University、ISE和Ximian在內，共同改善提報核准為ECMA標準的規格。
  • 2001年12月，C#程式語言及通用語言架構（Common Language Infrastructure/CLI）通過ECMA的許可成為第一版的標準分別為 ECMA-334 和 ECMA-335 ，2001年12月，修正為第二版。
  • 2003 年 4 月， C#程式語言及通用語言架構（Common Language Infrastructure/CLI）通過國際標準組織 (The International Organization for Standardization/ISO)和世界電訊科技委員會（International Electrotechnical Committee/IEC）的標準認證，成為開發Web services的標準程式語言及架構 『ISO/IEC 23270 (C#), ISO/IEC 23271 (CLI) and ISO/IEC 23272 (CLI TR)』。


C# 程式的一般結構
1.C# 程式可以由一個或多個檔案組成。
2.每個檔案可以包含一個或多個命名空間 (Namespace)。
3.一個命名空間除了可以包含其他的命名空間，還可以包含:
類別、結構、介面、列舉 (Enumeration) 、委派 (Delegate)
等型別。
4.但是每個類別不能跨越多個檔案。


簡介Main() 方法
C# 程式必須包含一個 Main 方法，以便控制項在其中開始和結束。
您可以在 Main 方法中建立物件，和執行其他方法。

Main 方法是位於一個類別或結構內的一種靜態方法。
在「Hello World!」範例中，這個方法位在 Hello 類別中。
宣告 Main 的方式有下列三種：

它會傳回 void：
static void Main()
{
...
}
或
public static void Main()
{
  ...
}

它也可以傳回一個 int：
static int Main()
{
...
return 0;
}

或
public static int Main()
{
  ...
  return 0;
}

它也可以接受引數：
static int Main(string[] args)
{
...
return 0;
}

或
public static int Main(string[] args)
{
 ...
 return 0;
}


使用完整名稱空間
名稱空間 (Namespace) 和型別具有唯一名稱，此名稱由表示邏輯階層架構的完整名稱所描述。例如，A.B 是巢狀於名稱空間 (或稱類型 A) 中的名稱空間 (或稱類型 B) 的名稱。
名稱空間可以用來幫助組織程式的結構，可以避免兩套程式碼集中命名的衝突。

下面程式碼片段中便具有巢狀的類別和名稱空間。每一實體後的註解代表完整的名稱。

namespace N1 // N1
{
class C1 // N1.C1
{
class C2 // N1.C1.C2
{
}
}
namespace N2 // N1.N2
{
class C2 // N1.N2.C2
{
}
}
}


不同名稱空間的呼叫 (範例)
using System;

   namespace Namespace1
   {
     public class Class1
     {
       public static void hello()
       {
         Console.WriteLine("Namespace1的Class1的hello()");
      }
      public static void test()
      {
        hello();
        Class1.hello();
        Namespace1.Class1.hello();
        Namespace2.Class1.hello();
      }
      [STAThread]
      static void Main(string[] args)
      {
       Namespace1.Class1.test();
       Namespace2.Class1.test();
     }
   }
 }
 namespace Namespace2
 {
   class Class1
   {
      public static void hello()
     {
        Console.WriteLine("Namespace2的Class1的hello()");
     }
     public static void test()
     {
       hello();
       Class1.hello();
       Namespace1.Class1.hello();
       Namespace2.Class1.hello();
     }
  }
 }


命名慣例
http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconNamingGuidelines.asp


預先定義的型別

C# 提供了一組預先定義型別，而且大部分都是 C 和 C++ 開發人 員早已熟知的型別。

預先定義的參考型別是 object 和 string。object 型別是所有其他型別的最終基底型別 (Base Type)。string 型別可代表 Unicode 字串值。string 型別值是固定不變的。

預先定義的數值型別包含了帶正負號 (Signed) 和不帶正負號 (Unsigned) 的整數類資料型別 (Integral Type)、浮點數型別，以及 bool、char 和 decimal 等型別。帶正負號的整數類資料型別是指 sbyte、short、int 和 long；而不帶正負號的整數類資料型別則是指 byte、ushort、uint 和 ulong；而浮點數型別則有 float 和 double。

bool 型別可以表示布林值 (Boolean Value)：即 true 或 false。包含 bool 可以使得自我說明程式碼更容易撰寫，也可以減少開發人員在應該使用「==」時誤用「=」的常見 C++ 程式碼撰寫錯誤。在 C# 中，下面這個範例

int i = ...;
F(i);
if (i = 0)   // Bug: the test should be (i == 0)
   G();

會產生編譯時期錯誤，因為運算式 i = 0 的型別是 int，而 if 陳述式需要的應該是 bool 型別的運算式。

此 char 型別可以表示 Unicode 字元。一個 char 型別的變數可以代表單一 16 位元的 Unicode 字元。

decimal 型別很適合用在會因不接受浮點數表示方式而產生進位錯誤的計算過程中。常見範例包括金融計算作業，例如，稅務計算和匯率轉換。decimal 型別可以提供 28 位數的顯著數字。

下表列出預先定義型別，並說明每種型別的常值寫法。

型別 說明 範例
object
 所有其他型別的最終基底型別
object o = null;
string
 字串型別；字串是一組依序排列的 Unicode 字元
string s = "hello";
sbyte
 8 位元帶正負號的整數類資料型別
sbyte val = 12;
short
 16 位元帶正負號的整數類資料型別
short val = 12;
int
 32 位元帶正負號的整數類資料型別
int val = 12;
long
 64 位元帶正負號的整數類資料型別
long val1 = 12;
long val2 = 34L;
byte
 8 位元的不帶正負號的整數類資料型別
byte val1 = 12;
ushort
 16 位元的不帶正負號的整數類資料型別
ushort val1 = 12;
uint
 32 位元的不帶正負號的整數類資料型別
uint val1 = 12;
uint val2 = 34U;
ulong
 64 位元的不帶正負號的整數類資料型別
ulong val1 = 12;
ulong val2 = 34U;
ulong val3 = 56L;
ulong val4 = 78UL;
float
 單精度浮點數型別
float val = 1.23F;
double
 雙精度浮點數型別
double val1 = 1.23;
double val2 = 4.56D;
bool
 Boolean 型別；bool 值不是 true 就是 false
bool val1 = true;
bool val2 = false;
char
 字元型別；char 值即是 Unicode 字元
char val = 'h';
decimal
 包含 28 位顯著數字的精確 decimal 型別
decimal val = 1.23M;

每種預先定義型別都會根據系統提供的型別而進行簡寫。例如，int 關鍵字會參考到 System.Int32 結構。由於考量到形式，關鍵字會較完整的系統型別名稱來得常用。

例如 int 這種預先定義數值型別，在少數用途時會有特殊處理方式，但在其他多數情況下，仍是與其他結構一樣的處理方式。開發人員可以使用運算子多載，來定義和預先定義數值型別類似的新結構型別。舉例來說，Digit 結構可以像預先定義整數類資料型別一樣，支援相同的數學運算，也可以定義 Digit 和預先定義型別之間的轉換。

預先定義的型別會自己套用運算子多載。例如，比較運算子 == 和 != 對不同的預先定義型別會有不同的語意：

  • 兩個 int 型別的運算式在代表相同的整數值時，就視為相同的運算式。
  • 兩個 object 型別的運算式都參考相同物件 (或都是 null 時) ，就視為相同的運算式。
  • 兩個 string 型別的運算式在字串執行個體於每個字元位置上擁有相同長度和字元時 (或都是 null 時)，就視為相同的運算式。

下列範例

using System;
class Test
{
   static void Main() {
      string s = "Test";
      string t = string.Copy(s);
      Console.WriteLine(s == t);
      Console.WriteLine((object)s == (object)t);
   }
}

將會產生下列輸出

True
False

因為在第一次比較時，所比較的是兩個 string 型別的運算式，第二次比較時則是比較兩個 object 型別的運算式。


日期時間
System.DateTime currentTime=new System.DateTime();
1. 取得年月日時分秒：currentTime=System.DateTime.Now;
2 .取得年 ：int 年=currentTime.Year;
3. 取得月 ：int 月=currentTime.Month;
4 .取得日 ：int 日=currentTime.Day;
5. 取得時 ：int 時=currentTime.Hour;
6. 取得分 ：int 分=currentTime.Minute;
7. 取得秒 ：int 秒=currentTime.Second;
8. 取得毫秒 ：int 毫秒=currentTime.Millisecond;
9. 取中文日期顯示-年月日時分 ：
    string strY=currentTime.ToString("f");  //不顯示秒
10. 取中文日期顯示-年月：
    string strYM=currentTime.ToString("y");
11. 取中文日期顯示-月日：
    string strMD=currentTime.ToString("m");
12. 取得預設格式的年月日，格式為：2003-9-23
    string strYMD=currentTime.ToString("d");
13. 取得預設格式的時分，格式為：14：24
    string strT=currentTime.ToString("t");
（變數可用中文）


變數.ToString()
12345.ToString("n");  //產生 12,345.00
12345.ToString("C");
//產生 NT$12,345.00
12345.ToString("e");
//產生 1.234500e+004
12345.ToString("f4"); //產生 12345.0000
12345.ToString("x");
//產生 3039 (16進制)
12345.ToString("p");
//產生 1,234,500.00%


常數宣告
範例：
using System;
namespace DefaultNamespace
{
class
MainClass
{
const int
MAXSIZE=100;
public static void Main(string[]
args)
{
Console.WriteLine("{0}",MAXSIZE);
}
}
}
=====================================================
★const 和 enum 宣告的比較：
const int VER =
42;
const int BIG = 0x4d4d;
const int LIT = 0x4949;

enum Demo
{
  VER = 42,
  BIG = 0x4d4d,
  LIT = 0x4949
}
說明：
  const：必須定義在Class之內.
  enum ：可定義於Class之外部或內部.


變數.Length (取字串長度)
如：
string str="台灣";
int Len = str.Length ;  //Len宣告成整數， str是字串的變數名稱


變數類別
C# 定義了七種變數類別：
1.靜態變數
2.執行個體變數 (Insatance Variable
3.陣列元素
4.數值參數
5.參考參數
6.輸出參數
7.區域變數
下面這個範例
class A
{
 public static int x;
 int y;
 void F(int[] v, int a, ref int b, out int c)
 {
  int i = 1;
   c = a + b++;
 }
}

x 是靜態變數，y 是執行個體變數，v[0] 是陣列元素，a 是數值參數，b 是參考參數，c 是輸出參數，而 i 是區域變數。


資料型態轉換
在 C# 中 轉 換 Data Type 是 一 件 很 簡 單 的 事 情 。
因 為 可 以 用 Convert 這 一 個 class。

1.由 string 轉 去 int

string strNum = "12345";
int iNum = Convert.ToInt32(strNum);

--------------------------------------------------------------------
2.由 2 進 制 的 string 轉 去 int

string strNum = "1010";
int iNum = Convert.ToInt32(strNum, 2); //iNum will be 10 in decimal

ToInt32的 第 二 個 parameter 是 base， 可 以 是 2, 8, 10 或 16 進 制 。
--------------------------------------------------------------------

3.由 int 轉 去 string

int iNum = 10;
string strNum = Convert.ToString(iNum);
Console.WriteLine(strNum);

Convert class 提 供 了 很 多 Data Type 轉 換 的 Methods， 我 也 不 再 介 紹 了 。


運算子優先順序和順序關聯性
類別 | 運算子
主要 | x.y f(x) a[x] x++ x-- new typeof checked unchecked
一元 | + - ! ~ ++x --x (T)x
乘法類 | * / %
加法類 | + -
移位 | << >>
關係和型別測試 | < > <= >= is as
相等 | == !=
邏輯 AND | &
邏輯 XOR | ^
邏輯 OR | |
條件式 AND | &&
條件式 OR | ||
條件式 | ?:
設定 | = *= /= %= += -= <<= >>= &= ^= |=


基本算術運算
1.加號：+
2.減號：-
3.乘號：*
4.除號：/
5.餘數：%
6.除外，另一運算元-負號(-)。
上述六種運算符號的執行優先順序為：
一、高優先順序：負號(-)
二、中優先順序：乘號(*)、除號(/)、餘數(%)
三、低優先順序：加號(+)、減號(-)


型別的轉換
例如：
 a，b為整數
 原式：s=a/b;
 強制改成浮點數，如下：
  s=(float)a/(float)b;


特殊運算式
1.遞增：i++、++i
2.遞減：i--、--i
3.基本運算式 i=i+1; 改成特殊運算式 i+=1;
例如：

基本運算式 | 特殊運算式
i=i+j | i+=j
i=i-j | i-=j
i=i*j | i*=j
i=i/j | i/=j
i=i%j | i%=j


sizeof 運算子
sizeof：算出任何型別的資料，所佔用記憶體位置數量(以Byte為單元)
格式：
   sizeof(某個資料型態);
例如：
 若  n= sizeof(char) ,則結果： n=1
備註：
 1.sizeof 運算子只適用於數值型別，而不能用在參考型別。
 2.sizeof 運算子只能用於unsafe 模式。
 3.sizeof 運算子無法多載。
範例：
using System;
class
SizeClass
{
// 注意：unsafe宣告的方法
unsafe public static void SizesOf()
{
Console.WriteLine("The size of short is
{0}.", sizeof(short));
Console.WriteLine("The
size of int is {0}.", sizeof(int));
Console.WriteLine("The size of long is {0}.", sizeof(long));
}
}
class MainClass
{
public
static void Main()
{
SizeClass.SizesOf();
}
}
輸出：
The size of short is 2.
The size of int is 4.
The size of long is 8.


註解符號
除了 C# 語言的註解符號 /* */ 外，C#還有單行註解符號：兩個斜號 // ，
用來表示由 // 至到該行結尾的東西都是註解。


 關鍵字
關鍵字是與識別項相似的已保留字元序列，而且無法當成識別項來使用，除非在它前面加上 @ 字元。
關鍵字：下列其中之一
abstract | as | base | bool | break | byte | case
catch | char | checked | class | const | continue | decimal
default | delegate | do | double | else | enum | event
explicit | extern | false | finally | fixed | float | for
foreach | goto | if | implicit | in | int | interface
internal | is | lock | long | namespace | new | null
object | operator | out | override | params | private | protected
public | readonly | ref | return | sbyte | sealed | short
sizeof | stackalloc | static | string | struct | switch | this
throw | true | try | typeof | uint | ulong | unchecked
unsafe | ushort | using | virtual | void | volatile | while

在某些文法部分，特定識別項有特別用法，可是關鍵字並沒有這類情況。例如，在屬性宣告中，「get」和「set」識別項就有特別的用法 。因為 get 或 set 以外的識別項絕對不會用在這些地方，所以這種方式在將這些字當作識別項使用時，並不會產生任何衝突。


標準輸入： Read() -不換新行
範例：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
    int i;
    Console.WriteLine("輸入字串:");
    while ((i = Console.Read()) != -1)
      Console.WriteLine((char)i + ": " + i);
  }
 }
}
備註：
The Read() method reads the next character from the standard input stream and returns its American Standard Code

執行：

輸入字串:
az
a: 97
z: 122
: 13

: 10
請按任意鍵繼續 . . .

說明執行結果，所代表的意思：

a: 97, ..., z: 122

「Enter」按鍵: 13

新行: 10


標準輸入： ReadLine()
範例：
using System;

namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   double price;
   string inputString;
Console.Write("輸入價格: ");
inputString = Console.ReadLine();
price = double.Parse(inputString );
Console.Write("價格 = ");
Console.WriteLine("{0:C}",
price);
}
}
}

執行結果：
輸入價格: 20
價格 = NT$20.00
請按任意鍵繼續 . . .


標準輸出：Write() -不換新行
Console.Write("Hello ");
Console.WriteLine("World");

或

Console.WriteLine("Hello World");
Console.Write("\n");


標準輸出：WriteLine()
範例1:
Console.WriteLine("PGUI " + 2004);
範例2:
int year = 2004;
Console.WriteLine("PGUI " + year);
結果：PGUI 2004

範例3:
double x = 55.77;
Console.WriteLine("x = " + x);

結果：x = 55.77

範例4:
char c = 'x'; double d = 0.5;
Console.WriteLine(c + " = " + d);

結果：x = 0.5

範例5:
string s = "Hello World";
Console.WriteLine(s);

結果：Hello World

範例6:
int x = 2004; double y = 0.5;
Console.WriteLine("{0} {1}", x, y);

結果：2004 0.5

範例7:
double y = 7.5;
Console.WriteLine("{0, 10:C5}", y);

結果：NT$7.50000


字串常值逸出序列
逸出序列 | 說明
\t | 定位字元 (Unicode 0x0009)。
\r | 換行字元 (0x000d)。
\n | 新行字元 (換行符號) (0x000a)。
\v | 垂直索引標籤 (0x000b)。
\a | 警告 (0x0007)。
\b | 退格鍵 (0x0008)。
\f | 換頁字元 (0x000c)。
\0 | Null (0x0000)。
\\ | 反斜線 (0x005c)。
\' | 單引號 (0x0027)。
\" | 雙引號 (0x0022)。
\xD | 含可變位數的十六進位字元碼。
\uABCD | Unicode 字元 0xABCD (u 或 U 都可以，其中 A、B、C 和 D 是有效的十六進位數字 0-9、a-f、A-F)。


應用：取得鍵盤按鍵對應值
程式碼：
using System;
namespace
DefaultNamespace
{
class
MainClass
{

public static void
Main(string[] args)
{
int VirtualKey;
string
inputstring;
Console.WriteLine("輸入單一字元:
");
inputstring=Console.ReadLine();
VirtualKey=(int)inputstring[0];
Console.WriteLine("對應鍵值:
{0}={1}",inputstring
,VirtualKey);
}
}
}
結果：
輸入:
A
對應鍵值: A=65
請按任意鍵繼續 . . .


if 敘述 (範例：奇數與偶數判斷)
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int
number,rem;
string
inputstring;
Console.WriteLine("請輸入任意數：");
inputstring=Console.ReadLine();
number=int.Parse(inputstring);
rem=number %
2;
if(rem==1)
Console.WriteLine("{0}為奇數",number);
else
Console.WriteLine("{0}為偶數",number);
}
}
}


e1?e2:e3 特殊運算式
在if敘述中，常看到如下：
if(a>b)
  c=a;
else
  c=b;
類似 e1?e2:e3，如果e1為真，則執行e2，否則執行e3。
if的簡化寫法為：
 c=(a>b)?a:b;


switch 敘述
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int
i;
string
inputstring;
Console.WriteLine("
1.DOS...");
Console.WriteLine(" 2.Windows
XP...");
Console.WriteLine(" 3.Windows 2003
Server...");
Console.WriteLine("
輸入選項值(1-3)：");
inputstring=Console.ReadLine();
i=int.Parse(inputstring);
switch(i)
{
case
1:Console.WriteLine(" 結果=>已選擇 DOS");
break;
case 2:Console.WriteLine(" 結果=>已選擇 Windows
XP");
break;
case
3:Console.WriteLine(" 結果=>已選擇 Windows 2003
Server");
break;
default:Console.WriteLine("錯誤=>無此選項!\n");
break;
}
}
}
}
結果：
 1.DOS...
 2.Windows XP...
 3.Windows 2003 Server...
 輸入選項值(1-3)：
 2
 結果=>已選擇 Windows XP
請按任意鍵繼續 . . .


While 敘述(1) ( 範例：九九乘法)
using System;
namespace
DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int
i,j,result;
i=1;
while(i<=9)
{
j=1;
while(j<=9)
{
result=i*j;
Console.Write("{0}*{1}={2}\t",i,j++,result);
}
i++;
Console.Write("\n");
}
}

}
}
結果：
1*1=1   1*2=2   1*3=3   1*4=4   1*5=5   1*6=6   1*7=7   1*8=8   1*9=9
2*1=2   2*2=4   2*3=6   2*4=8   2*5=10  2*6=12  2*7=14  2*8=16  2*9=18
3*1=3   3*2=6   3*3=9   3*4=12  3*5=15  3*6=18  3*7=21  3*8=24  3*9=27
4*1=4   4*2=8   4*3=12  4*4=16  4*5=20  4*6=24  4*7=28  4*8=32  4*9=36
5*1=5   5*2=10  5*3=15  5*4=20  5*5=25  5*6=30  5*7=35  5*8=40  5*9=45
6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36  6*7=42  6*8=48  6*9=54
7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49  7*8=56  7*9=63
8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64  8*9=72
9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81
請按任意鍵繼續 . . .


for 敘述(1) ( 範例：九九乘法)
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int
i,j,result;
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
{
result=i*j;
Console.Write("{0}*{1}={2}\t",i,j,result);
}
Console.Write("\n");
}
}

}
}
結果：
1*1=1   1*2=2   1*3=3   1*4=4   1*5=5   1*6=6   1*7=7   1*8=8   1*9=9
2*1=2   2*2=4   2*3=6   2*4=8   2*5=10  2*6=12  2*7=14  2*8=16  2*9=18
3*1=3   3*2=6   3*3=9   3*4=12  3*5=15  3*6=18  3*7=21  3*8=24  3*9=27
4*1=4   4*2=8   4*3=12  4*4=16  4*5=20  4*6=24  4*7=28  4*8=32  4*9=36
5*1=5   5*2=10  5*3=15  5*4=20  5*5=25  5*6=30  5*7=35  5*8=40  5*9=45
6*1=6   6*2=12  6*3=18  6*4=24  6*5=30  6*6=36  6*7=42  6*8=48  6*9=54
7*1=7   7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49  7*8=56  7*9=63
8*1=8   8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64  8*9=72
9*1=9   9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81
請按任意鍵繼續 . .


do..While 敘述 (範例：1加到100)
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int
i,sum;
i=1;
sum=0;
do
{
sum+=i++;
}while(i<=100);
Console.WriteLine("1加到100，結果為{0}",sum);
}
}
}
結果:
1加到100，結果為5050
請按任意鍵繼續 . . .


for 敘述(2) ( 範例：列出65至90間所有ASCII字元)
範例1：(整數轉字元)
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   int i;
   for (i=65;i<=90;i++)
    Console.WriteLine("{0}= {1}",i,(char)i);
  }
 }
}
結果：
65= A
66= B
67=
C
68= D
69= E
70= F
71= G
72= H
73= I
74= J
75= K
76=
L
77= M
78= N
79= O
80= P
81= Q
82= R
83= S
84= T
85=
U
86= V
87= W
88= X
89= Y
90= Z
請按任意鍵繼續 . . .
範例2：(字元轉整數)
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int
i;
for
(i=65;i<=90;i++)
{
Console.WriteLine("{0}= {1}",(char)i,(int)(char)i);
}
}
}
}
結果：
A= 65
B= 66
C= 67
D=
68
E= 69
F= 70
G= 71
H= 72
I= 73
J= 74
K= 75
L= 76
M=
77
N= 78
O= 79
P= 80
Q= 81
R= 82
S= 83
T= 84
U= 85
V=
86
W= 87
X= 88
Y= 89
Z= 90
請按任意鍵繼續 . .
.


While 敘述(2) ( 範例：求最大公因數)
利用輾轉相除法，求最大公因數(gcd)
程式碼如下：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int
number1,number2,tmp;
string
inputstring;

Console.WriteLine("請輸入第一個數：");
inputstring=Console.ReadLine();
number1=int.Parse(inputstring);

Console.WriteLine("請輸入第二個數：");
inputstring=Console.ReadLine();
number2=int.Parse(inputstring);

while (number2 !=
0)
{
tmp=number1 %
number2;
number1 =
number2;
number2=tmp;
}
Console.WriteLine("最大公因數={0}",number1);
}
}
}
結果：
請輸入第一個數：
14
請輸入第二個數：
2
最大公因數=2
請按任意鍵繼續 . . .


For Each 敘述
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int[] arrInt =
{0,1,2,3};
foreach (int i in
arrInt)
{
Console.WriteLine("i= " +
i);
}
}
}
}
結果：
i= 0
i= 1
i= 2
i= 3
請按任意鍵繼續 . . .


for 敘述(3) (輸入數字，相反列印出來)
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int digit,num;
string
inputstring;
Console.WriteLine("輸入任意數：");
inputstring=Console.ReadLine();
num=int.Parse(inputstring);
Console.WriteLine("相反列印結果：");
while
(num
!=0)
{
digit=num%10;
num=num/10;
Console.Write("{0}",digit);
}
Console.WriteLine("\n");
}
}
}
結果：
輸入任意數：
1234567890
相反列印結果：
0987654321
請按任意鍵繼續 . . .


break敘述
break敘述 的用法有兩種：
1.在switch敘述中，扮演將case敘述中斷的角色。
2.強迫一般迴路指令(for、while、do-while)敘述中斷。
範例：
 for (i=0;i<=99;i++)
 {
    :
    :
    if (條件 1)
     break;
    :
 }
說明：
由上述，原則上for敘述將執行100圈，但是，如果條件1成立，
則不管敘述已經執行幾圈了，程式會立即離開這個迴圈敘述。


continue敘述
continue 和break的敘述類似，但是continue敘述是令迴路重新回到測試位置，而忽略continue和迴路終止之間的程式指令。
範例：
 for (i=0;i<=99;i++)
 {
    :
    :
    if (條件 1)
     continue;
    :
 }
說明：
由上述，原則上這個迴路將徹底執行所有迴路內指令100次，
但是如果條件1成立時，則迴路會忽略它和迴路中止點間的指令，
而回到測試位置。


goto敘述
1.goto敘述在執行時，後面加上一個標題(Label)。
2.標題是一個符號位址，告訴C#語言，直接跳到標題位置執行指令。
  當然程式中一定要有標題(Label)這個敘述，標題的寫法與變數一樣，
  但是後面結束要加上冒號(：)。
範例：
begin：
 ：
 ：
  if(i>j)
   goto stop;
  goto begin;
 ：
stop：
說明：

上述，如果i大於j，則跳到stop位址，否則跳到begin位址。
注意：
goto敘述：只限在同一程式段落內跳，不可跳到另一個函數或副程式內。


一維陣列(1) -基本操作
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[]
args)
{
int[] array = new int[10];
for( int i = 0; i < array.Length;
i++ )
{
array[i] =
i;
Console.WriteLine("{0}",array[i]);
}
}
}
}
結果：
0
1
2
3
4
5
6
7
8
9
請按任意鍵繼續 . . .


一維陣列(2)-泡泡排序法
範例：宣告一個整數陣列num，此陣列內含5個元素，分別是
           3,6,7,5,9
           int[] num=new int[5]{3,6,7,5,9};
     依小到大排序，並列出每執行一迴路後，排序結果。
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int i,j,tmp;
int[] num=new int[5]{3,6,7,5,9};
//陣列初始化
for(i=0;i<4;i++)
{
for (j=0;j<4;j++)
if
(num[j]>num[j+1])
{
tmp=
num[j];
num[j]=num[j+1];
num[j+1]=tmp;
}
Console.Write("第{0}迴路：\t",i);
for(j=0;j<5;j++)
Console.Write("{0}\t",num[j]);
Console.Write("\n");
}
}

}
}

結果：
第0迴路：       3       6       5       7       9
第1迴路：       3       5       6       7       9
第2迴路：       3       5       6       7       9
第3迴路：       3       5       6       7       9
請按任意鍵繼續 . . .
檢討：
上述排序法有一個缺點：
只排兩個迴路就完成排序工作，但是，仍然執行四次迴路。
下一節「一維陣列(3)-改良式泡泡排序法」，會使用一個旗號變數(flag)，
解決上述問題。


一維陣列(3)-改良式泡泡排序法
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int i,j,tmp;
int[] num=new
int[5]{3,6,7,5,9};
bool
flag;
for(i=0;i<4;i++)
{
flag=true;
for
(j=0;j<4;j++)
if
(num[j]>num[j+1])
{
tmp=
num[j];
num[j]=num[j+1];
num[j+1]=tmp;
flag=false;
}
if(flag)
break;
Console.Write("第{0}迴路：\t",i);
for(j=0;j<5;j++)
Console.Write("{0}\t",num[j]);
Console.Write("\n");
}
}

}
}

結果：
第0迴路：       3       6       5       7       9
第1迴路：       3       5       6       7       9
請按任意鍵繼續 . . .


二維陣列(1)-基本操作
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int[,] num=new
int[3,3];
int
i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
num[i,j]=i+j;
Console.Write(" {0}
",num[i,j]);
}
Console.Write("\n");
}
}

}
}
結果：
 0  1  2
 1  2  3
 2  3  4
請按任意鍵繼續 . . .


二維陣列(2)-陣列初始化
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main(string[] args)
{
int[,] num=new
int[3,3]{{1,2,3},
{1,2,3},
{1,2,3}};
int
i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
Console.Write(" {0}
",num[i,j]);
}
Console.Write("\n");
}
}

}
}
結果：
 1  2  3
 1  2  3
 1  2  3
請按任意鍵繼續 . . .


資料型態(Data Type)
Inherits from System.Array

Note on Resize

Use Clone(), Copy(), CopyTo() methods to keep the old data.

資料型態(Data Type)

// define
int[] int1 = new int[5];    // 0 to 4, 5 items
// int[5] int2;    // syntax error

// define without initial size
int[] int2;
int2 = new int[5];

// define and initialize
int[] int32 = new int[] {0, 1, 2, 3, 4};
int[] int33 = {0, 1, 2, 3, 4};

// define and assign value later
int[] int4;
int4 = new int[] {0, 1, 2, 3, 4};

// resize
int[] int5 = new int[5];
int5 = new int[9];  // old data is lost

// rectangular array, the second dimension is always the same
int[,] int6 = new int[5, 3];
int[,] int7;
int7 = new int[5, 3];

// jagged array, the second dimension varies
int[][] int8;
int8 = new int[5][];
int8[0] = new int[3];
int8[1] = new int[4];
Debug.WriteLine(int8.Length.ToString());    // 6
Debug.WriteLine(int8[0].Length.ToString()); // 4
// Debug.WriteLine(int8[2].Length.ToString()); // run-time error

// sample
Char[] splitArray = new Char[] {';'};


物件型態(Reference Type)
// define
object[] obj1 = new object[5];    // 0 to 4, 5 items
// object[5] obj2;    // syntax error

// define without initial size
object[] obj2;
obj2 = new object[5];

// define and initialize
object[] obj32 = new object[] {new object(),
                                  new object(), new object(),
                                  new object(), new object()};
object[] obj33 = {new object(),
                     new object(), new object(),
                     new object(), new object()};

// define and assign value later
object[] obj4;
obj4 = new object[] {new object(),
                        new object(), new object(),
                        new object(), new object()};

// resize
object[] obj5 = new object[5];
obj5 = new object[9];  // old data is lost

// rectangular array, the second dimension is always the same
object[,] obj6 = new object[5, 3];
object[,] obj7;
obj7 = new object[5, 3];

// jagged array, the second dimension varies
object[][] obj8;
obj8 = new object[5][];
obj8[0] = new object[3];
obj8[1] = new object[4];
Debug.WriteLine(obj8.Length.ToString());    // 6
Debug.WriteLine(obj8[0].Length.ToString()); // 4
// Debug.WriteLine(obj8[2].Length.ToString()); // run-time error

// sample
DataTable table1 = new DataTable();
DataColumn column1 = new DataColumn("RowId");
table1.Columns.Add(column1);
table1.PrimaryKey = new DataColumn[] {table1.Columns["RowId"]};


使用指標注意事項
使用指標注意事項：
1.指標在C#語言中，屬於 unsafe類的程式碼，
   所以在編譯時，請至專案選項中設定為true。
2.設定方式：
   專案選單->專案選項->Debug或Release->程式碼項目
   ->允許非安全程式碼->設為true
3.再執行程式碼編譯，即可。
備註：
 1.未設定時，編譯視窗會出現提示訊息：
   「程式中若有 unsafe 程式碼，編譯時必須使用 /unsafe 選項」
 2.C# 建議少用此非安全性程式碼。
範例：
using System;
class
MyClass  //類別
{
public unsafe void Method()
{
int x =
10;
int y = 20;
int *ptr1 =
&x;
int *ptr2 =
&y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
}

class
MyClient         //主程式
{
public static void
Main()
{
MyClass mc = new
MyClass();
mc.Method();
}
}
結果：
1242764
1242760
10
20
請按任意鍵繼續 . . .


指標-基本操作
程式碼：
using System;
namespace DefaultNamespace
{
class democlass
{
public unsafe void Getptr()
{
int i=20;
int
*ptr=&i;
Console.WriteLine("取得指標位址：{0}",(int)ptr);
Console.WriteLine("取得指標結果：{0}",*ptr);
}

}

class
MainClass
{
public static void
Main(string[] args)
{
democlass runptr=new
democlass();
runptr.Getptr();
}
}
}
結果：
取得指標位址：1242760
取得指標結果：20
請按任意鍵繼續 . . .


函數指標的進化論 (上)

作者：蔡學鏞

2003 年 10 月

摘要

函數指標 (function pointer) 是傳統 C 語言中少數的動態機制，但是近來許多語言都不再支援函數指標 (包括 Java 和 C#)，而改用其他機制來代替。本文章簡單扼要地說明，多型 (polymorphism)、反映 (reflection)、委託 (delegate) 如何取代函數指標。

函數指標 (function pointer) 是一種「指向函數的指標」，和一般指向資料的指標不同。凡是研究過許多系統原始碼 (例如：Linux Kernel、Borland OWL) 的人，對於函數指標應該都不陌生，因滛多數低階系統都使用 C 語言撰寫，而函數指標是傳統C語言中少數的動態機制，有許多不可取代的地方，所以這些 C 原始碼中到處可見函數指標。

透過一個實際的範例，來瞭解何謂函數指標：

// FncPtr.cpp
#include
using std::cin;
using std::cout;
using std::endl;

// 聲明 Fnc1(), Fun2(), Twice()
float Fnc1(int);
float Fnc2(int);
double Twice(float (*)(int), int);

// 主程式
int main() {
  int A = 3;
  int B = 5;
  count << "Twice(Fnc1, A)的值為: "
            << Twice(Fnc1, A) << endl;
  count << "Twice(Fnc2, B)的值為: "
            << Twice(Fnc2, B) << endl;
}

float Fnc1(int N) {
  return float (N*N);
}

float Fnc2(int N) {
  return float (N*N*N);
}

double Twice(float (*pF)(int), int N) {
  return 2.0 * double(pF(N));
}

執行結果：

Twice(Fnc1, A)的值為：18
Twice(Fnc2, B)的值為：250

此例中，pF 即為函數指標，而函數名稱本身 (Fun1 與 Fun2) 是常數的函數指標。通過函數指標，函數被資料化了 (變成指標)，如此一來函數也可以被傳遞、被紀錄，所以 Fnc1 與 Fnc2 可以被當成參數，傳進 Twice() 中。

一旦函數可以被傳遞、被紀錄，這開�坐F許多可能性，𠖳生許多有趣的應用，特別是下列三者：

  • 多型 (polymorphism)：稍後再說明。
  • 多緒 (multithreading)：將函數指標傳進負責建立多緒的 API 中：例如 Win32 的 CreateThread(...pF...)。
  • 回呼 (call-back)：所謂的回呼機制就是：「當發生某事件時，自動呼叫某段程式碼」，Charles Petzold 稱此滛「Don’t Call Me, I'll Call You」。事件驅動 (event-driven) 的系統經常透過函數指標來實現回呼機制，例如 Win32 的 WinProc 其實就是一種回呼，用來處理視窗的訊息。

函數指標的致命缺點是：無法對參數 (parameter) 和返回值 (return value) 的型態進行檢查，因為函數已經退化成指標，指標是不帶有這些型態資訊的。少了型態檢查，當參數或返回值不一致時，會造成嚴重的錯誤。編譯器和虛擬機器 (VM) 並不會幫我們找出函數指標這樣的致命錯誤。所以，許多新的程式語言不支援函數指標，而改用其他方式。

多型

多型的實現方式很複雜，大致上是編譯器或 VM 在資料結構內加入一個資料指標，此指標通常稱滛 vptr，是 Virtual Table Pointer 的意思。vptr 指向一個 Virtual Table，此 Virtual Table 是一個陣列 (array)，由許多函數指標所組成，每個函數指標各自指向一個函數的地址。如圖 1 所示。

圖 1
圖 1

不管是 C++ 編譯器、或是 Java VM、或是 .NET CLR，內部都是以此方式來實現多型。儘管如此，這只能算是 black magic，對於 C++、Java 與 .NET 語言來說，函數指標「並未因此」和語言本身有直接相關。換句話說，C++ 和 Java 與 .NET 語言，就算語法本身不支援函數指標，照樣也能實現多型。事實上，C++ 固然支援函數指標，但不是滛了多型的關係，而是滛了和 C 相容 (畢竟 C++ 是 C 的 superset)；IL Asm (.NET 上的組合語言) 固然支援函數指標，但由於安全的理由，使用上受到相當大的限制，且不是滛了多型的關係。至於 Java 與 C# 則都不支援函數指標。

沒錯，Java 與 C# 都不支援函數指標。雖然剛剛解釋過，這不會影響對於多型的支援，但是這會不會影響對於多緒 (multithreading) 與回呼 (call-back) 機制的支援呢？答案是：不會！因為 Java 可以利用多型或反映 (reflection) 來實現多緒與回呼，而 C#可 以利用多型或反映或委託 (delegate) 來實現多緒與回呼。

反映

顧名思義，反映 (reflection) 機制就像是在吳承恩所著的西遊記中所提及的「照妖鏡」，可以讓類別或物件 (object) 在執行時期「現出原形」。我們可以利用反映機制來深入瞭解某類別 (class) 的建構子 (constructor)、方法 (method)、欄位 (field)，甚至可以改變欄位的值、呼叫方法、建立新的物件。有了反映機制，程式員即使對所欲使用的類別所知不多，也能照樣寫程式。反映機制能夠用來呼叫方法，這正是反映機制能夠取代函數指標的原因。

以 Java 來說，java.lang.reflect.Method (以下簡稱 Method) 類別是用來表示某類別的某方法。我們可以透過 java.lang.Class (以下簡稱 Class) 類別的許多方法來取得 Method 物件。Method 類別提供 invoke() 方法，透過 invoke()，此 Method 物件所表示的方法可以被呼叫，所有的參數則是被組織成一個陣列，以方便傳入 invoke()。

舉個例子，下面是一個名為 Invoke 的程式，它會將命令列的 Java 類別名稱和要呼叫的方法名稱作為參數。為了簡單起見，我假定此方法是靜態的，且沒有參數：

import java.lang.reflect.*;

class Invoke {
    public static void main(String[] args ) {
        try {
            Class c = Class.forName( args[0] );
            Method m = c.getMethod( args[1], new Class [] { } );
            Object ret = m.invoke( null, null );
            System.out.println(args[0] + "." + args[1] +"() = " + ret );
        } catch ( ClassNotFoundException ex ) {
            System.out.println("找不到此類別");
        } catch (NoSuchMethodException ex ) {
            System.out.println("此方法不存在");
        } catch (IllegalAccessException ex ) {
            System.out.println("沒有權限調用此方法");
        } catch (InvocationTargetException ex ) {
            System.out.println("調用此方法時發生下列例外:\n" +
                ex.getTargetException() );
        }
    }
}

我們可以執行 Invoke 來取得系統的時間：

java Invoke java.lang.System CurrentTimeMillis

執行的結果如下所示：

java.lang.System.currentTimeMillis() = 1049551169474

我們的第一步就是用名稱去尋找指定的 Class。我們用類別名稱 (命令列的第一個參數) 去呼叫 forName() 方法，然後用方法名稱 (命令列的第二個參數) 去取得方法。getMethod() 方法有兩個參數：第一個是方法名稱 (命令列的第二個參數)，第二個是 Class 物件的陣列，這個陣例指明了方法的 signature (任何方法都可能會被多載，所以必須指定 signature 來分辨。) 因為我們的簡單程式只呼叫沒有參數的方法，我們建立一個 Class 物件的匿名空陣列。如果我們想要呼叫有參數的方法，我們可以傳遞一個類別陣列，陣列的內容是各個類別的型態，依順序排列。

一旦我們有了 Method 物件，就呼叫它的 invoke() 方法，這會造成我們的目標方法被調用，並且將結果以 Object 物件傳回。如果要對此物件做其他額外的事，你必須將它轉型為更精確的型態。

invoke() 方法的第一個參數就是我們想要呼叫目標方法的物件，如果該方法是靜態的，就沒有物件，所以我們把第一個參數設為
null，這就是我們範例中的情形。第二個參數是要傳給目標方法作為參數的物件陣列，它們的型態要符合呼叫 getMethod()
方法中所指定的型態。因為我們呼叫的方法沒有參數，所以我們傳遞 null 作為 invoke() 的第二個參數。

以上是 Java 的例子，事實上，.NET 的反映機制也相去不遠，不再贅述。反映機制是最動態的機制，比多型的功能更強大。然而，反映的速度比多型慢許多 (而且多型又比函數指標稍慢)，所以若非必要，應該少用反映機制。事實上，不管是 Java API 或 .NET Framework，都不使用反映機制來實現回呼與多緒。

Java 的多緒

Java沒有函數指標(為了系統安全)，也不用反映機制來處理多緒(一方面為了效率，二方面反映機制是在JDK1.1才開始支援)，而是使用多型的機制來處理多緒，作法如下：(另一種作法是實作java.lang.Runnable介面，與下面的作法雷同，不另說明。)

將執行緒的程式寫在下面的run()方法中：

class MyThread extends java.lang.Thread {
    public void run() {
        // ...
    }
}

再利用下面的方式來啟動此執行緒：

MyThread thread = new MyThread();
thread.start();

start() 方法定義在 java.lang.Thread 類別內，start() 方法會請作業系統建立一個執行緒，再呼叫 run()，此時調用的並非在 java.lang.Thread 內定義的 run() (它是空的)，而是利用多型機制，調用到 MyThread 內定義的 run()。

Java的回呼

通常回呼機制都是使用 publisher/subscriber (出版者/訂閱者) 的方式，必須先向系統註冊：

  • 何事件：我對何種事件感興趣
  • 何函數：當事件發生時，請呼叫我的函數，以滛通知。此函數即滛回呼函數 (call-back function)。

Java 也是使用類似的作法，差別在於 Java 無法利用函式指標，且採用物件導向的作法。Java 將出版者 (publisher) 稱滛事件來源 (event source)，將訂閱者 (subscriber) 稱滛事件傾聽者 (event listener)。大致的作法如下：

  • 向事件來源註冊 (registry) 事件傾聽者
  • 該事件發生時，事件來源通知 (notify) 事件傾聽者

事件來源提供名滛 addXxxListener() 的方法來讓事件傾聽者註冊之用，此方法需要傳入事件傾聽者當參數。至於是何種事件，則由 Xxx 以滛識別。例如：addMouseListener() 表示註冊「滑鼠事件」的事件傾聽者。

利用 addXxxListener()，事件來源就可以將事件傾聽者記錄在欄位 (field) 中。當事件發生時，事件來源就可以從欄位中知道該通知和物件。可是應該呼叫該物件的那個方法呢？如果該物件沒有提供該方法呢？

想要解決此問題，事件來源就必須過濾註冊的對象，addXxxListener() 所需要的參數不可以是籠統的
java.lang.Object，而必須是一個實作 XxxListener 介面 (interface) 的物件。只要在
XxxListener 介面內宣告一個比方說 XxxEventHappened()，那樌任何實作
XxxListener 的物件，都必定有實現 XxxEventHappened()，所以事件來源就可以在事件發生時，呼叫事件傾聽者的
XxxEventHappened()。這正是依靠多型機制才能達成。

事件來源通知事件傾聽者時，往往需要夾帶一些額外的訊息，例如：事件來源是誰、事件發生於何時、事件發生的原因為何…。這些訊息被封裝成事件物件，當作參數傳給 XxxEventHappened()。

Java AWT/Swing 規定，所有的事件都必須繼承自 java.util.EventObject 類別；所有的事件傾聽者都必須實現 java.util.EventListener 介面。圖二是 Java AWT 的事件繼承階層圖：

圖 2
圖 2

例如，我要向一個名為 jButton1 的 javax.swing.JButton 物件註冊，成為它的事件傾聽者，那麼就必須實作 java.awt.event.ActionListener 介面，提供 actionPerformed() 方法，如下所示：

class MyActionListener implements ActionListener {
  public void actionPerformed(ActionEvent evt) {
    // ...
  }
}

註冊的方式如下：

MyActionListener mal = new MyActionListener();
jButton1.addActionListener(mal);

使用多型的機制來實現多緒和回呼，不但麻煩 (必須繼承)，也不能使用靜態方法，因為靜態方法本來就沒有多型的機制 (static 一定是 non-virtual)。順便一提，前面所提到的反映機制，可以支援靜態方法 (static method)。

未完待續 ...

此文章分成兩篇。在本篇中，你可以瞭解 Java 如何利用多型的機制來取代函數指標，在下篇中，你將會體驗到，.NET 是如何利用 delegate 來徹底地取代函數指針，以提供比 Java 更好的解決方式。


函數指標的進化論（下）

作者：蔡學鏞

2003 年 11 月

Delegate

C# 也支援多型與反射，但是 C# 卻是使用 delegate 來實現多緒和回呼 (而不使用多型與反射)。delegate 是函數指標的改良品種。delegate 的效率應該比多型稍差，但是用起來更方便，且允許使用靜態方法。

C# 編譯器對 delegate 以及 event 提供了大量的語法甜頭 (syntactic sugar)，這些語法甜頭並不符合一般觀念中的程式語法，所以往往讓許多初學者丈二金剛摸不著頭腦。後面會陸續揭露 C# 編譯器的這些內幕。

C# 不支援函數指標，所以不能使用下面的語法：

void (*pFnc)(int, double);

必須改用下面的語法來宣告 delegate：

delegate void MyDelegate(int p1, double p2);

而上面的語法，等於下面的效果：

//版本一
class MyDelegate : System.MulticastDelegate {
  public MyDelegate(Object target, System.IntPtr)
  { ... }
  public void virtual Invoke(int p1, double p2)
  { ... }
  public virtual IasyncResult BeginInvoke(...)
  { ... }
  public virtual void EndInvoke(...)
  { ... }
}

其實，也可以是：

//版本二
class MyDelegate : System.MulticastDelegate {
  public MyDelegate(Object target, System.IntPtr)
  { ... } // IntPtr 和 pointer 無關，是 native int 的意思
  public void virtual Invoke(int p1, double p2)
  { ... }
}

為了簡單起見，我們只討論版本二。請注意，不管版本一與版本二，都無法編譯成功，因為 C# 語言規定：只有 C# 編譯器可以直接製造出繼承自 MulticastDelegate 的類別，編程員不可以在 C# 原始碼中定義 MulticastDelegate 的衍生類別。換句話說，這樣的語法甜頭是強制的，非用不可，別無選擇。

補充說明，MulticastDelegate 繼承自 Delegate。微軟原本的意思是讓 Delegate 的衍生類別只能包裝一個方法，MulticastDelegate 的衍生類別可以包裝多個方法。但是後來發現這樣的設計有相當多缺點，所以乾脆讓所有的 delegate 都繼承自 MulticastDelegate。由於這樣重大的設計變更來得太晚，所以微軟不敢全面調整 .NET Framework，怕會因此出現 bug，所以沒有更動原先的程式庫，只有更動編譯器和文件。讀者可能會認為，為何不用 .NET 特有的 side-by-side execution 方式 (用來解決 DLL Hell)，同時執行兩個不同版本的 dll？我認為，問題之一出在 MulticastDelegate 與 Delegate 是屬於 mscorlib.dll，這是絕對不能使用 side-by-side execution 的 dll。目前 (1.0 與 1.1) 雖然 MulticastDelegate 與 Delegate 都還存在，但是在未來的 .NET 版本可就難說了。

編譯器幫我們產生的建構子需要兩個參數，第一個是方法所屬的物件，第二個是方法在「Method」metadata table 中的位置。編程員當然不會知道這個位置是幾號 (但是編譯器知道)，所以編程員無法直接使用此建構子。事實上，產生 delegate 對象的過程中充滿離奇，有許多語法甜頭，下面會一一解釋。

你可以用下面的方式，來產生一個非靜態方法的 delegate：

new MyDelegate(myObject.MyNonStaticMethod);

編譯器會自動調用 MyDelegate 建構子，第一個參數是 myObject，第二個參數是 MyNonStaticMethod 方法在「Method」metadata table中的位置。

你也可以用下面的方式，來產生一個靜態方法的 delegate：

new MyDelegate(MyClass.MyStaticMethod);

編譯器會自動調用 MyDelegate 建構子，第一個參數是 null，第二個參數是 MyStaticMethod 方法在 「Method」metadata table中的位置。

注意：不管是不是 static 方法，都必須符合 MyDelegate 的 signature (參數和返回值的型態)，否則編譯會失敗。

下面有更怪的例子：

MyDelegate md = null;
md += new MyDelegate(MyClass.MyStaticMethod);

第一次看到這樣的程式碼，許多人都會嚇了一跳：md 是 null，怎麼可以使用 +=？這會不會導致 System.NullReferenceException？事實上，這樣的寫法，編譯之後會變成：

MyDelegate md = null;
md = System.Delegate.Combine(md, new MyDelegate(MyClass.MyStaticMethod));

Combine() 是 System.Delegate 所提供的靜態方法，目的在於將第二個 Delegate 結合到第一個 Delegate 中，傳回此一新的 Delegate；如果第一個 Delegate 為 null，則直接傳回第二個 Delegate。

類似地，下面的程式：

md -= new MyDelegate(MyClass.MyStaticMethod);

編譯之後會變成：

md = System.Delegate.Remove(md, new MyDelegate(MyClass.MyStaticMethod));

Remove() 是 System.Delegate 所提供的靜態方法，目的在於將第二個 Delegate 自第一個 Delegate 中移除，並傳回此一新的 Delegate。

稍早提到下面的定義：

delegate void MyDelegate(int p1, double p2);

會造成編譯器會自動產生下面的定義。

class MyDelegate : System.MulticastDelegate {
  public MyDelegate(Object target, System.IntPtr)
  { ... } // IntPtr 和 pointer 無關，是 native int 的意思
  public void virtual Invoke(int p1, double p2)
  { ... }
}

現在我們把焦點集中在 Invoke() 上，此方法的參數和返回值型態一定會和 delegate 相同，以此例來說，方法參數必須是 int，double，而傳出值必須是 void。

如何調用 delegate？相當簡單，請看下面的例子：

MyDelegate d = new MyDelegate(MyClass.MyStaticMethod);
d(1, 3.4);

delegate 其實還有許多有趣的主題，包括 System.Reflection.RuntimeMethodInfo 類別做了哪些事 (這個類別是 Undocumented，.NET 1.0 文件中沒有說明)、多個 delegate 如何串接、delegate 如何和反映機制合作......等，因為篇幅有限，我都不在本文章說明，請感興趣的讀者自行研究這些主題。

C# 的多緒

傳統的多緒使用函數指標當參數，C# 利用 delegate 來取代函數指標，所以當然也將 delegate 用在多緒上。下面是一個 C# 多緒的例子：

using System;
using System.Threading;

class SimpleThreadApp {
  public static void WorkerThreadMethod() {
    // ...
  }
  public static void Main() {
    ThreadStart woker = new ThreadStart(WorkerThreadMethod);
    Thread t = new Thread(worker);
    t.start();
  }
}

ThreadStart 是一個 delegate，由 System.Threading 所提供。這個程式應該不難理解，所以我不再解釋。

C# 的回呼

對於 C# 來說，事件來源可以使用下面的方式來定義：

public class YourButton {
  public YourDelegate Click;
  // ...
}

這麼一來，外面的程式如果想要註冊，用法如下：

yourButton.Click += new YourDelegate(MyClass.MyStaticMethod);

在 YourButton 類別定義「內」，如果想通知所有的事件傾聽者，只要用下面的程式碼即可：

Click();

糟糕的是，連在 YourButton 類別定義「外」，也可以使用下面的方式，來產生通知，這樣子會違反物件導向的封裝精神。

yourButton.Click();

所以顯然我們應該將 YourButton 內的 Click 由 public 改成 private：

public class YourButton {
  private YourDelegate Click;
  // ...
}

但是這樣卻造成外面的程式無法向 YourButton 註冊，所以我們再將程式改成下面的模樣：

//作法一
public class YourButton {
  private YourDelegate Click;
  public void add_Click(YourDelegate d) {
    Click += d;
  }
  public void remove_Click(YourDelegate d) {
    Click -= d;
  }
  // ...
}

幾乎大家都有這樣的需求，所以 C# 編譯器於是又提供了一個語法甜頭 (利用 event 關鍵字)，只要寫出下面 (作法二) 的程式，編譯之後的結果就和上面 (作法一) 一樣：

//作法二
public class YourButton {
  public event YourDelegate Click;
  // ...
}

或者你想要自行提供 add 和 remove 內的程式碼也成 (可能是為了提供 side-effect 程式碼)，如下所示 (有點類似 property 的語法)：

//作法三
public class YourButton {
  private YourDelegate _Click;
  public event YourDelegate Click {
    add {
      // .. side-effect code here, if any
      Click += value;
      // .. side-effect code here, if any
    }
    remove {
      // .. side-effect code here, if any
      Click -= value;
      // .. side-effect code here, if any
    }
  }
  // ...
}

為何用作法三，不用作法一，因為作法三有使用 event 關鍵字，只要有使用 event 關鍵字 (包括作法二)，就會使得編譯器將它記錄在「Event」Metadata Table 內。有沒有紀錄這個對於執行時的毫無影響，但是可以幫助編譯器等工具軟件判讀，來簡化原始碼。例如，使用作法一，無法用下面的方式來註冊以及取消註冊。

yourButton.Click += new YourDelegate(MyClass.MyStaticMethod);
yourButton.Click -= new YourDelegate(MyClass.MyStaticMethod);

但是，使用作法二和三，則可以用這種方式來註冊以及取消註冊。因為編譯器從「Event」Metadata Table 內發現 Click 是 event，所以只要程式中使用 +=，則自動編譯成 add_Click()；使用 -=，則自動編譯成 remove_Click()。

結論

函數指標、多型、反映、delegate，彼此之間互有關連，也各有優缺點。從函數指標演化到 delegate 的這段過程中，我對於這些機制設計者的巧思益發感到敬佩。


委派簡介(Delegate)
委派 (Delegate) 具有其他語言 (例如 C++、Pascal 和 Modula) 提出的函式指標的案例之能力。不同於 C++ 函式指標，委派是完全物件導向；而且不同於 C ++ 成員函式指標，委派會封裝物件執行個體和方法兩者。
委派宣告可以定義衍生自 System.Delegate 類別的類別。委派執行個體會封裝引動過程清單，其中包含一個或多個方法，每一個都稱為可呼叫實體。如果是執行個體方法，可呼叫實體便會由一個執行個體和該執行個體的方法組成。如果是靜態方法，可呼叫實體就只會包含方法。利用適當的引數集合叫用委派執行個體，會導致每個委派的可呼叫實體都以指定的引數集合叫用。
委派執行個體有一個既有趣又有用的特性，就是它根本不知道也不在乎，它究竟封裝了哪種方法的類別；其所在意的事，是那些方法是否相容於委派的型別。這樣一來，會使得委派更適合「匿名的」引動過程。


委派講解(1) -委派如何運作

在大部分情況中，我們在呼叫函式時，都會直接指定要呼叫的函式。如果 MyClass 類別擁有一個叫做 Process 的函式，我們通常會以下列方式呼叫它：

MyClass myClass = new MyClass();
myClass.Process();

這在大部分情況下都行得通。不過，有時候我們不想直接呼叫函式—而希望能夠將它傳遞給別人，供他們呼叫。這在事件驅動系統中尤其有用，例如在圖形使用者介面中，我希望某些程式碼在使用者按一下按鈕時被執行、或者我要記錄某些資訊，但是卻無法指定如何記錄它時。

請參考下列範例：

public class MyClass
{
   public void Process()
   {
      Console.WriteLine("Process() begin");
      // other stuff here?
      Console.WriteLine("Process() end");
   }
}

在這個類別中，我們正在做一些記錄，以便知道函式何時開始和結束。不幸的是，我們的記錄只能硬接到主控台，而這可能並不是我們要的。我們真正想要的是，有辦法控制資訊要從函式外的哪裡記錄，而不必讓函式程式碼變得更複雜。

委派正好適合這個用途，它可以讓我們指定要呼叫的函式的模樣，而不必指定要呼叫哪一個函式。委派的宣告看起來就像是函式的宣告，只不過在這個案例中，我們宣告的是這個委派可以參考的函式的簽名碼 (Signature)。

就我們的範例來說，我們要宣告接受單一字串參數而且沒有傳回型別的委派。我們的類別修改如下：

public class MyClass
{
   public delegate void LogHandler(string message);
   public void Process(LogHandler logHandler)
   {
      if (logHandler != null)
         logHandler("Process() begin");
      // other stuff here?
      if (logHandler != null)
         logHandler ("Process() end");
   }
}

使用委派就像直接呼叫函式一樣，不過，在呼叫函式之前，我們需要加上一項檢查，看看委派是否為 Null (也就是說，沒有指向函式)。

如果要呼叫 Process() 函式，我們需要宣告與委派相符的記錄函式，再建立指向函式的委派的執行個體。然後這個委派會被傳遞給 Process() 函式。

class Test
{
   static void Logger(string s)

   {
      Console.WriteLine(s);
   }

   public static void Main()
   {
      MyClass myClass = new MyClass();

      MyClass.LogHandler lh = new MyClass.LogHandler(Logger);

      myClass.Process(lh);
   }
}

Logger() 函式就是我們想要從 Process()
函式呼叫的函式，而且它會被宣告以便符合委派。我們在 Main()
中建立委派的執行個體，並將委派建構函式傳遞給我們要建構函式指向的這個函式。最後將委派傳遞給 Process() 函式，才能夠呼叫
Logger() 函式。

如果您是 C++ 的使用者，可能會認為委派很像函式指標，您的想法算是很正確。不過，委派不只是函式指標而已，它還提供其他功能。

傳遞狀態

在上面的簡單範例中，Logger() 函式只有寫出字串。不同的函式可能會想將資訊記錄到檔案中，不過，要這樣做，函式必要知道要將資訊寫入那個檔案。

於 Win32𦲷 中，在傳遞函式指標時，您可以將狀態一起傳遞出去。不過，在 C# 中就沒有必要這樣做，因為委派可以參考靜態或成員函式。底下是如何參考成員函式的範例：

class FileLogger
{
   FileStream fileStream;
   StreamWriter streamWriter;

   public FileLogger(string filename)
   {
      fileStream = new FileStream(filename, FileMode.Create);
      streamWriter = new StreamWriter(fileStream);
   }

   public void Logger(string s)
   {
      streamWriter.WriteLine(s);
   }

   public void Close()
   {
      streamWriter.Close();
      fileStream.Close();
   }
}
class Test
{
   public static void Main()
   {
      FileLogger fl = new FileLogger("process.log");

      MyClass myClass = new MyClass();

      MyClass.LogHandler lh = new MyClass.LogHandler(fl.Logger);

      myClass.Process(lh);
      fl.Close();
   }
}

FileLogger 類別只會封裝檔案。修改 Main() 才能讓委派指向
FileLogger 的 fl 執行個體上的 Logger() 函式。在從
Process() 叫用這個委派時，就會呼叫成員函式，並將字串記錄到適當的檔案中。

酷的是我們不必變更 Process() 函式；不論是否參考靜態或成員函式，所有委派的程式碼都是一樣的。

多點傳送

能夠指向成員函式固然好，但是用委派做的還不止於此。在 C# 中，委派是多點傳送的，這表示它們可以同時指向一個以上的函式 (也就是說，它們不以 System.MulticastDelegate 型別為基礎)。多點傳送委派有一份函式清單，當委派被叫用時，清單中的所有函式也都會被呼叫。我們可以在第一個範例的記錄函式中加回去，並呼叫兩個委派。為了合併兩個委派，我們要使用 Delegate.Combine() 函式。程式碼如下所示：

      MyClass.LogHandler lh = (MyClass.LogHandler)
         Delegate.Combine(new Delegate[]
            {new MyClass.LogHandler(Logger),
            new MyClass.LogHandler(fl.Logger)});

哇，真是難看！與其強迫使用者接受這個語法，不如由 C# 提供更好的語法。您可以不要呼叫 Delegate.Combine()，而只要用 += 將兩個委派合併起來即可：

      MyClass.LogHandler lh = null;
      lh += new MyClass.LogHandler(Logger);
      lh += new MyClass.LogHandler(fl.Logger);

這樣就清爽多了。如果要將委派從多點傳送委派中移除，可以呼叫 Delegate.Remove()，或者使用 -= 運算子 (我知道我會用哪一個)。

呼叫多點傳送委派時，叫用清單中的委派會依它們出現的順序被同步呼叫。如果處理序期間發生錯誤，執行處理序會中斷。

如果想更密切的控制叫用順序—例如，如果您想要有保證的叫用—可以從委派取得叫用清單，並自行叫用函式。方法如下所示：

foreach (LogHandler logHandler in lh.GetInvocationList())
{
   try
   {
      logHandler(message);
   }
   catch (Exception e)
   {
      // do something with the exception here?
   }
}

程式碼在 Try-Catch 中只會包裝各項呼叫，所以處理常式中擲回的例外狀況 (Exception) 並不會妨礙其他處理常式被呼叫。

事件

我們已經談了不少委派，現在該來談談事件了。一個顯而易見的問題是：「既然已經有了委派，為什麼還要事件？」

最好的回答就是，研究一下使用者介面物件的案例。例如，按鈕上面可能有一個公用的 Click 委派。我們可以將函式連結到該委派，那樣在按下按鈕時就會呼叫委派。我們可以這樣做：

   Button.Click = new Button.ClickHandler(ClickFunction);

這表示在按下按鈕時，就會呼叫 ClickFunction()。

問題：上面的程式碼有問題嗎？我們忘了什麼？

答案是我們忘了使用 +=，而直接指定了委派。這表示任何連結到 Button.Click 的其他委派都會被解除攔截。Button.Click 必須是公用 (Public) 的，其他物件才能存取它，而我們無法阻止上述的情況。同樣的，如果要移除委派，使用者可以這樣寫：

   Button.Click = null;

這樣會移除所有委派。

這些情況特別糟糕，因為在很多案例中，都只連結一個委派，問題不會明顯到被當成錯誤。若日後連結了另一個委派，問題就開始惡化了。

事件會在委派模型上方加一層保護。底下是可支援事件的物件之範例：

public class MyObject
{
   public delegate void ClickHandler(object sender, EventArgs e);
   public event ClickHandler Click;

   protected void OnClick()
   {
      if (Click != null)
         Click(this, null);
   }
}

ClickHandler 委派會用事件委派的標準模式來定義事件的簽名碼。它的名稱以處理常式結尾，而且有兩個參數。第一個參數是傳送物件的物件，第二個參數則用來傳遞和事件一起發出的資訊。這個案例沒有要傳遞的資訊，所以直接使用 EventArgs，但是有資料要傳遞時，就要使用從 EventArgs 衍生的類別 (例如 MouseEventArgs)。

宣告 Click 事件要做兩件事。首先，宣告名為 Click 的委派成員變數，這個變數會從類別內部被使用。其次，宣告名為 Click 的事件，這個事件可以根據一般的存取規則，從類別外部被使用 (在這個案例中，事件是公用的)。

通常都會包括一個像 OnClick() 的函式，使得型別或衍生型別可以引發事件，您會發現，它用來引發事件的程式碼和委派的程式碼一樣，因為 Click 是一個委派。

就像委派一樣，我們攔截和取消攔截使用 += 和 -= 的事件，和委派不同的地方，在於這些是唯一能在事件上執行的作業。這樣可以確保先前談到的兩項錯誤不會發生。

事件的使用方式簡單明瞭。

class Test
{
   static void ClickFunction(object sender, EventArgs args)
   {
      // process the event here.
   }
   public static void Main()
   {
      MyObject myObject = new MyObject();

      myObject.Click += new MyObject.ClickHandler(ClickFunction);
   }
}

我們建立和委派的簽名碼相符的靜態函式或成員函式，然後用 += 將委派的新執行個體加入事件。

本月到此為止。下個月我們要談一下事件如何在內部運作，以及實作事件的一些進階方法 (提示：事件有時候因為有額外保護而略不同於委派)。如果您真的好奇地等不及了，範例程式碼裡也有下個月的程式碼。


委派講解(2) -深入探討事件 (Event)

上個月我們談到委派如何運作，也提了一下事件。這個月，我們要深入一點探討事件。

在上個月的專欄中，我提示過事件就像只有套用 += 和 -= 運算子的委派。我們學到當您以下列方式使用委派時：

      MyClass.LogHandler lh = null;
      lh += new MyClass.LogHandler(Logger);
      lh += new MyClass.LogHandler(fl.Logger);

編譯器會將 += 的使用轉換為呼叫 Delegate.Combine()。因此，我們或許可以預期，同樣的情形也會發生在事件上，且讓我們來看看編譯器會做什麼。我們用的是上個月的程式碼：

   public static void Main()
   {
      MyObject myObject = new MyObject();
      myObject.Click += new MyObject.ClickHandler(ClickFunction);
   }

建立程式碼之後，經由 Microsoft 中繼語言反組譯工具 (Intermediate Language Disassembler，ILDASM) 加以執行 (如需 ILDASM 的詳細資訊，請參閱 易學易用 C# )，看看那兒有些什麼東西。令我們感到驚訝的是，找到的不是對 Delegate.Combine() 的呼叫，而是對 MyObject 類別中名為 add_Click() 的函式的呼叫。嗯，我真想知道那個函式會做什麼。

如果查看一下 MyObject 的資訊，會注意到，它有名為 add_Click() 和
remove_Click() 的函式。查看 add_Click() 中的 IL 時，發現函式中有對
Delegate.Combine() 的呼叫。

這種情形和屬性的情形很像，我們不是直接存取欄位，而是用存取子 (Accessor) 函式取得或設定數值。在這個案例中，我們呼叫一個加入函式以連結事件，再呼叫移除函式從事件取消攔截，這正是為什麼在事件上除了 += 或 -= 之外，您不能作其他事情的原因。我們所謂的事件會被實作為加入和移除函式。

C# 中有兩種不同的方法可以實作事件，這兩種方法的詳細情形略有不同。首先來談談簡單的案例。

簡單的事件

在簡單事件案例中，編譯器會為我們做所有的工作。當我們撰寫底下這樣的程式碼時：

   public event LogHandler Log;

編譯器會宣告名為 Log 的私用 (Private) 委派欄位，也會宣告名為 add_Log() 和 remove_Log() 的函式，這些函式會呼叫適當的 Delegate 函式，以便從私用欄位加入或移除委派。最後則是在參考加入和移除函式的中繼資料中宣告名為 Log 的事件，這樣就會有事件顯示在物件瀏覽器中，而且編譯器還可以找到和事件相關聯的加入和移除函式 (這也是屬性運作的方式)。

且讓我們修改上個月的記錄範例，以便使用事件而不是使用委派：

using System;
using System.IO;

public class MyClass
{
   public delegate void LogHandler(string message);

   public event LogHandler Log;

   public void Process()
   {
      OnLog("Process() begin");
      // other stuff here?
      OnLog("Process() end");
   }

   protected void OnLog(string message)
   {
      if (Log != null)
         Log(message);
   }
}

class FileLogger
{
   FileStream fileStream;
   StreamWriter streamWriter;

   public FileLogger(string filename)
   {
      fileStream = new FileStream(filename, FileMode.Create);
      streamWriter = new StreamWriter(fileStream);
   }

   public void Logger(string s)
   {
      streamWriter.WriteLine(s);
   }

   public void Close()
   {
      streamWriter.Close();
      fileStream.Close();
   }
}

class Test
{
   static void Logger(string s)
   {
      Console.WriteLine(s);
   }

   public static void Main()
   {
      FileLogger fl = new FileLogger("process.log");

      MyClass myClass = new MyClass();

      myClass.Log += new MyClass.LogHandler(Logger);
      myClass.Log += new MyClass.LogHandler(fl.Logger);

      myClass.Process();
      fl.Close();
   }
}

我們不讓 Process() 函式以委派作為參數，而是宣告 Log 事件。在 Main() 中，只是將委派的執行個體加入事件會比較簡潔一些，您不必自己去處理事情 (或許還會做錯了)。

通常您都會想讓編譯器去做所有的事情，不過，有時候還是需要自己動手。

進階事件

編譯器處理事件時的問題之一是，它會為事件宣告委派欄位，而這會在物件中佔用空間。如果物件只支援一個或兩個事件，還不成問題，但是很多使用者介面物件可能支援十個、甚至上百個不同的事件。指定的物件同時只能連結幾個事件，所以會有很多浪費的空間。

進階語法可以讓程式設計人員接管整個處理序，包括委派的儲存。若要開始試試，底下的進階語法能執行與編譯器完全一樣的功能：

using System;
using System.Runtime.CompilerServices;

public class MyClass
{
   public delegate void LogHandler(string message);

   private LogHandler log;
   public event LogHandler Log
   {
      [MethodImpl(MethodImplOptions.Synchronized)]
      add
      {
         log = (LogHandler) Delegate.Combine(log, value);
      }

      [MethodImpl(MethodImplOptions.Synchronized)]
      remove
      {
         log = (LogHandler) Delegate.Remove(log, value);
      }
   }
   protected void OnLog(string message)
   {
      if (log != null)
         log(message);
   }
}

在這個範例中，我們為事件撰寫了自己的 add() 和 remove() 存取子。Delegate.Combine() 和 Delegate.Remove() 呼叫不需要太多解釋。必須要有 MethodImpl 屬性，加入和移除函式才是安全執行緒的 (Thread-safe) 函式。如果沒有這個屬性，兩個執行緒可能會同時呼叫加入函式，如果時機湊巧 (或者不湊巧，看您的觀點而定)，可能會得到不正確的結果。

這個範例顯示的是，如何撰寫沒有任何好處的多餘程式碼。為了得到我們所要的好處 - 使用較少的儲存空間 - 我們需要用其他方法儲存委派。

假設我們的物件可以有很多事件和它關聯，但是這些事件很少是在作用中。所以，我們將需要方法來儲存和事件關聯的委派，而不必讓各個委派都要使用獨立的欄位。將它們儲存在雜湊表 (Hashtable) 中是輕鬆的作法，但是撰寫類別將雜湊表封裝起來更簡潔一些，介面也會比較簡單。最後的結果如下：

using System;
using System.Runtime.CompilerServices;
using System.Collections;

class DelegateCache
{
   private Hashtable delegateStorage = new Hashtable();
   public Delegate Find(object key)
   {
      return((Delegate) delegateStorage[key]);
   }
   public void Add(object key, Delegate myDelegate)
   {
      delegateStorage[key] =
         Delegate.Combine((Delegate) delegateStorage[key],
                myDelegate);
   }
   public void Remove(object key, Delegate myDelegate)
   {
      delegateStorage[key] =
         Delegate.Remove((Delegate) delegateStorage[key],
                myDelegate);
   }
}

public class MyClass
{
   public delegate void LogHandler(string message);

   private DelegateCache delegateCache = new DelegateCache();

   private static object logEventKey = new object(); // unique key
   public event LogHandler Log
   {
      [MethodImpl(MethodImplOptions.Synchronized)]
      add
      {
         delegateCache.Add(logEventKey, value);
      }

      [MethodImpl(MethodImplOptions.Synchronized)]
      remove
      {
         delegateCache.Remove(logEventKey, value);
      }
   }

   protected void OnLog(string message)
   {
      LogHandler lh = (LogHandler) delegateCache.Find(logEventKey);

      if (lh != null)
         lh(message);
   }

   public void Process()
   {
      OnLog("Process() begin");
      // other stuff here?
      OnLog("Process() end");
   }
}

class Test
{
   static void Logger(string s)
   {
      Console.WriteLine(s);
   }

   public static void Main()
   {
      MyClass myClass = new MyClass();

      myClass.Log += new MyClass.LogHandler(Logger);
      myClass.Log += new MyClass.LogHandler(Logger);

      myClass.Process();
      myClass.Log -= new MyClass.LogHandler(Logger);

      myClass.Process();
   }
}

DelegateCache 類別會為我們完成棘手的工作，而且可以讓其他類別用來儲存它們的委派。Add 和 Remove 存取子會用 Helper 類別來儲存委派。LogEventKey 變數用來產生這個事件獨有的索引鍵，但是不會佔用物件的空間，因為它是靜態的變數。然後在我們呼叫 DelegateCache 執行個體中的函式時，會使用這個索引鍵來確認我們得到的是正確的委派。這個範例輸出的程式碼如下：

Process() begin
Process() begin
Process() end
Process() end
Process() begin
Process() end

我們也可以實作整個應用程式而非針對單一執行個體的快取。要這樣做，就必須根據執行個體和索引鍵來儲存委派。


QuickDelegate Demo
using System;
// 1. Define delegate.
public delegate double UnitConversion(double from);
class QuickDelegateDemo
{
    // 2. Define handler method.
    public static double FeetToInches(double feet)
    {
        return feet * 12;
    }
    static void
Main()
{
//
3. Create delegate instance.
UnitConversion doConversion = new UnitConversion(FeetToInches);
        Console.WriteLine("Feet to Inches Converter");
        Console.WriteLine("------------------------\n");

        Console.Write("Please enter feet:  ");
        double feet = Double.Parse(Console.ReadLine());
        // 4. Use delegate just like a method.
        double inches = doConversion(feet);
Console.WriteLine("\n{0} Feet = {1} Inches.\n", feet,
inches);
Console.ReadLine();
}
}


Dynamic Delegates
using System;
// 1. Define delegate.
public delegate double UnitConversion(double from);
class DynamicDelegates
{
//
// 2. Define handler methods.
//
public double FeetToInches(double
feet)
{
return feet * 12;
}
    public double YardsToInches(double yards)
    {
        return yards * 36;
    }
    // Factory method for returning delegate
    public UnitConversion GetConversionMethod(string conversionType)
    {
        UnitConversion conversion;
        switch (conversionType)
        {
            case "1":
                conversion = new UnitConversion(FeetToInches);
                break;
            case "2":
                conversion = new UnitConversion(YardsToInches);
                break;
            default:
                throw new ArgumentException("Unrecognized conversion type: " + conversionType, conversionType);
        }
        return conversion;
    }
    // show menu and return units to convert and type of conversion
    public void GetUserInput(out double units, out string conversionType)
    {
        Console.WriteLine("Units Converter");
        Console.WriteLine("------------------------\n");

        Console.WriteLine("1 - Feet to Inches");
        Console.WriteLine("2 - Yards to Inches");
        Console.Write("\nPlease select conversion option (1 or 2):  ");
        conversionType = Console.ReadLine();
        Console.Write("\n\nPlease enter units:  ");
        units = Double.Parse(Console.ReadLine());
    }
    static void
Main()
{
DynamicDelegates dels = new
DynamicDelegates();

double
units;
string
conversionType;

dels.GetUserInput(out units, out
conversionType);
        // 3. get delegate instance via factory method.
        UnitConversion doConversion = dels.GetConversionMethod(conversionType);
        // 4. Use delegate just like a method.
        double inches = doConversion(units);
Console.WriteLine("\n{0} Units = {1} Inches.\n", units,
inches);
Console.ReadLine();
}
}


Event Listener
using System;
class EventListener
{
static void Main()
{
EventPublisher publisher = new
EventPublisher();
EventListener  listener  = new EventListener();
publisher.InterestingEvent += new
EventHandler(listener.HandlerOne);
publisher.InterestingEvent += new
EventHandler(listener.HandlerTwo);
        publisher.InterestingDelegate += new EventHandler(listener.HandlerOne);
        // assignment accidentally wiped out delegate for listener.HandlerOne
        publisher.InterestingDelegate = new EventHandler(listener.HandlerTwo);
        // illegal
//        publisher.InterestingEvent = null;
        // can't invoke event outside of its containing class
//        publisher.InterestingEvent(listener, EventArgs.Empty);
        Console.WriteLine("\nInvoking Event:\n");
        publisher.FireEvent();
        Console.WriteLine("\nInvoking Delegate:\n");
        publisher.InterestingDelegate(listener, EventArgs.Empty);
        Console.ReadLine();
    }
    public void HandlerOne(object sender, EventArgs e)
    {
        Console.WriteLine("HandlerOne Called.");
    }
    public void HandlerTwo(object sender, EventArgs e)
    {
        Console.WriteLine("HandlerTwo Called.");
    }
}
class EventPublisher
{
    // declare event
    public event EventHandler InterestingEvent;
    // declare public delegate
    public EventHandler InterestingDelegate;
    public void
FireEvent()
{
InterestingEvent(this,
EventArgs.Empty);
}
}


介面修飾詞
介面修飾詞：
new
public
protected
internal
private
1.new 修飾詞僅能用於定義於類別內的介面。它指定介面隱藏相同名稱的繼承成員。
2.public、protected、internal 和 private 修飾詞控制介面的存取範圍。依據介面宣告出現的內容，只會允許部分的修飾詞 。


兩整數值互相交換
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   int a=5;
   int b=3;
   Console.WriteLine("a={0}, b={1}", a, b);
   swapValue(ref a, ref b);
   Console.WriteLine("a={0}, b={1}", a, b);
  }
  /// <summary>
  /// 兩整數值互相交換
  /// </summary>
  public static void swapValue(ref int a, ref int b)
  {
   int tmp = a;
   a = b;
   b = tmp;
  }
 }
}


平方根 (Math.Sqrt)
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
double
x=2.0;
Console.WriteLine("{0}",Math.Sqrt(x));
}
}
}
結果：
 1.4142135623731
 請按任意鍵繼續 . . .


三角函數(Sin,Cos,tan...)
三角函數：
 Sin,Cos,tan,Asin,Acos,Atan,Atan2,sinh,conh,tanh
範例：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
double
x=3.1415926;
Console.WriteLine("Sin={0}",Math.Sin(x));
Console.WriteLine("Cos={0}",Math.Cos(x));
Console.WriteLine("Tan={0}",Math.Tan(x));
}
}
}
結果：
Sin=5.35897931700532E-08
Cos=-0.999999999999999
Tan=-5.35897931700533E-08
請按任意鍵繼續
. . .


整數處理(Floor、Ceiling、Abs、Sign)
Floor   ：傳回不大於X的最大整數
Ceiling ：傳回不小於X的最小整數
Abs     ：傳回X的絕對值
Sign    ：傳回-1∼0∼1之間的識別數值
程式碼範例：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   double x=8.3;
   double
y=-2;
Console.WriteLine("Floor={0}",Math.Floor(x));
Console.WriteLine("Ceiling={0}",Math.Ceiling(x));
Console.WriteLine("Abs={0}",Math.Abs(y));
   Console.WriteLine("Sign={0}",Math.Sign(y));
  }
 }
}
結果：
Floor=8
Ceiling=9
Abs=2
Sign=-1
請按任意鍵繼續 . . .


Pow函數
Pow函數：求某數的某次方值
範例：
      y
   X   =>使用Pow函數，傳回此公式結果。
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
double
x=3.2;
double
y=1.8;
Console.WriteLine("Pow(x,y)={0}",Math.Pow(x,y));
}
}
}
結果：
Pow(x,y)=8.1146531454009
請按任意鍵繼續 . . .


其他函數(Exp、Log、Log10)
                 x
Exp   ：指數函數 e
Log   ：自然對數函數
Log10 ：以10為底的對數函數
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
double
x=8.0;
Console.WriteLine("Exp(x)={0}",Math.Exp(x));
Console.WriteLine("Log(x)={0}",Math.Log(x));
Console.WriteLine("Log10(x)={0}",Math.Log10(x));
}
}
}
結果：
Exp(x)=2980.95798704173
Log(x)=2.07944154167984
Log10(x)=0.903089986991944
請按任意鍵繼續 . . .


遞回函數呼叫
第一種寫法：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   int i;
   for (i=0;i<5;i++)
    Console.WriteLine("{0}!= {1}",i,factorial(i));
  }

  public static int factorial(int j)
  {
   int sum;
   if(j==0)
    sum=1;
   else
    sum=j*factorial(j-1);
   return sum;
  }
 }
}
第二種寫法：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   int i;
   for (i=0;i<5;i++)
    Console.WriteLine("{0}!= {1}",i,factorial(i));
  }

  public static int factorial(int j)
  {
   return((j ==0) ? 1 : (j * factorial(j-1)));
  }
 }
}
結果：
0!= 1
1!= 1
2!= 2
3!= 6
4!= 24
請按任意鍵繼續 . . .


隨機數函數 (1) (System.Random)
由1到100之間，隨機產生10個數。
程式碼如下：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
Random rand = new
Random();
for (int
i=1;i<=10;i++)
//產生10個數
Console.WriteLine("{0}",rand.Next( 1, 100 ));
//1-100之間
}
}
}


隨機數函數(2) -猜數字遊戲 0-99
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
int
num=100;
int ran,guess;
int
count=0;
string inputstring;
Random rand = new
Random();
ran=rand.Next( 0,
num);
while
(true)
{
count++;
Console.WriteLine("猜
0-99 之間的整數：");
inputstring=Console.ReadLine();
guess=int.Parse(inputstring);
if
(ran==guess)
{
Console.WriteLine("好棒喔！答對了！");
break;
}
if
(ran>guess)
Console.WriteLine("錯！你應該在猜大一點...\n");
else
Console.WriteLine("錯！你應該在猜小一點...\n");
}
Console.WriteLine("你總共猜了 {0}
次",count);
}
}
}
結果：
猜 0-99 之間的整數：
50
錯！你應該在猜大一點...
猜 0-99 之間的整數：
60
錯！你應該在猜小一點...
猜 0-99 之間的整數：
55
好棒喔！答對了！
你總共猜了 3 次
請按任意鍵繼續 . . .


return (函數的傳回值)
return(函數的傳回值):
除了可以把函數內的值傳回呼叫程式外，同時具有令函數結束，返回呼叫程式的功能。


前端處理程式(C# Preprocessor Directives)- #if 指令
#define demo
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
         #if demo
            Console.WriteLine("Hello World Demo");
         #else
            Console.WriteLine("Hello World");
         #endif
  }
 }
}


#region (指定程式區塊)
#region name

說明：

name ：The name you want to give to the region, which will appear in the #D Code Editor.
範例：
// preprocessor_region.cs
#region MyClass definition <------指定的區塊開始
public class MyClass
{
   public static void Main()
   {
   }
}
#endregion                 <------指定的區塊結束


C# Preprocessors
http://msdn.microsoft.com/library/en-us/csref/html/vclrfPreprocessorDirectives.asp
Even though the C# compiler does not have a separate preprocessor,there are some preprocessing directives supported by the C# compiler which helps in conditional compilation. Unlike C++ directives the C# directives cannot be used for creating macros. Following is the list of preprocessing directives supported by C#.
  • #if
  • #else
  • #elif
  • #endif
  • #define
  • #undef
  • #warning
  • #error
  • #line
  • #region
  • #endregion
#if, along with the #else, #elif,endif, #define, and #undef directives, lets you include or exclude code based on the condition of one or more symbols.This can be most useful when compiling code for a debug build or when compiling for a specific configuration.

The #define directive is used for defining a symbol.When this symbol is used as the expression in a #if directive or #elif directive the expression will evaluate to true. The syntax for using the #define directive is
#define symbol

A symbol can also be defined using the /define compiler option.The syntax for using this compiler option is
csc sourcefilename /define symbol

Multiple symbols can be defined with /define by using ;(semicolon) or ,(comma) to separate the symbol names.The #undef directive is used for undefining a symbol.When this symbol is used as the expression in a #if directive or #elif directive the expression will evaluate to false. The syntax for using the #undef directive is
#undef symbol

Note:The #define and #undef directives must precede all the statements other than directives in a file

The #if directive is used to test symbols and if they evaluate to true the compiler executes all the code between #if directive and the next directive.The syntax for using #if directive is

#if symbol [operator symbol] ....
Multiple symbols can be evaluated using ==,!=,&&,|| operators.

The #elif directive is used in compound conditional statments.The #elif directive is evaluated if all the preceding #if and #elif directives evaluate to false. If the #elif expression evaluates to true the compiler executes all the code between #elif directive and the next directive.The syntax for using #elif directive is
#elif symbol [operator symbol] ....

The #else directive is used in compound conditional statments.The #else directive is evaluated if all the preceding #if and #elif directives evaluate to false. If the #else expression evaluates to true the compiler executes all the code between #else directive and the #endif directive.

The #endif directive is used for terminating #if /STRONG> directive.

Note:The #if directive should be explicitly terminated with #endif directive.
Example

#define DEBUG
using System;
class PreProcessorTest
{
  static void Main()
  {
    #if (DEBUG)
        Console.WriteLine("DebuG is True");
    #else
        Console.WriteLine("DebuG is False");
    #endif
  }
}

Compiling the above code will result in the following output
DebuG is True

The #line directive is used to change the complier's line number and filename in error and warning messages. The syntax for using #line directive is
#line number ["filename"]
Example
using System;
class PreProcessorTest{
         static void Main()
          {
           #line 100
           Console.LineWrite("God is Great");
           }
}

Compiling the above code will result in the following error.
PreProcessorTest.cs(100,2): error CS0117: 'System.Console' does not contain a d definition for 'LineWrite'
The error message show the error line number as 100 even though the actual line of error is 7

The #warning directive is used to generate a warning from a specific location in the code.It is normally used within a conditional directive.The syntax for using #warning directive is
#warning message

The #error directive is used to generate an error from a specific location in our code.It is normally used within a conditional directive.The syntax for using the #error directive is
#error message

The #region and #endregion are used to specify a block of code which can be expanded or collapsed when using the outline feature of Visual Studio editor.The syntax for using the #region directive is
#region regionname
Note:The #region directive should be explicitly terminated with #endregion directive.


Structures (結構)

struct 型別是一種數值型別，可以包含建構函式、常數、欄位、方法、屬性、索引子、運算子和巢狀型別 (Nested Type)，結構也能實作介面。
結構不可以宣告預設的 (無參數的) 的建構函式。
不過可以使用有參數的建構函式。
存取structure裡的memeber比存取class裡的member要快一點。
範例：
class TestStruct
{
 public static void Main()
 {
SimpleStruct st = new
SimpleStruct(4);
System.Console.WriteLine(st.i);
st.aMethod();
}
}

struct SimpleStruct
{
  public int i;
  public SimpleStruct(int j)
  {
   i=j;
  }
  public void aMethod()
  {
   System.Console.WriteLine("Inside aMethod");
  }
}

結果：
4
Inside aMethod

Features of Structures:
========================================================
* A structure or struct can contain only fields, methods, Etc.,

* In struct we can't initialize the variable whereas in class it can be possible

* It must be initialized either through function or using object

* Fields can't be given initial values at that time of creation.

* struct can't have a constructor.

* struct can't support the concept of inheritance

* We can derive a structure from an interface

* We can't inherit from sealed class

* A structure could not inherit from a class, the reverse is also true

* You can't declare a struct as sealed, because by default it is sealed

* A structure declare as abstract can't be used as a base class, i.e., be used in a derivation

* No destructor for struct

* struct are created on the stack and die when we reach the closing brace


enum(列舉)
enum Weekdays
{
  Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
}


類別(Class)與結構(Structs) 比較

Classes and structs are same as in C++, except in the difference of their memory allocation. Objects of classes are allocated in the heap, and are created using new, where as structs are allocated in the stack. Structs in C# are very light and fast datatypes. For heavy datatypes, you should create classes.

範例:

struct Date
{
  int day;
  int month;
  int year;
}

class Date
{
  int day;
  int month;
  int year;
  string weekday;
  string monthName;

  public int GetDay()
  {
    return day;
  }

  public int GetMonth()
  {
    return month;
  }

  public int GetYear()
  {
    return year;
  }

  public void SetDay( int Day )
  {
    day = Day;
  }

  public void SetMonth( int Month )
  {
    month = Month;
  }

  public void SetYear( int Year )
  {
    year = Year;
  }

  public bool IsLeapYear()
  {
    return (year/4 == 0);
  }

  public void SetDate( int day, int month, int year )
  {
  }

  ...
}


傳回字元索引位置 - (String.IndexOf / String.LastIndexOf )
一、String.IndexOf
從您正在檢查的字串開頭開始，傳回字元或字串的索引位置。傳回整數值。
程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string MyString = "Hello World";
   Console.WriteLine(MyString.IndexOf('W'));
  }
 }
}
結果：
6
請按任意鍵繼續 . . .
二、String.LastIndexOf
從您正在檢查的字串結尾開始，傳回字元或字串的索引位置。傳回整數值。
程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string MyString = "Hello World";
   Console.WriteLine(MyString.LastIndexOf('d'));
  }
 }
}
結果：
10
請按任意鍵繼續 . . .
說明：上述兩個範例，可知計算時，都會忽略空白字元。


字串大小寫轉換 (String.ToUpper /String.ToLower )
範例：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string Str1 = "abc";
   string Str2 = "ABC";
   Console.WriteLine(Str1.ToUpper()); //轉大寫
   Console.WriteLine(Str2.ToLower()); //轉小寫
  }
 }
}
結果：
ABC
abc
請按任意鍵繼續 . . .


字串拷貝 (String.Copy)
String.Copy使用與指定的 String 相同的值，建立 String 的新執行個體。
程式碼：
using System;
namespace
DefaultNamespace
{
class
MainClass
{
public static void
Main()
{
string str1 =
"abc";
string str2 =
"xyz";
Console.WriteLine("1) str1 = '{0}'",
str1);
Console.WriteLine("2) str2 = '{0}'",
str2);
Console.WriteLine("執行拷貝...");
str2
= String.Copy(str1);
Console.WriteLine("3)
str1 = '{0}'", str1);
Console.WriteLine("4) str2 = '{0}'",
str2);
}
}
}
結果：
1) str1 = 'abc'
2) str2 = 'xyz'
執行拷貝...
3) str1 = 'abc'
4) str2 = 'abc'
請按任意鍵繼續 . . .


字串比較(1) (String.Compare)
String.Compare比較兩個字串的值。傳回整數值。
程式碼：
using
System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
string MyString =
"Hello World!";
if (String.Compare(MyString, "Hello World?")==-1)
Console.WriteLine("字串不一樣");
else
Console.WriteLine("字串一樣");
}
}
}


字串比較(2)-檢查字串是否完全相同 (String.CompareOrdinal )
String.CompareOrdinal比較兩個字串，不管本地文化特性。傳回整數值。
程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string MyString = "Hello World!";
   Console.WriteLine(String.CompareOrdinal(MyString, "hello world!"));
  }
 }
}
說明：
此範例會顯示不一樣的表示數字：-32


字串比較(3)- ( String.CompareTo )
String.CompareTo將目前的字串物件與另一個字串加以比較。傳回整數值。
程式碼：
using System;
namespace
DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
String MyString =
"Hello World";
String OtherString = "Hello
World!";
int MyInt = MyString.CompareTo(OtherString);
Console.WriteLine( MyInt );
}
}
}

結果：
顯示-1


字串比較(4) - (String.Equals )
String.Equals判斷兩個字串是否相同。傳回布林值。
程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string MyString = "Hello World";
   Console.WriteLine(MyString.Equals("Hello World"));
  }
 }
}
結果：
顯示True


字串比較(5) - (String.StartsWith /String.EndsWith )
一、String.StartsWith
判斷字串的開頭是否為傳入的字串。傳回布林值。
程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string MyString = "Hello World";
   Console.WriteLine(MyString.StartsWith("Hello"));
  }
 }
}
結果：
顯示True
二、String.EndsWith
判斷字串的結尾是否為傳入的字串。傳回布林值。
程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   string MyString = "Hello World";
   Console.WriteLine(MyString.EndsWith("Hello"));
  }
 }
}
結果：
顯示False


由字元組成的一維陣列
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
char[] Q=new char[3]
{'a','b','c'};
int
i;
for(i=0;i<3;i++)
Console.Write("{0}",Q[i]);
Console.Write("\n");
}
}
}
結果：
abc
請按任意鍵繼續 . . .


分辨 File 類型
假 設 我 們 有 一 個 string， 它 載 著 一 個 檔 案 的 路 徑 ，
我 們 現 在 想 知 道 那 一 個 File 是 檔 案 還 是 資 料 夾 。
我 們 可 以 使 用 FileAttributes。

public static void CheckFileAttribute(string strFilePath)
{
 try
 {
  FileAttributes aAttributes = File.GetAttributes(strFilePath);
  if ( aAttributes == FileAttributes.Directory )
       Console.WriteLine(strFilePath + " 是一個資料夾");
  else
       Console.WriteLine(strFilePath + " 不是一個資料夾");
 } catch ( IOException e )
   {
      Console.WriteLine(e.Message);
   }
}


鏈結串列

The following code demonstrates how to write amd use a link list in C#.

using System;

namespace PardesiServices
{
 class LinkList
 {
  public string Val;
  public object NextItem;
  [STAThread]
  static void Main(string[] args)
  {
   LinkList obList = new LinkList();
   obList.Val = "Head";
   LinkList obHead = obList;
   // Add 10 items to the list.
   for (int i = 0; i < 10; i++)
   {
    obList.NextItem = new LinkList();
    obList = (LinkList)obList.NextItem;
    obList.Val = i.ToString();
   }
   // Print the added items.
   while (obHead != null)
   {
    Console.WriteLine("Item: {0}", obHead.Val);
    obHead = (LinkList)obHead.NextItem;
   }
  }
 }
}


泡泡排序
using System;
...
namespace BubbleSorter
{
 public class BubbleSorter
 {
  public void Sort(int [] list)
  {
   int i,j,temp;
   bool done=false;
   j=1;
   while((j<list.Length)&&(!done))
   {
    done=true;
    for(i=0;i<list.Length-j;i++)
    {
     if(list[i]>list[i+1])
     {
      done=false;
      temp=list[i];
      list[i]=list[i+1];
      list[i+1]=temp;
     }
    }
    j++;
   }
  }
 }

 public class MainClass
 {
  public static void Main()
  {
   int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47};
   BubbleSorter sh=new BubbleSorter();
   sh.Sort(iArrary);
   for(int m=0;m<iArrary.Length;m++)
    Console.Write("{0} ",iArrary[m]);
   Console.WriteLine();
  }
 }
}


選擇排序
using System;

namespace SelectionSorter
{
 public class SelectionSorter
 {
  private int min;
  public void Sort(int [] list)
  {
   for(int i=0;i<list.Length-1;i++)
   {
    min=i;
    for(int j=i+1;j<list.Length;j++)
    {
     if(list[j]<list[min])
      min=j;
    }
    int t=list[min];
    list[min]=list[i];
    list[i]=t;
   }
  }
 }

 public class MainClass
 {
  public static void Main()
  {
   int[] iArrary=new int[]{1,5,3,6,10,55,9,2,87,12,34,75,33,47};
   SelectionSorter ss=new SelectionSorter();
   ss.Sort(iArrary);
   for(int m=0;m<iArrary.Length;m++)
    Console.Write("{0}  ",iArrary[m]);
   Console.WriteLine();
  }
 }
}


插入排序
using System;

namespace ShellSorter
{
 public class ShellSorter
 {
  public void Sort(int [] list)
  {
   int inc;
   for(inc=1;inc<=list.Length/9;inc=3*inc+1);
   for(;inc>0;inc/=3)
   {
    for(int i=inc+1;i<=list.Length;i+=inc)
    {
     int t=list[i-1];
     int j=i;
     while((j>inc)&&(list[j-inc-1]>t))
     {
      list[j-1]=list[j-inc-1];
      j-=inc;
     }
     list[j-1]=t;
    }
   }
  }
 }

 public class MainClass
 {
  public static void Main()
  {
   int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47};
   ShellSorter sh=new ShellSorter();
   sh.Sort(iArrary);
   for(int m=0;m<iArrary.Length;m++)
    Console.Write("{0} ",iArrary[m]);
   Console.WriteLine();
  }
 }
}


Shell排序
using System;

namespace ShellSorter
{
 public class ShellSorter
 {
  public void Sort(int [] list)
  {
   int inc;
   for(inc=1;inc<=list.Length/9;inc=3*inc+1);
   for(;inc>0;inc/=3)
   {
    for(int i=inc+1;i<=list.Length;i+=inc)
    {
     int t=list[i-1];
     int j=i;
     while((j>inc)&&(list[j-inc-1]>t))
     {
      list[j-1]=list[j-inc-1];
      j-=inc;
     }
     list[j-1]=t;
    }
   }
  }
 }

 public class MainClass
 {
  public static void Main()
  {
   int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47};
   ShellSorter sh=new ShellSorter();
   sh.Sort(iArrary);
   for(int m=0;m<iArrary.Length;m++)
    Console.Write("{0} ",iArrary[m]);
   Console.WriteLine();
  }
 }
}


常數
常數為可以表示一個常數值的類別成員：即可以在編譯時期計算的數值。
常數可以在相同程式中相依其他常數，只要這之間沒有循環相依性。
範例
class Constants
{
   public const int A = 1;
   public const int B = A + 1;
}

說明了擁有兩個公用常數的 Constants 類別。
即使常數被認定是靜態成員，常數宣告仍不需要、也不允許使用 static 修飾詞。
常數可以透過類別來存取，就像下面這個範例
using System;
class
Test
{
static void Main() {
Console.WriteLine("{0}, {1}", Constants.A,Constants.B);
}
}

其將分別印出 Constants.A 和 Constants.B 的值。


類別(class)與物件(Object)的區別
類別(Class):可以說是一種型態,但沒有實體.
物件(Object):是用Class實作出來的東西.

舉個例子來說,有一段程式如下:

class Rectangle
{
int Height;
int Width;
};
//宣告了一個名為Rectangle的"類別",但是並沒有實體

void main()
{
Rectangle RecA , RecB ;
............
}
//宣告 RecA,RecB 為Rectangle型態的"物件",RecA及RecB皆有實體(有佔記憶體空間)

另一個例子說明:
桌上有3顆大小不一的蘋果,它們的名稱分別為 AppleA , AppleB , AppleC . 我們知道這3顆蘋果:AppleA , AppleB , AppleC 都是一顆蘋果 (癈話....=.=") .
那麼我們可以說:
蘋果是類別 ; 而AppleA , AppleB , AppleC是物件.

另一個例子說明:
class就好像是蓋房子的藍圖一樣 ,可以重複使用它蓋很多棟房子 ,
而object則好像是用藍圖蓋出的房子一樣 ,是class的"實作"....


using System;
using System.Text.RegularExpressions;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
            string expression = @"[a-zA-Z]\.";
            Regex regular = new Regex(expression, RegexOptions.Compiled);
            Console.WriteLine("Regular Expression: {0}", expression);

            string search;

            search = "a";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "a.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "ab.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "ab..";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "ab";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "aB.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "aB..";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "aB";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "a.B.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));

            // first attempt on exact match, see final attempt for better one
            expression = @"[a-zA-Z]\.$";
            Console.WriteLine("Regular Expression: {0}", expression);
            search = "ab.";
            Match m = Regex.Match(search, expression);
            Console.WriteLine("Exact match for {0} is {1}", search, (m.Success && m.Index == 0 && m.Length == search.Length));

            // second attempt
            expression = @"[a-zA-Z]\.$";
            Console.WriteLine("Regular Expression: {0}", expression);
            search = "ab.";
            m = Regex.Match(search, expression);
            Console.WriteLine("Exact match for {0} is {1}", search, (m.Success) && (m.Value == search));

            // final attempt to find exact match
            // ^ match begin of line, $ match end of line
            expression = @"^[a-zA-Z]\.$";
            regular = new Regex(expression, RegexOptions.Compiled);
            Console.WriteLine("Regular Expression: {0}", expression);

            search = "a";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "a.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "ab.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "ab..";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "ab";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "aB.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "aB..";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "aB";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "a.B.";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));
            search = "";
            Console.WriteLine("Search for {0} is {1}", search, regular.IsMatch(search));

            expression = @"^[a-zA-Z]$|^[a-zA-Z]\.$|^[a-zA-Z]\.[a-zA-Z]\.$";
            regular = new Regex(expression, RegexOptions.Compiled);
            Console.WriteLine("Regular Expression: {0}", expression);

            search = "a";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "a.";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "ab.";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "ab..";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "ab";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "aB.";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "aB..";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "aB";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "a.B.";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));
            search = "";
            Console.WriteLine("Exact match for {0} is {1}", search, regular.IsMatch(search));

            Console.Write("按 Enter 鍵 繼續: ");
            Console.ReadLine();

  }
 }
}


Hello world程式 -1
1.檔案->新增->新增專案->C#->Console應用程式->確定
2.執行
程式碼如下：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
Console.WriteLine("Hello
World!");
}
}
}


Hello world程式-2
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   dispMessage("Hello world 程式-2");
  }
  public static void dispMessage(string msg)
  {
   Console.WriteLine(msg);
  }
 }
}


視窗應用程式-基本架構
1.檔案->新增->新增專案->C#->Windows應用程式->確定
2.執行
程式碼如下：
using System;
using System.Windows.Forms; //參考區

namespace DefaultNamespace  //名稱空間區段開始
{
public class MainForm : System.Windows.Forms.Form //Class區段開始
{
  //元件初始化區
  public MainForm()
  {
   InitializeComponent();
  }

  #region 表單視窗設計 程式碼自動產生區
  private void InitializeComponent()
  {
   // Form1
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Text = "MainForm";
   this.Name = "MainForm";
  }
  #endregion

  [STAThread] //程式進入點
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }
  } //Class區段 結束
} //名稱空間 結束


C# 和 C++ 的比較
下列連結中表格包含 C++ 與 C# 功能之間的重要比較。
如果您是 C++ 程式設計人員，這個表格將概要地提供您兩種語言之間最大的差異。
 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cscon/html/vclrfComparisonBetweenCCSharp.asp


From the Team

Welcome to the Team section of the Visual C# Developer Center. Provided by the C# Product Team, the content in this section includes samples, articles, columns, and other information produced by the team. This section also contains message boards on which you can ask questions of the C# team members.

Eric Gunnerson
Visual C# Team

Blogs from the C# Team
Get connected with the C# team through their blogs (web logs). Ask questions, read about the development process behind your favorite language and tools, and more.

  • Eric Gunnerson
  • Gus Perez
  • Dan Fernandez
C# Language
Find specifications and other information about C# in the C# Language section. It's also the place to interact with the C# language designers and other experts.

Getting Help
Find the answers to your questions about Visual C# on the Microsoft public newsgroups. In these newsgroups, you can interact with Visual C# product team members, MVPs, and other C# enthusiasts.

  • microsoft.public.dotnet.languages.csharp
Sample Code from the C# Team
Check out sample applications from the C# Team, along with libraries for you to use. For more code samples, go to the downloads/code samples page of this developer center.

Frequently Asked Questions
Find answers to your C# questions in this list of common questions answered by team members.

Tools
Find various tools to help you in your C# development.

  • .NET Framework SDK Downloads
  • Classes and Libraries
  • AQdevTeam

Friends of C#

  • C# Station (providing C# help and links since July 4th, 2000!!)
  • .NET Weblogs @ ASP.NET
  • ASP.NET Tutorials, Components, and Links at 123aspx.com
  • Blogs on GotDotNet
  • C# at Suite101.com
  • C# Information Portal—Mantro Technologies
  • C# Help
  • dotnetspider.com
  • c-sharpcenter.com
  • csharp-corner.com
  • CSharpFriends—ASP.NET & C# Tutorials
  • Cshrp.net, an Online C# Resource
  • DevASP.NET for ASP.NET, XML, and C# Developers
  • DotNetBips—Applying .NET
  • GotDotNet: The Microsoft .NET Framework Community
  • Matthew Reynolds' .NET 247
  • RDPTools Website
  • The Code Project—Free Source Code and Tutorials
  • tiberi.us
  • Visual C# .NET Developer's Cookbook
  • Wimdows.net, Your Guide to ASP.net!
  • www.csharpsoft.com


C# 語法快速參考卡
// CLASS1.CS -- Syntax-at-a-Glance for the C# programming language.
// A quick code reference for programmers who work in many languages.
// Executable code, minimal comments document the essence of the language.
// Copyright (C) 2001 StructureByDesign.  All Rights Reserved.

using System;
using System.Collections;
using System.IO;

namespace StructureByDesign.Syntax
{
public class Class1: Object
{
    public static int Main(string[] args)       // Entry point.
    {
        System.Console.WriteLine("Hello");
        Class2 aclass2 = new Class2();
        aclass2.run();
        return 0;
    }
}

interface Interface1
{
    void run();
}

class Class2: Class1, Interface1
{
    public const int CONSTANT = 1;          // Access not restricted, implicitly static.
    private int m_intPrivateField;          // Access limited to containing type.
    public Class2() : base()                // Constructor.
    {
        initialize();
    }
    protected void initialize()             // Object initialization.
    {                                       // Access limited to containing class or types derived.
        Number = 1;
    }
    protected int Number                    // Language property feature.
    {
        get
        {
            return m_intPrivateField;
        }
        set
        {
            m_intPrivateField = value;      // Implicit parameter.
        }
    }
    public void run()
    {
        anonymousCode();
        arrays();
        collections();
        comparison();
        control();
        filesStreamsAndExceptions();
        numbersAndMath();
        primitivesAndConstants();
        runtimeTyping();
        strings();
    }
    void anonymousCode()
    {
        Delegate adelegate = new Delegate(Run);
        adelegate();
    }
    delegate void Delegate();
    void Run()
    {
        Console.WriteLine("Run");
    }
    void arrays()
    {
        int[] arrayOfInts = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        arrayOfInts[0] = 9;
        assert(arrayOfInts[0] == arrayOfInts[9]);

        String[] arrayOfStrings = new String[10];
        assert(arrayOfStrings[0] == null);
        assert(arrayOfStrings.Length == 10);

        arrayOfStrings = new String[] { "one", "two" };

        byte[,] arrayOfBytes = { {0,0,0},
                                 {0,1,2},
                                 {0,2,4}};
        assert(arrayOfBytes[2,2] == 4);
    }
    void collections()
    {
        IList ailist = new ArrayList();
        ailist.Add("zero"); ailist.Add("one"); ailist.Add("three");
        ailist[2] = "two";
        assert(ailist[2].Equals("two"));
        ailist.Remove("two");
        ((ArrayList)ailist).Sort();
        for(IEnumerator aie = ((ArrayList)ailist).GetEnumerator(); aie.MoveNext(); )
            ;
        foreach(String astring in ailist)
            ;

        IDictionary aidictionary = new Hashtable();
        aidictionary.Add("key", "value");
        assert(aidictionary["key"].Equals("value"));

        // Set not available.
    }
    void comparison()
    {
        int aint1 = 1;
        int aint2 = 2;
        int aint = 1;
        String astring1 = "one";
        String astring2 = "two";
        String astring = astring1;

        assert(aint == aint1);
        assert(aint1 != aint2);
        assert(astring == astring1);
        assert(astring1 == String.Copy("one"));         // For strings == is overloaded to compare values.
        assert(!astring1.Equals(astring2));
        assert(astring1.Equals(String.Copy("one")));

        astring = null;
        if (astring != null && astring.Length > 0)      // Conditional evaluation.
            assert(false);

        if (aint2 < 0 || 1 < aint2)
            assert(true);
    }
    void control()
    {
        if (true)
            assert(true);
        else
            assert(false);
        /////
        switch ('b') {
            case 'a':
                assert(false);
                break;
            case 'b':
                assert(true);
                break;
            default:
                assert(false);
                break;
        }
        /////
        for (int ai1 = 0; ai1 < 10; ai1++)
            assert(true);
        /////
        int ai = 0;
        while (ai < 10) {
            assert(true);
            ai++;
        }

        do
            ai--;
        while (ai > 0);

        for (int x = 0; x < 10; x++)        // Labeled break/continue not available.
            for (int y = 0; y < 10; y++)
                if (x == 9)
                    break;
                else
                    continue;
    }
    void filesStreamsAndExceptions()
    {
        FileInfo afileinfo = new FileInfo("list.txt");
        try {
            StreamWriter asw = new StreamWriter("list.txt");
            asw.WriteLine("line");
            asw.WriteLine("line");
            asw.Close();

            assert(afileinfo.Exists);

            StreamReader asr = new StreamReader("list.txt");
            String astringLine;
            while ((astringLine = asr.ReadLine()) != null)
                assert(astringLine.Equals("line"));
            asr.Close();
        } catch (IOException aexception) {
            System.Console.WriteLine(aexception.Message);
            throw new NotSupportedException();
        }
        finally {
            afileinfo.Delete();
        }
    }
    void numbersAndMath()
    {
        assert(Int32.Parse("123") == 123);
        assert(123.ToString().Equals("123"));

        assert(Math.PI.ToString("n3").Equals("3.142"));

        assert(Int32.MaxValue < Int64.MaxValue);

        assert(Math.Abs(Math.Sin(0) - 0) <= Double.Epsilon);
        assert(Math.Abs(Math.Cos(0) - 1) <= Double.Epsilon);
        assert(Math.Abs(Math.Tan(0) - 0) <= Double.Epsilon);

        assert(Math.Abs(Math.Sqrt(4) - 2) <= Double.Epsilon);
        assert(Math.Abs(Math.Pow(3,3) - 27) <= Double.Epsilon);

        assert(Math.Max(0,1) == 1);
        assert(Math.Min(0,1) == 0);

        assert(Math.Abs(Math.Ceiling(9.87) - 10.0) <= Double.Epsilon);
        assert(Math.Abs(Math.Floor(9.87) - 9.0) <= Double.Epsilon);
        assert(Math.Round(9.87) == 10);

        Random arandom = new Random();
        double adouble = arandom.NextDouble();
        assert(0.0 <= adouble && adouble < 1.0);
        int aint = arandom.Next(10);
        assert(0 <= aint && aint < 10);
    }
    enum Season: byte { Spring=0, Summer, Fall, Winter };

    void primitivesAndConstants()
    {
        bool abool = false;
        char achar = 'A';           // 16 bits, Unicode

        byte abyte = 0x0;           // 8 bits, unsigned, hex constant
        sbyte asbyte = 0;           // 8 bits, signed

        short ashort = 0;           // 16 bits, signed
        ushort aushort = 0;         // 16 bits, unsigned

        int aint = 0;               // 32 bits, signed
        uint aunit = 0;             // 32 bits, unsigned

        long along = 0L;            // 64 bits, signed
        ulong aulong = 0;           // 64 bits, unsigned

        float afloat = 0.0F;        // 32 bits
        double adouble = 0.0;       // 64 bits

        decimal adecimal = 0;       // 128 bits, financial calculations

        Season aseason = Season.Fall;
        assert((byte)aseason == 2);
    }
    void runtimeTyping()
    {
        assert(new int[] { 1 } is int[]);
        assert(new ArrayList() is ArrayList);

        assert((new ArrayList()).GetType() == typeof(ArrayList));
        assert(typeof(Int32) is Type);      // Type of primitive type.

        assert(Type.GetType("System.Collections.ArrayList") == typeof(ArrayList));
    }
    void strings()
    {
        String astring1 = "one";
        String astring2 = "TWO";

        assert((astring1 + "/" + astring2).Equals("one/TWO"));
        assert(astring2.ToLower().Equals("two"));   // Equals ignoring case not available.
        assert(astring1.Length == 3);
        assert(astring1.Substring(0,2).Equals("on"));
        assert(astring1[2] == 'e');
        assert(astring1.ToUpper().Equals("ONE"));
        assert(astring2.ToLower().Equals("two"));
        assert(astring1.CompareTo("p") < 0);
        assert(astring1.IndexOf('e') == 2);
        assert(astring1.IndexOf("ne") == 1);
        assert(astring1.Trim().Length == astring1.Length);

        assert(Char.IsDigit('1'));
        assert(Char.IsLetter('a'));
        assert(Char.IsWhiteSpace('\t'));
        assert(Char.ToLower('A') == 'a');
        assert(Char.ToUpper('a') == 'A');
    }

    private void assert(bool abool)
    {
        if (!abool)
            throw new Exception("assert failed");
    }
 }
}


using System;
using System.Runtime.InteropServices;
using System.Text;
using HANDLE = System.IntPtr;
using HWND = System.IntPtr;
namespace Win32
{
public struct OVERLAPPED
{
public int Internal;
public int
InternalHigh;
public int offset;
public int
OffsetHigh;
public HANDLE hEvent;
}
public
struct SECURITY_ATTRIBUTES
{
public int
nLength;
public int lpSecurityDescriptor;
public
int bInheritHandle;
}
public struct PROCESS_INFORMATION
{
public HANDLE hProcess;
public HANDLE
hThread;
public int dwProcessId;
public int
dwThreadId;
}
public struct COMMPROP
{
public short wPacketLength;
public
short wPacketVersion;
public int
dwServiceMask;
public int dwReserved1;
public int
dwMaxTxQueue;
public int dwMaxRxQueue;
public int
dwMaxBaud;
public int dwProvSubType;
public int
dwProvCapabilities;
public int
dwSettableParams;
public int
dwSettableBaud;
public short wSettableData;
public
short wSettableStopParity;
public int
dwCurrentTxQueue;
public int
dwCurrentRxQueue;
public int dwProvSpec1;
public
int dwProvSpec2;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=1)] public short[] wcProvChar;
}
public struct
COMSTAT
{
public int fBitFields;
public
int cbInQue;
public int cbOutQue;
}
public
struct DCB
{
public int
DCBlength;
public int BaudRate;
public int
fBitFields;
public short wReserved;
public short
XonLim;
public short XoffLim;
public byte
ByteSize;
public byte Parity;
public byte
StopBits;
public byte XonChar;
public byte
XoffChar;
public byte ErrorChar;
public byte
EofChar;
public byte EvtChar;
public short
wReserved1;
}
public struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public
int ReadTotalTimeoutMultiplier;
public int
ReadTotalTimeoutConstant;
public int
WriteTotalTimeoutMultiplier;
public int
WriteTotalTimeoutConstant;
}
public struct SYSTEM_INFO
{
public int dwOemID;
public int
dwPageSize;
public int
lpMinimumApplicationAddress;
public int
lpMaximumApplicationAddress;
public int
dwActiveProcessorMask;
public int
dwNumberOrfProcessors;
public int
dwProcessorType;
public int
dwAllocationGranularity;
public int
dwReserved;
}
#region Global Memory
Flags
#endregion
public struct MEMORYSTATUS
{
public int dwLength;
public int
dwMemoryLoad;
public int dwTotalPhys;
public int
dwAvailPhys;
public int dwTotalPageFile;
public
int dwAvailPageFile;
public int
dwTotalVirtual;
public int
dwAvailVirtual;
}
public struct GENERIC_MAPPING
{
public int GenericRead;
public int
GenericWrite;
public int GenericExecute;
public
int GenericAll;
}
public struct LUID
{
public int LowPart;
public int
HighPart;
}
public struct LUID_AND_ATTRIBUTES
{
public LUID pLuid;
public int
Attributes;
}
public struct ACL
{
public byte AclRevision;
public byte
Sbz1;
public short AclSize;
public short
AceCount;
public short Sbz2;
}
public struct
ACE_HEADER
{
public byte AceType;
public
byte AceFlags;
public int AceSize;
}
public
struct ACCESS_ALLOWED_ACE
{
public ACE_HEADER
Header;
public int Mask;
public int
SidStart;
}
public struct ACCESS_DENIED_ACE
{
public ACE_HEADER Header;
public int
Mask;
public int SidStart;
}
public struct
SYSTEM_AUDIT_ACE
{
public ACE_HEADER
Header;
public int Mask;
public int
SidStart;
}
public struct SYSTEM_ALARM_ACE
{
public ACE_HEADER Header;
public int
Mask;
public int SidStart;
}
public struct
ACL_REVISION_INFORMATION
{
public int
AclRevision;
}
public struct ACL_SIZE_INFORMATION
{
public int AceCount;
public int
AclBytesInUse;
public int
AclBytesFree;
}
public struct SECURITY_DESCRIPTOR
{
public byte Revision;
public byte
Sbz1;
public int Control;
public int
Owner;
public int Group;
public ACL
Sacl;
public ACL Dacl;
}
public struct
PRIVILEGE_SET
{
public int
PrivilegeCount;
public int
Control;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public LUID_AND_ATTRIBUTES[] Privilege;
}
public struct
EXCEPTION_RECORD
{
public int
ExceptionCode;
public int ExceptionFlags;
public
int pExceptionRecord;
public int
ExceptionAddress;
public int
NumberParameters;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=15)] public int [] ExceptionInformation;
}
public
struct EXCEPTION_DEBUG_INFO
{
public EXCEPTION_RECORD
pExceptionRecord;
public int
dwFirstChance;
}
public struct CREATE_THREAD_DEBUG_INFO
{
public HANDLE hThread;
public int
lpThreadLocalBase;
public int
lpStartAddress;
}
public struct CREATE_PROCESS_DEBUG_INFO
{
public HANDLE hFile;
public HANDLE
hProcess;
public HANDLE hThread;
public int
lpBaseOfImage;
public int
dwDebugInfoFileOffset;
public int
nDebugInfoSize;
public int
lpThreadLocalBase;
public int
lpStartAddress;
public int lpImageName;
public
short fUnicode;
}
public struct EXIT_THREAD_DEBUG_INFO
{
public int dwExitCode;
}
public
struct EXIT_PROCESS_DEBUG_INFO
{
public int
dwExitCode;
}
public struct LOAD_DLL_DEBUG_INFO
{
public HANDLE hFile;
public int
lpBaseOfDll;
public int
dwDebugInfoFileOffset;
public int
nDebugInfoSize;
public int lpImageName;
public
short fUnicode;
}
public struct UNLOAD_DLL_DEBUG_INFO
{
public int lpBaseOfDll;
}
public
struct OUTPUT_DEBUG_STRING_INFO
{
public string
lpDebugStringData;
public short fUnicode;
public
short nDebugStringLength;
}
public struct RIP_INFO
{
public int dwError;
public int
dwType;
}
public struct OFSTRUCT
{
public byte cBytes;
public byte
fFixedDisk;
public short nErrCode;
public short
Reserved1;
public short
Reserved2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=128)]
public byte[] szPathName;
}
public struct CRITICAL_SECTION
{
public int pDebugInfo;
public int
LockCount;
public int RecursionCount;
public int
pOwningThread;
public int pLockSemaphore;
public
int Reserved;
}
public struct BY_HANDLE_FILE_INFORMATION
{
public int dwFileAttributes;
public
FILETIME ftCreationTime;
public FILETIME
ftLastAccessTime;
public FILETIME
ftLastWriteTime;
public int
dwVolumeSerialNumber;
public int
nFileSizeHigh;
public int nFileSizeLow;
public int
nNumberOfLinks;
public int nFileIndexHigh;
public
int nFileIndexLow;
}
public struct MEMORY_BASIC_INFORMATION
{
public int BaseAddress;
public int
AllocationBase;
public int
AllocationProtect;
public int RegionSize;
public
int State;
public int Protect;
public int
lType;
}
public struct EVENTLOGRECORD
{
public int Length;
public int
Reserved;
public int RecordNumber;
public int
TimeGenerated;
public int TimeWritten;
public
int EventID;
public short EventType;
public short
NumStrings;
public short EventCategory;
public
short ReservedFlags;
public int ClosingRecordNumber;
public int StringOffset;
public int
UserSidLength;
public int UserSidOffset;
public
int DataLength;
public int DataOffset;
}
public struct TOKEN_GROUPS
{
public int
GroupCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
 public SID_AND_ATTRIBUTES[] Groups;
}
public struct
TOKEN_PRIVILEGES
{
public int
PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=1)] public LUID_AND_ATTRIBUTES[]
Privileges;
}
public struct CONTEXT
{
public double FltF0;
public double
FltF1;
public double FltF2;
public double
FltF3;
public double FltF4;
public double
FltF5;
public double FltF6;
public double
FltF7;
public double FltF8;
public double
FltF9;
public double FltF10;
public double
FltF11;
public double FltF12;
public double
FltF13;
public double FltF14;
public double
FltF15;
public double FltF16;
public double
FltF17;
public double FltF18;
public double
FltF19;
public double FltF20;
public double
FltF21;
public double FltF22;
public double
FltF23;
public double FltF24;
public double
FltF25;
public double FltF26;
public double
FltF27;
public double FltF28;
public double
FltF29;
public double FltF30;
public double
FltF31;
public double IntV0;
public double
IntT0;
public double IntT1;
public double
IntT2;
public double IntT3;
public double
IntT4;
public double IntT5;
public double
IntT6;
public double IntT7;
public double
IntS0;
public double IntS1;
public double
IntS2;
public double IntS3;
public double
IntS4;
public double IntS5;
public double
IntFp;
public double IntA0;
public double
IntA1;
public double IntA2;
public double
IntA3;
public double IntA4;
public double
IntA5;
public double IntT8;
public double
IntT9;
public double IntT10;
public double
IntT11;
public double IntRa;
public double
IntT12;
public double IntAt;
public double
IntGp;
public double IntSp;
public double
IntZero;
public double Fpcr;
public double
SoftFpcr;
public double Fir;
public int
Psr;
public int
ContextFlags;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public int []Fill;
}
public struct EXCEPTION_POINTERS
{
public EXCEPTION_RECORD
pExceptionRecord;
public CONTEXT
ContextRecord;
}
public struct LDT_BYTES
{
public byte BaseMid;
public byte
Flags1;
public byte Flags2;
public byte
BaseHi;
}
public struct LDT_ENTRY
{
public short LimitLow;
public short
BaseLow;
public int HighWord;
}
public
struct TIME_ZONE_INFORMATION
{
public int
Bias;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)] public
short[] StandardName;
public SYSTEMTIME
StandardDate;
public int
StandardBias;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public short[] DaylightName;
public SYSTEMTIME
DaylightDate;
public int DaylightBias;
}
public
struct WIN32_STREAM_ID
{
public int
dwStreamID;
public int dwStreamAttributes;
public
int dwStreamSizeLow;
public int
dwStreamSizeHigh;
public int
dwStreamNameSize;
public byte
cStreamName;
}
public struct STARTUPINFO
{
public int cb;
public string
lpReserved;
public string lpDesktop;
public string
lpTitle;
public int dwX;
public int
dwY;
public int dwXSize;
public int
dwYSize;
public int dwXCountChars;
public int
dwYCountChars;
public int dwFillAttribute;
public
int dwFlags;
public short wShowWindow;
public
short cbReserved2;
public int lpReserved2;
public
HANDLE hStdInput;
public HANDLE hStdOutput;
public
HANDLE hStdError;
}
public struct CPINFO
{
public int MaxCharSize;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=Kernel.MAX_DEFAULTCHAR)] public byte[] DefaultChar;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=Kernel.MAX_LEADBYTES)] public byte[] LeadByte;
}
public struct NUMBERFMT
{
public
int NumDigits;
public int LeadingZero;
public
int Grouping;
public string lpDecimalSep;
public
string lpThousandSep;
public int NegativeOrder;
}
public struct CURRENCYFMT
{
public
int NumDigits;
public int LeadingZero;
public
int Grouping;
public string lpDecimalSep;
public
string lpThousandSep;
public int NegativeOrder;
public int PositiveOrder;
public string
lpCurrencySymbol;
}
public struct COORD
{
public short x;
public short
y;
}
public struct SMALL_RECT
{
public short Left;
public short
Top;
public short Right;
public short
Bottom;
}
public struct KEY_EVENT_RECORD
{
public int bKeyDown;
public short
wRepeatCount;
public short wVirtualKeyCode;
public
short wVirtualScanCode;
public byte uChar;
public
int dwControlKeyState;
}
public struct MOUSE_EVENT_RECORD
{
public COORD dwMousePosition;
public
int dwButtonState;
public int
dwControlKeyState;
public int
dwEventFlags;
}
public struct WINDOW_BUFFER_SIZE_RECORD
{
public COORD dwSize;
}
public
struct MENU_EVENT_RECORD
{
public int
dwCommandId;
}
public struct FOCUS_EVENT_RECORD
{
public int bSetFocus;
}
public
struct CHAR_INFO
{
public short
Char;
public short Attributes;
}
public struct
CONSOLE_SCREEN_BUFFER_INFO
{
public COORD
dwSize;
public COORD dwCursorPosition;
public
short wAttributes;
public SMALL_RECT
srWindow;
public COORD
dwMaximumWindowSize;
}
public struct CONSOLE_CURSOR_INFO
{
public int dwSize;
public int
bVisible;
}
public struct SID_IDENTIFIER_AUTHORITY
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)]
public byte[] Value;
}
public struct SID_AND_ATTRIBUTES
{
public int Sid;
public int
Attributes;
}
public struct WIN32_FIND_DATA
{
public int dwFileAttributes;
public
FILETIME ftCreationTime;
public FILETIME ftLastAccessTime;
public FILETIME ftLastWriteTime;
public int
nFileSizeHigh;
public int nFileSizeLow;
public int
dwReserved0;
public int
dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr,
SizeConst=Kernel.MAX_PATH)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
public string cAlternate;
}
public struct
COMMCONFIG
{
public int dwSize;
public
short wVersion;
public short wReserved;
public DCB
dcbx;
public int dwProviderSubType;
public int
dwProviderOffset;
public int
dwProviderSize;
public byte
wcProviderData;
}
public struct SERVICE_STATUS
{
public int dwServiceType;
public int
dwCurrentState;
public int
dwControlsAccepted;
public int
dwWin32ExitCode;
public int
dwServiceSpecificExitCode;
public int
dwCheckPoint;
public int dwWaitHint;
}
public
struct ENUM_SERVICE_STATUS
{
public string
lpServiceName;
public string lpDisplayName;
public
SERVICE_STATUS ServiceStatus;
}
public struct
QUERY_SERVICE_LOCK_STATUS
{
public int
fIsLocked;
public string lpLockOwner;
public int
dwLockDuration;
}
public struct QUERY_SERVICE_CONFIG
{
public int dwServiceType;
public int
dwStartType;
public int dwErrorControl;
public
string lpBinaryPathName;
public string
lpLoadOrderGroup;
public int dwTagId;
public
string lpDependencies;
public string
lpServiceStartName;
public string
lpDisplayName;
}
public struct SERVICE_TABLE_ENTRY
{
public string lpServiceName;
public
int lpServiceProc;
}
public struct LARGE_INTEGER
{
public int lowpart;
public int
highpart;
}
public struct PERF_DATA_BLOCK
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=4)]
public string Signature;
public int
LittleEndian;
public int Version;
public int
Revision;
public int TotalByteLength;
public int
HeaderLength;
public int NumObjectTypes;
public
int DefaultObject;
public SYSTEMTIME
SystemTime;
public LARGE_INTEGER PerfTime;
public
LARGE_INTEGER PerfFreq;
public LARGE_INTEGER
PerTime100nSec;
public int
SystemNameLength;
public int
SystemNameOffset;
}
public struct PERF_OBJECT_TYPE
{
public int TotalByteLength;
public int
DefinitionLength;
public int HeaderLength;
public
int ObjectNameTitleIndex;
public string
ObjectNameTitle;
public int
ObjectHelpTitleIndex;
public string
ObjectHelpTitle;
public int DetailLevel;
public
int NumCounters;
public int DefaultCounter;
public
int NumInstances;
public int CodePage;
public
LARGE_INTEGER PerfTime;
public LARGE_INTEGER
PerfFreq;
}
public struct PERF_COUNTER_DEFINITION
{
public int ByteLength;
public int
CounterNameTitleIndex;
public string
CounterNameTitle;
public int
CounterHelpTitleIndex;
public string
CounterHelpTitle;
public int DefaultScale;
public
int DetailLevel;
public int CounterType;
public
int CounterSize;
public int
CounterOffset;
}
public struct PERF_INSTANCE_DEFINITION
{
public int ByteLength;
public int
ParentObjectTitleIndex;
public int
ParentObjectInstance;
public int UniqueID;
public
int NameOffset;
public int NameLength;
}
public
struct PERF_COUNTER_BLOCK
{
public int
ByteLength;
}
public struct OSVERSIONINFO
{
public int dwOSVersionInfoSize;
public
int dwMajorVersion;
public int
dwMinorVersion;
public int dwBuildNumber;
public
int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr,
SizeConst=128)] public string szCSDVersion;
}
public struct
SYSTEM_POWER_STATUS
{
public byte
ACLineStatus;
public byte BatteryFlag;
public byte
BatteryLifePercent;
public byte Reserved1;
public
int BatteryLifeTime;
public int
BatteryFullLifeTime;
}
public abstract class AdvApi
{
[DllImport("AdvApi32")] public static extern int ImpersonateLoggedOnUser(HANDLE hToken);
[DllImport("advapi32")] public static extern int IsTextUnicode(IntPtr lpBuffer, int cb, ref int lpi);
[DllImport("advapi32")] public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref int phToken);
[DllImport("advapi32")] public static extern int NotifyChangeEventLog(HANDLE hEventLog, HANDLE hEvent);
[DllImport("advapi32")] public static extern int SetThreadToken(int Thread, int Token);
[DllImport("advapi32")] public static extern Byte GetSidSubAuthorityCount(IntPtr pSid);
[DllImport("advapi32")] public static extern SID_IDENTIFIER_AUTHORITY GetSidIdentifierAuthority(IntPtr pSid);
[DllImport("advapi32")] public static extern int AbortSystemShutdown(string lpMachineName);
[DllImport("advapi32")] public static extern int AccessCheck(ref SECURITY_DESCRIPTOR pSecurityDescriptor, int ClientToken, int DesiredAccess, GENERIC_MAPPING GenericMapping, PRIVILEGE_SET PrivilegeSet, int PrivilegeSetLength, int GrantedAccess, int Status);
[DllImport("advapi32")] public static extern int AccessCheckAndAuditAlarm(string SubsystemName, IntPtr HandleId, string ObjectTypeName, string ObjectName, SECURITY_DESCRIPTOR SecurityDescriptor, int DesiredAccess, GENERIC_MAPPING GenericMapping, int ObjectCreation, int GrantedAccess, int AccessStatus, ref int pfGenerateOnClose);
[DllImport("advapi32")] public static extern int AddAccessAllowedAce(ref ACL pAcl, int dwAceRevision, int AccessMask, IntPtr pSid);
[DllImport("advapi32")] public static extern int AddAccessDeniedAce(ref ACL pAcl, int dwAceRevision, int AccessMask, IntPtr pSid);
[DllImport("advapi32")] public static extern int AddAce(ref ACL pAcl, int dwAceRevision, int dwStartingAceIndex, IntPtr pAceList, int nAceListLength);
[DllImport("advapi32")] public static extern int AddAuditAccessAce(ref ACL pAcl, int dwAceRevision, int dwAccessMask, IntPtr pSid, int bAuditSuccess, int bAuditFailure);
[DllImport("advapi32")] public static extern int AdjustTokenGroups(int TokenHandle, int ResetToDefault, TOKEN_GROUPS NewState, int BufferLength, TOKEN_GROUPS PreviousState, int ReturnLength);
[DllImport("advapi32")] public static extern int AdjustTokenPrivileges(int TokenHandle, int DisableAllPrivileges, TOKEN_PRIVILEGES NewState, int BufferLength, TOKEN_PRIVILEGES PreviousState, int ReturnLength);
[DllImport("advapi32")] public static extern int AllocateAndInitializeSid(ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, Byte nSubAuthorityCount, int nSubAuthority0, int nSubAuthority1, int nSubAuthority2, int nSubAuthority3, int nSubAuthority4, int nSubAuthority5, int nSubAuthority6, int nSubAuthority7, ref int lpPSid);
[DllImport("advapi32")] public static extern int AllocateLocallyUniqueId(LARGE_INTEGER Luid);
[DllImport("advapi32")] public static extern int AreAllAccessesGranted(int GrantedAccess, int DesiredAccess);
[DllImport("advapi32")] public static extern int AreAnyAccessesGranted(int GrantedAccess, int DesiredAccess);
[DllImport("advapi32")] public static extern int BackupEventLog(HANDLE hEventLog, string lpBackupFileName);
[DllImport("advapi32")] public static extern int ChangeServiceConfig(HANDLE hService, int dwServiceType, int dwStartType, int dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, ref int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword, string lpDisplayName);
[DllImport("advapi32")] public static extern int ClearEventLog(HANDLE hEventLog, string lpBackupFileName);
[DllImport("advapi32")] public static extern int CloseEventLog(HANDLE hEventLog);
[DllImport("advapi32")] public static extern int CloseServiceHandle(HANDLE hSCObject);
[DllImport("advapi32")] public static extern int ControlService(HANDLE hService, int dwControl, ref SERVICE_STATUS lpServiceStatus);
[DllImport("advapi32")] public static extern int CopySid(int nDestinationSidLength, IntPtr pDestinationSid, IntPtr pSourceSid);
[DllImport("advapi32")] public static extern int CreatePrivateObjectSecurity(ref SECURITY_DESCRIPTOR ParentDescriptor, SECURITY_DESCRIPTOR CreatorDescriptor, SECURITY_DESCRIPTOR NewDescriptor, int IsDirectoryObject, int Token, GENERIC_MAPPING GenericMapping);
[DllImport("advapi32")] public static extern int CreateProcessAsUser(HANDLE hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, int bInheritHandles, int dwCreationFlags, string lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32")] public static extern int CreateService(HANDLE hSCManager, string lpServiceName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, ref int lpdwTagId, string lpDependencies, string lp, string lpPassword);
[DllImport("advapi32")] public static extern int DeleteAce(ref ACL pAcl, int dwAceIndex);
[DllImport("advapi32")] public static extern int DeleteService(HANDLE hService);
[DllImport("advapi32")] public static extern int DeregisterEventSource(HANDLE hEventLog);
[DllImport("advapi32")] public static extern int DestroyPrivateObjectSecurity(ref SECURITY_DESCRIPTOR ObjectDescriptor);
[DllImport("advapi32")] public static extern int DuplicateToken(int ExistingTokenHandle, short ImpersonationLevel, int DuplicateTokenHandle);
[DllImport("advapi32")] public static extern int EnumDependentServices(HANDLE hService, int dwServiceState, ref ENUM_SERVICE_STATUS lpServices, int cbBufSize, ref int pcbBytesNeeded, ref int lpServicesReturned);
[DllImport("advapi32")] public static extern int EnumServicesStatus(HANDLE hSCManager, int dwServiceType, int dwServiceState, ref ENUM_SERVICE_STATUS lpServices, int cbBufSize, ref int pcbBytesNeeded, ref int lpServicesReturned, ref int lpResumeHandle);
[DllImport("advapi32")] public static extern int EqualPrefixSid(IntPtr pSid1, IntPtr pSid2);
[DllImport("advapi32")] public static extern int EqualSid(IntPtr pSid1, IntPtr pSid2);
[DllImport("advapi32")] public static extern int FindFirstFreeAce(ref ACL pAcl, ref int pAce);
[DllImport("advapi32")] public static extern int GetAce(ref ACL pAcl, int dwAceIndex, IntPtr pAce);
[DllImport("advapi32")] public static extern int GetAclInformation(ref ACL pAcl, IntPtr pAclInformation, int nAclInformationLength, short dwAclInformationClass);
[DllImport("advapi32")] public static extern int GetFileSecurity(string lpFileName, int RequestedInformation, ref SECURITY_DESCRIPTOR pSecurityDescriptor, int nLength, ref int lpnLengthNeeded);
[DllImport("advapi32")] public static extern int GetKernelObjectSecurity(HANDLE handle, int RequestedInformation, ref SECURITY_DESCRIPTOR pSecurityDescriptor, int nLength, ref int lpnLengthNeeded);
[DllImport("advapi32")] public static extern int GetLengthSid(IntPtr pSid);
[DllImport("advapi32")] public static extern int GetNumberOfEventLogRecords(HANDLE hEventLog, int NumberOfRecords);
[DllImport("advapi32")] public static extern int GetOldestEventLogRecord(HANDLE hEventLog, int OldestRecord);
[DllImport("advapi32")] public static extern int GetPrivateObjectSecurity(ref SECURITY_DESCRIPTOR ObjectDescriptor, int SecurityInformation, SECURITY_DESCRIPTOR ResultantDescriptor, int DescriptorLength, int ReturnLength);
[DllImport("advapi32")] public static extern int GetSecurityDescriptorControl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, short pControl, ref int lpdwRevision);
[DllImport("advapi32")] public static extern int GetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, ref int lpbDaclPresent, ref ACL pDacl, ref int lpbDaclDefaulted);
[DllImport("advapi32")] public static extern int GetSecurityDescriptorGroup(ref SECURITY_DESCRIPTOR pSecurityDescriptor, IntPtr pGroup, ref int lpbGroupDefaulted);
[DllImport("advapi32")] public static extern int GetSecurityDescriptorLength(ref SECURITY_DESCRIPTOR pSecurityDescriptor);
[DllImport("advapi32")] public static extern int GetSecurityDescriptorOwner(ref SECURITY_DESCRIPTOR pSecurityDescriptor, IntPtr pOwner, ref int lpbOwnerDefaulted);
[DllImport("advapi32")] public static extern int GetSecurityDescriptorSacl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, ref int lpbSaclPresent, ref ACL pSacl, ref int lpbSaclDefaulted);
[DllImport("advapi32")] public static extern int GetServiceDisplayName(HANDLE hSCManager, string lpServiceName, StringBuilder lpDisplayName, ref int cchBuffer);
[DllImport("advapi32")] public static extern int GetServiceKeyName(HANDLE hSCManager, string lpDisplayName, StringBuilder lpServiceName, ref int cchBuffer);
[DllImport("advapi32")] public static extern int GetSidLengthRequired(Byte nSubAuthorityCount);
[DllImport("advapi32")] public static extern int GetSidSubAuthority(IntPtr pSid, int nSubAuthority);
[DllImport("advapi32")] public static extern int GetTokenInformation(int TokenHandle, short TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, int ReturnLength);
[DllImport("advapi32")] public static extern int GetUserName(StringBuilder lpBuffer, int nSize);
[DllImport("advapi32")] public static extern int ImpersonateNamedPipeClient(HANDLE hNamedPipe);
[DllImport("advapi32")] public static extern int ImpersonateSelf(short ImpersonationLevel);
[DllImport("advapi32")] public static extern int InitializeAcl(ref ACL pAcl, int nAclLength, int dwAclRevision);
[DllImport("advapi32")] public static extern int InitializeSecurityDescriptor(ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision);
[DllImport("advapi32")] public static extern int InitializeSid(IntPtr Sid, ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, Byte nSubAuthorityCount);
[DllImport("advapi32")] public static extern int InitiateSystemShutdown(string lpMachineName, string lpMessage, int dwTimeout, int bForceAppsClosed, int bRebootAfterShutdown);
[DllImport("advapi32")] public static extern int IsValidAcl(ref ACL pAcl);
[DllImport("advapi32")] public static extern int IsValidSecurityDescriptor(ref SECURITY_DESCRIPTOR pSecurityDescriptor);
[DllImport("advapi32")] public static extern int IsValidSid(IntPtr pSid);
[DllImport("advapi32")] public static extern int LockServiceDatabase(HANDLE hSCManager);
[DllImport("advapi32")] public static extern int LookupAccountName(string lpSystemName, string lpAccountName, int Sid, int cbSid, string ReferencedDomainName, int cbReferencedDomainName, int peUse);
[DllImport("advapi32")] public static extern int LookupAccountSid(string lpSystemName, IntPtr Sid, string name, int cbName, string ReferencedDomainName, int cbReferencedDomainName, int peUse);
[DllImport("advapi32")] public static extern int LookupPrivilegeDisplayName(string lpSystemName, string lpName, string lpDisplayName, int cbDisplayName, ref int lpLanguageID);
[DllImport("advapi32")] public static extern int LookupPrivilegeName(string lpSystemName, ref LARGE_INTEGER lpLuid, string lpName, int cbName);
[DllImport("advapi32")] public static extern int LookupPrivilegeValue(string lpSystemName, string lpName, ref LARGE_INTEGER lpLuid);
[DllImport("advapi32")] public static extern int MakeAbsoluteSD(ref SECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor, ref SECURITY_DESCRIPTOR pAbsoluteSecurityDescriptor, ref int lpdwAbsoluteSecurityDescriptorSize, ref ACL pDacl, ref int lpdwDaclSize, ref ACL pSacl, ref int lpdwSaclSize, IntPtr pOwner, ref int lpdwOwnerSize, IntPtr pPrimaryGroup, ref int lpdwPrimaryGroupSize);
[DllImport("advapi32")] public static extern int MakeSelfRelativeSD(ref SECURITY_DESCRIPTOR pAbsoluteSecurityDescriptor, ref SECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor, ref int lpdwBufferLength);
[DllImport("advapi32")] public static extern int NotifyBootConfigStatus(int BootAcceptable);
[DllImport("advapi32")] public static extern int ObjectCloseAuditAlarm(string SubsystemName, IntPtr HandleId, int GenerateOnClose);
[DllImport("advapi32")] public static extern int ObjectPrivilegeAuditAlarm(string SubsystemName, IntPtr HandleId, int ClientToken, int DesiredAccess, PRIVILEGE_SET Privileges, int AccessGranted);
[DllImport("advapi32")] public static extern int OpenBackupEventLog(string lpUNCServerName, string lpFileName);
[DllImport("advapi32")] public static extern int OpenEventLog(string lpUNCServerName, string lpSourceName);
[DllImport("advapi32")] public static extern int OpenSCManager(string lpMachineName, string lpDatabaseName, int dwDesiredAccess);
[DllImport("advapi32")] public static extern int OpenService(HANDLE hSCManager, string lpServiceName, int dwDesiredAccess);
[DllImport("advapi32")] public static extern int OpenThreadToken(int ThreadHandle, int DesiredAccess, int OpenAsSelf, int TokenHandle);
[DllImport("advapi32")] public static extern int PrivilegeCheck(int ClientToken, PRIVILEGE_SET RequiredPrivileges, ref int pfResult);
[DllImport("advapi32")] public static extern int PrivilegedServiceAuditAlarm(string SubsystemName, string ServiceName, int ClientToken, PRIVILEGE_SET Privileges, int AccessGranted);
[DllImport("advapi32")] public static extern int QueryServiceConfig(HANDLE hService, ref QUERY_SERVICE_CONFIG lpServiceConfig, int cbBufSize, ref int pcbBytesNeeded);
[DllImport("advapi32")] public static extern int QueryServiceLockStatus(HANDLE hSCManager, ref QUERY_SERVICE_LOCK_STATUS lpLockStatus, int cbBufSize, ref int pcbBytesNeeded);
[DllImport("advapi32")] public static extern int QueryServiceObjectSecurity(HANDLE hService, int dwSecurityInformation, IntPtr lpSecurityDescriptor, int cbBufSize, ref int pcbBytesNeeded);
[DllImport("advapi32")] public static extern int QueryServiceStatus(HANDLE hService, ref SERVICE_STATUS lpServiceStatus);
[DllImport("advapi32")] public static extern int ReadEventLog(HANDLE hEventLog, int dwReadFlags, int dwRecordOffset, ref EVENTLOGRECORD lpBuffer, int nNumberOfBytesToRead, ref int pnBytesRead, ref int pnMinNumberOfBytesNeeded);
[DllImport("advapi32")] public static extern int RegCloseKey(HANDLE hKey);
[DllImport("advapi32")] public static extern int RegConnectRegistry(string lpMachineName, HANDLE hKey, ref int phkResult);
[DllImport("advapi32")] public static extern int RegCreateKey(HANDLE hKey, string lpSubKey, ref int phkResult);
[DllImport("advapi32")] public static extern int RegCreateKeyEx(HANDLE hKey, string lpSubKey, int Reserved, string lpClass, int dwOptions, int samDesired, ref SECURITY_ATTRIBUTES lpSecurityAttributes, ref int phkResult, ref int lpdwDisposition);
[DllImport("advapi32")] public static extern int RegDeleteKey(HANDLE hKey, string lpSubKey);
[DllImport("advapi32")] public static extern int RegDeleteValue(HANDLE hKey, string lpValueName);
[DllImport("advapi32")] public static extern int RegEnumKey(HANDLE hKey, int dwIndex, string lpName, int cbName);
[DllImport("advapi32")] public static extern int RegEnumKeyEx(HANDLE hKey, int dwIndex, string lpName, ref int lpcbName, ref int lpReserved, string lpClass, ref int lpcbClass, ref FILETIME lpftLastWriteTime);
[DllImport("advapi32")] public static extern int RegEnumValue(HANDLE hKey, int dwIndex, string lpValueName, ref int lpcbValueName, ref int lpReserved, ref int lpType, Byte lpData, ref int lpcbData);
[DllImport("advapi32")] public static extern int RegFlushKey(HANDLE hKey);
[DllImport("advapi32")] public static extern int RegGetKeySecurity(HANDLE hKey, int SecurityInformation, ref SECURITY_DESCRIPTOR pSecurityDescriptor, ref int lpcbSecurityDescriptor);
[DllImport("advapi32")] public static extern int RegLoadKey(HANDLE hKey, string lpSubKey, string lpFile);
[DllImport("advapi32")] public static extern int RegNotifyChangeKeyValue(HANDLE hKey, int bWatchSubtree, int dwNotifyFilter, HANDLE hEvent, int fAsynchronus);
[DllImport("advapi32")] public static extern int RegOpenKey(HANDLE hKey, string lpSubKey, ref int phkResult);
[DllImport("advapi32")] public static extern int RegOpenKeyEx(HANDLE hKey, string lpSubKey, int ulOptions, int samDesired, ref int phkResult);
[DllImport("advapi32")] public static extern int RegQueryInfoKey(HANDLE hKey, string lpClass, ref int lpcbClass, ref int lpReserved, ref int lpcSubKeys, ref int lpcbMaxSubKeyLen, ref int lpcbMaxClassLen, ref int lpcValues, ref int lpcbMaxValueNameLen, ref int lpcbMaxValueLen, ref int lpcbSecurityDescriptor, ref FILETIME lpftLastWriteTime);
[DllImport("advapi32")] public static extern int RegQueryValue(HANDLE hKey, string lpSubKey, string lpValue, ref int lpcbValue);
[DllImport("advapi32")] public static extern int RegQueryValueEx(HANDLE hKey, string lpValueName, ref int lpReserved, ref int lpType, IntPtr lpData, ref int lpcbData);
[DllImport("advapi32")] public static extern int RegReplaceKey(HANDLE hKey, string lpSubKey, string lpNewFile, string lpOldFile);
[DllImport("advapi32")] public static extern int RegRestoreKey(HANDLE hKey, string lpFile, int dwFlags);
[DllImport("advapi32")] public static extern int RegSaveKey(HANDLE hKey, string lpFile, ref SECURITY_ATTRIBUTES lpSecurityAttributes);
[DllImport("advapi32")] public static extern int RegSetKeySecurity(HANDLE hKey, int SecurityInformation, ref SECURITY_DESCRIPTOR pSecurityDescriptor);
[DllImport("advapi32")] public static extern int RegSetValue(HANDLE hKey, string lpSubKey, int dwType, string lpData, int cbData);
[DllImport("advapi32")] public static extern int RegSetValueEx(HANDLE hKey, string lpValueName, int Reserved, int dwType, IntPtr lpData, int cbData);
[DllImport("advapi32")] public static extern int RegUnLoadKey(HANDLE hKey, string lpSubKey);
[DllImport("advapi32")] public static extern int RegisterEventSource(string lpUNCServerName, string lpSourceName);
[DllImport("advapi32")] public static extern int RegisterServiceCtrlHandler(string lpServiceName, ref int lpHandlerProc);
[DllImport("advapi32")] public static extern int ReportEvent(HANDLE hEventLog, int wType, int wCategory, int dwEventID, IntPtr lpUserSid, int wNumStrings, int dwDataSize, ref int lpStrings, IntPtr lpRawData);
[DllImport("advapi32")] public static extern int RevertToSelf();
[DllImport("advapi32")] public static extern int SetAclInformation(ref ACL pAcl, IntPtr pAclInformation, int nAclInformationLength, short dwAclInformationClass);
[DllImport("advapi32")] public static extern int SetFileSecurity(string lpFileName, int SecurityInformation, ref SECURITY_DESCRIPTOR pSecurityDescriptor);
[DllImport("advapi32")] public static extern int SetKernelObjectSecurity(HANDLE handle, int SecurityInformation, SECURITY_DESCRIPTOR SecurityDescriptor);
[DllImport("advapi32")] public static extern int SetPrivateObjectSecurity(int SecurityInformation, SECURITY_DESCRIPTOR ModificationDescriptor, SECURITY_DESCRIPTOR ObjectsSecurityDescriptor, GENERIC_MAPPING GenericMapping, int Token);
[DllImport("advapi32")] public static extern int SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, int bDaclPresent, ref ACL pDacl, int bDaclDefaulted);
[DllImport("advapi32")] public static extern int SetSecurityDescriptorGroup(ref SECURITY_DESCRIPTOR pSecurityDescriptor, IntPtr pGroup, int bGroupDefaulted);
[DllImport("advapi32")] public static extern int SetSecurityDescriptorOwner(ref SECURITY_DESCRIPTOR pSecurityDescriptor, IntPtr pOwner, int bOwnerDefaulted);
[DllImport("advapi32")] public static extern int SetSecurityDescriptorSacl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, int bSaclPresent, ref ACL pSacl, int bSaclDefaulted);
[DllImport("advapi32")] public static extern int SetServiceObjectSecurity(HANDLE hService, int dwSecurityInformation, IntPtr lpSecurityDescriptor);
[DllImport("advapi32")] public static extern int SetServiceStatus(HANDLE hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
[DllImport("advapi32")] public static extern int SetTokenInformation(int TokenHandle, short TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength);
[DllImport("advapi32")] public static extern int StartService(HANDLE hService, int dwNumServiceArgs, ref int lpServiceArgVectors);
[DllImport("advapi32")] public static extern int StartServiceCtrlDispatcher(ref SERVICE_TABLE_ENTRY lpServiceStartTable);
[DllImport("advapi32")] public static extern int UnlockServiceDatabase(IntPtr ScLock);
[DllImport("advapi32")] public static extern void FreeSid(IntPtr pSid);
[DllImport("advapi32")] public static extern void MapGenericMask(int AccessMask, GENERIC_MAPPING GenericMapping);
[DllImport("advapi32")] public static extern int GetUserNameW(Byte lpBuffer, int nSize);
[DllImport("advapi32")] public static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, int TokenHandle);
}
public abstract class Version
{
[DllImport("version")] public static extern int GetFileVersionInfo(string lptstrFilename, int dwHandle, int dwLen, IntPtr lpData);
[DllImport("version")] public static extern int GetFileVersionInfoSize(string lptstrFilename, ref int lpdwHandle);
[DllImport("version")] public static extern int VerFindFile(int uFlags, string szFileName, string szWinDir, string szAppDir, string szCurDir, ref int lpuCurDirLen, string szDestDir, ref int lpuDestDirLen);
[DllImport("version")] public static extern int VerInstallFile(int uFlags, string szSrcFileName, string szDestFileName, string szSrcDir, string szDestDir, string szCurDir, string szTmpFile, ref int lpuTmpFileLen);
[DllImport("version")] public static extern int VerQueryValue(IntPtr pBlock, string lpSubBlock, ref int lplpBuffer, ref int puLen);
}
 public abstract class
Kernel
{
[DllImport("kernel32")] public static extern
void OutputDebugString(string
lpszOutputString);
[DllImport("KERNEL32")] public static extern
int ConvertDefaultLocale(int Locale);
[DllImport("KERNEL32")]
public static extern int EnumDateFormats(int lpDateFmtEnumProc, int Locale, int
dwFlags);
[DllImport("KERNEL32")] public static extern int
EnumSystemCodePages(int lpCodePageEnumProc, int
dwFlags);
[DllImport("KERNEL32")] public static extern int
EnumSystemLocales(int lpLocaleEnumProc, int
dwFlags);
[DllImport("KERNEL32")] public static extern int
EnumTimeFormats(int lpTimeFmtEnumProc, int Locale, int
dwFlags);
[DllImport("KERNEL32")] public static extern int
GetThreadLocale();
[DllImport("KERNEL32")] public static extern
int IsValidLocale(int Locale, int
dwFlags);
[DllImport("KERNEL32")] public static extern void
ZeroMemory(IntPtr dest, int numBytes);
[DllImport("kernel32")]
public static extern COORD GetLargestConsoleWindowSize(HANDLE
hConsoleOutput);
[DllImport("kernel32")] public static extern int
AllocConsole();
[DllImport("kernel32")] public static extern int
BackupRead(HANDLE hFile, Byte lpBuffer, int nNumberOfBytesToRead, ref int
lpNumberOfBytesRead, int bAbort, int bProcessSecurity, IntPtr
lpContext);
[DllImport("kernel32")] public static extern int
BackupSeek(HANDLE hFile, int dwLowBytesToSeek, int dwHighBytesToSeek, ref int
lpdwLowByteSeeked, ref int lpdwHighByteSeeked, ref int
lpContext);
[DllImport("kernel32")] public static extern int
BackupWrite(HANDLE hFile, Byte lpBuffer, int nNumberOfBytesToWrite, ref int
lpNumberOfBytesWritten, int bAbort, int bProcessSecurity, ref int
lpContext);
[DllImport("kernel32")] public static extern int
Beep(int dwFreq, int dwDuration);
[DllImport("kernel32")] public
static extern int BeginUpdateResource(string pFileName, int
bDeleteExistingResources);
[DllImport("kernel32")] public static
extern int BuildCommDCB(string lpDef, ref DCB
lpDCB);
[DllImport("kernel32")] public static extern int
BuildCommDCBAndTimeouts(string lpDef, ref DCB lpDCB, ref COMMTIMEOUTS
lpCommTimeouts);
[DllImport("kernel32")] public static extern int
CallNamedPipe(string lpNamedPipeName, IntPtr lpInBuffer, int nInBufferSize,
IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesRead, int
nTimeOut);
[DllImport("kernel32")] public static extern int
ClearCommBreak(int nCid);
[DllImport("kernel32")] public static
extern int ClearCommError(HANDLE hFile, ref int lpErrors, ref COMSTAT
lpStat);
[DllImport("kernel32")] public static extern int
CloseHandle(HANDLE hObject);
[DllImport("kernel32")] public
static extern int CommConfigDialog(string lpszName, HWND hwnd, ref COMMCONFIG
lpCC);
[DllImport("kernel32")] public static extern int
CompareFileTime(ref FILETIME lpFileTime1, ref FILETIME
lpFileTime2);
[DllImport("kernel32")] public static extern int
CompareString(int Locale, int dwCmpFlags, string lpString1, int cchCount1,
string lpString2, int cchCount2);
[DllImport("kernel32")] public
static extern int ConnectNamedPipe(HANDLE hNamedPipe, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
ContinueDebugEvent(int dwProcessId, int dwThreadId, int
dwContinueStatus);
[DllImport("kernel32")] public static extern
int CopyFile(string lpExistingFileName, string lpNewFileName, int
bFailIfExists);
[DllImport("kernel32")] public static extern int
CreateConsoleScreenBuffer(int dwDesiredAccess, int dwShareMode, ref
SECURITY_ATTRIBUTES lpSecurityAttributes, int dwFlags, IntPtr
lpScreenBufferData);
[DllImport("kernel32")] public static extern
int CreateDirectory(string lpPathName, ref SECURITY_ATTRIBUTES
lpSecurityAttributes);
[DllImport("kernel32")] public static
extern int CreateDirectoryEx(string lpTemplateDirectory, string lpNewDirectory,
ref SECURITY_ATTRIBUTES
lpSecurityAttributes);
[DllImport("kernel32")] public static
extern int CreateEvent(ref SECURITY_ATTRIBUTES lpEventAttributes, int
bManualReset, int bInitialState, string
lpName);
[DllImport("kernel32")] public static extern int
CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, ref
SECURITY_ATTRIBUTES lpSecurityAttributes, int dwCreationDisposition, int
dwFlagsAndAttributes, HANDLE
hTemplateFile);
[DllImport("kernel32")] public static extern int
CreateFileMapping(HANDLE hFile, ref SECURITY_ATTRIBUTES lpFileMappigAttributes,
int flProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, string
lpName);
[DllImport("kernel32")] public static extern int
CreateIoCompletionPort(int FileHandle, int ExistingCompletionPort, int
CompletionKey, int
NumberOfConcurrentThreads);
[DllImport("kernel32")] public static
extern int CreateMailslot(string lpName, int nMaxMessageSize, int lReadTimeout,
ref SECURITY_ATTRIBUTES
lpSecurityAttributes);
[DllImport("kernel32")] public static
extern int CreateMutex(ref SECURITY_ATTRIBUTES lpMutexAttributes, int
bInitialOwner, string lpName);
[DllImport("kernel32")] public
static extern int CreateNamedPipe(string lpName, int dwOpenMode, int dwPipeMode,
int nMaxInstances, int nOutBufferSize, int nInBufferSize, int nDefaultTimeOut,
ref SECURITY_ATTRIBUTES
lpSecurityAttributes);
[DllImport("kernel32")] public static
extern int CreatePipe(int phReadPipe, int phWritePipe, ref SECURITY_ATTRIBUTES
lpPipeAttributes, int nSize);
[DllImport("kernel32")] public
static extern int CreateProcess(string lpApplicationName, string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES
lpThreadAttributes, int bInheritHandles, int dwCreationFlags, IntPtr
lpEnvironment, string lpCurrentDriectory, ref STARTUPINFO lpStartupInfo, ref
PROCESS_INFORMATION
lpProcessInformation);
[DllImport("kernel32")] public static
extern int CreateRemoteThread(HANDLE hProcess, ref SECURITY_ATTRIBUTES
lpThreadAttributes, int dwStackSize, ref int lpStartAddress, IntPtr lpParameter,
int dwCreationFlags, ref int lpThreadId);
[DllImport("kernel32")]
public static extern int CreateSemaphore(ref SECURITY_ATTRIBUTES
lpSemaphoreAttributes, int lInitialCount, int lMaximumCount, string
lpName);
[DllImport("kernel32")] public static extern int
CreateTapePartition(HANDLE hDevice, int dwPartitionMethod, int dwCount, int
dwSize);
[DllImport("kernel32")] public static extern int
CreateThread(ref SECURITY_ATTRIBUTES lpThreadAttributes, int dwStackSize, ref
int lpStartAddress, IntPtr lpParameter, int dwCreationFlags, ref int
lpThreadId);
[DllImport("kernel32")] public static extern int
DebugActiveProcess(int dwProcessId);
[DllImport("kernel32")]
public static extern int DefineDosDevice(int dwFlags, string lpDeviceName,
string lpTargetPath);
[DllImport("kernel32")] public static
extern int DeleteFile(string lpFileName);
[DllImport("kernel32")]
public static extern int DeviceIoControl(HANDLE hDevice, int dwIoControlCode,
IntPtr lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize,
ref int lpBytesReturned, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
DisableThreadLibraryCalls(HANDLE
hLibModule);
[DllImport("kernel32")] public static extern int
DisconnectNamedPipe(HANDLE hNamedPipe);
[DllImport("kernel32")]
public static extern int DosDateTimeToFileTime(int wFatDate, int wFatTime, ref
FILETIME lpFileTime);
[DllImport("kernel32")] public static
extern int DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle,
HANDLE hTargetProcessHandle, ref int lpTargetHandle, int dwDesiredAccess, int
bInheritHandle, int dwOptions);
[DllImport("kernel32")] public
static extern int EndUpdateResource(HANDLE hUpdate, int
fDiscard);
[DllImport("kernel32")] public static extern int
EnumCalendarInfo(int lpCalInfoEnumProc, int Locale, int Calendar, int
CalType);
[DllImport("kernel32")] public static extern int
EnumResourceLanguages(HANDLE hModule, string lpType, string lpName, ref int
lpEnumFunc, int lParam);
[DllImport("kernel32")] public static
extern int EnumResourceNames(HANDLE hModule, string lpType, ref int lpEnumFunc,
int lParam);
[DllImport("kernel32")] public static extern int
EnumResourceTypes(HANDLE hModule, ref int lpEnumFunc, int
lParam);
[DllImport("kernel32")] public static extern int
EraseTape(HANDLE hDevice, int dwEraseType, int
bimmediate);
[DllImport("kernel32")] public static extern int
EscapeCommFunction(int nCid, int nFunc);
[DllImport("kernel32")]
public static extern int ExpandEnvironmentStrings(string lpSrc, string lpDst,
int nSize);
[DllImport("kernel32")] public static extern int
FileTimeToDosDateTime(ref FILETIME lpFileTime, ref int lpFatDate, ref int
lpFatTime);
[DllImport("kernel32")] public static extern int
FileTimeToLocalFileTime(ref FILETIME lpFileTime, ref FILETIME
lpLocalFileTime);
[DllImport("kernel32")] public static extern
int FileTimeToSystemTime(ref FILETIME lpFileTime, ref SYSTEMTIME
lpSystemTime);
[DllImport("kernel32")] public static extern int
FillConsoleOutputAttribute(HANDLE hConsoleOutput, int wAttribute, int nLength,
COORD dwWriteCoord, ref int
lpNumberOfAttrsWritten);
[DllImport("kernel32")] public static
extern int FillConsoleOutputCharacter(HANDLE hConsoleOutput, Byte cCharacter,
int nLength, COORD dwWriteCoord, ref int
lpNumberOfCharsWritten);
[DllImport("kernel32")] public static
extern int FindClose(HANDLE hFindFile);
[DllImport("kernel32")]
public static extern int FindCloseChangeNotification(HANDLE
hChangeHandle);
[DllImport("kernel32")] public static extern int
FindFirstChangeNotification(string lpPathName, int bWatchSubtree, int
dwNotifyFilter);
[DllImport("kernel32")] public static extern int
FindFirstFile(string lpFileName, WIN32_FIND_DATA
lpFindFileData);
[DllImport("kernel32")] public static extern int
FindNextChangeNotification(HANDLE
hChangeHandle);
[DllImport("kernel32")] public static extern int
FindNextFile(HANDLE hFindFile, WIN32_FIND_DATA
lpFindFileData);
[DllImport("kernel32")] public static extern int
FindResource(HANDLE hInstance, string lpName, string
lpType);
[DllImport("kernel32")] public static extern int
FindResourceEx(HANDLE hModule, string lpType, string lpName, int
wLanguage);
[DllImport("kernel32")] public static extern int
FlushConsoleInputBuffer(HANDLE
hConsoleInput);
[DllImport("kernel32")] public static extern int
FlushFileBuffers(HANDLE hFile);
[DllImport("kernel32")] public
static extern int FlushInstructionCache(HANDLE hProcess, IntPtr lpBaseAddress,
int dwSize);
[DllImport("kernel32")] public static extern int
FlushViewOfFile(IntPtr lpBaseAddress, int
dwNumberOfBytesToFlush);
[DllImport("kernel32")] public static
extern int FoldString(int dwMapFlags, string lpSrcStr, int cchSrc, string
lpDestStr, int cchDest);
[DllImport("kernel32")] public static
extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int
dwLanguageId, string lpBuffer, int nSize, int
Arguments);
[DllImport("kernel32")] public static extern int
FreeConsole();
[DllImport("kernel32")] public static extern int
FreeEnvironmentStrings(string lpsz);
[DllImport("kernel32")]
public static extern int FreeLibrary(HANDLE
hLibModule);
[DllImport("kernel32")] public static extern int
FreeResource(HANDLE hResData);
[DllImport("kernel32")] public
static extern int GenerateConsoleCtrlEvent(int dwCtrlEvent, int
dwProcessGroupId);
[DllImport("kernel32")] public static extern
int GetACP();
[DllImport("kernel32")] public static extern int
GetBinaryType(string lpApplicationName, ref int
lpBinaryType);
[DllImport("kernel32")] public static extern int
GetCPInfo(int CodePage, ref CPINFO
lpCPInfo);
[DllImport("kernel32")] public static extern int
GetCommConfig(HANDLE hCommDev, ref COMMCONFIG lpCC, ref int
lpdwSize);
[DllImport("kernel32")] public static extern int
GetCommMask(HANDLE hFile, ref int
lpEvtMask);
[DllImport("kernel32")] public static extern int
GetCommModemStatus(HANDLE hFile, ref int
lpModemStat);
[DllImport("kernel32")] public static extern int
GetCommProperties(HANDLE hFile, ref COMMPROP
lpCommProp);
[DllImport("kernel32")] public static extern int
GetCommState(int nCid, ref DCB lpDCB);
[DllImport("kernel32")]
public static extern int GetCommTimeouts(HANDLE hFile, ref COMMTIMEOUTS
lpCommTimeouts);
[DllImport("kernel32")] public static extern int
GetCommandLine();
[DllImport("kernel32")] public static extern
int GetCompressedFileSize(string lpFileName, ref int
lpFileSizeHigh);
[DllImport("kernel32")] public static extern int
GetComputerName(string lpBuffer, int
nSize);
[DllImport("kernel32")] public static extern int
GetConsoleCP();
[DllImport("kernel32")] public static extern int
GetConsoleCursorInfo(HANDLE hConsoleOutput, ref CONSOLE_CURSOR_INFO
lpConsoleCursorInfo);
[DllImport("kernel32")] public static
extern int GetConsoleMode(HANDLE hConsoleHandle, ref int
lpMode);
[DllImport("kernel32")] public static extern int
GetConsoleOutputCP();
[DllImport("kernel32")] public static
extern int GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, ref
CONSOLE_SCREEN_BUFFER_INFO
lpConsoleScreenBufferInfo);
[DllImport("kernel32")] public static
extern int GetConsoleTitle(string lpConsoleTitle, int
nSize);
[DllImport("kernel32")] public static extern int
GetCurrencyFormat(int Locale, int dwFlags, string lpValue, ref CURRENCYFMT
lpFormat, string lpCurrencyStr, int
cchCurrency);
[DllImport("kernel32")] public static extern int
GetCurrentDirectory(int nBufferLength, string
lpBuffer);
[DllImport("kernel32")] public static extern int
GetCurrentProcess();
[DllImport("kernel32")] public static extern
int GetCurrentProcessId();
[DllImport("kernel32")] public static
extern int GetCurrentThread();
[DllImport("kernel32")] public
static extern int GetCurrentThreadId();
[DllImport("kernel32")]
public static extern int
GetCurrentTime();
[DllImport("kernel32")] public static extern
int GetDateFormat(int Locale, int dwFlags, ref SYSTEMTIME lpDate, string
lpFormat, string lpDateStr, int cchDate);
[DllImport("kernel32")]
public static extern int GetDefaultCommConfig(string lpszName, ref COMMCONFIG
lpCC, ref int lpdwSize);
[DllImport("kernel32")] public static
extern int GetDiskFreeSpace(string lpRootPathName, ref int lpSectorsPerCluster,
ref int lpBytesPerSector, ref int lpNumberOfFreeClusters, ref int
lpTotalNumberOfClusters);
  [DllImport("kernel32")] public static extern int
GetDiskFreeSpaceEx(string lpDirectoryName,out ulong lpFreeBytesAvailable,out
ulong lpTotalNumberOfBytes,out ulong
lpTotalNumberOfFreeBytes);
[DllImport("kernel32")] public static
extern int GetDriveType(string nDrive);
[DllImport("kernel32")]
public static extern int GetEnvironmentVariable(string lpName, string lpBuffer,
int nSize);
[DllImport("kernel32")] public static extern int
GetExitCodeProcess(HANDLE hProcess, ref int
lpExitCode);
[DllImport("kernel32")] public static extern int
GetExitCodeThread(HANDLE hThread, ref int
lpExitCode);
[DllImport("kernel32")] public static extern int
GetFileAttributes(string lpFileName);
[DllImport("kernel32")]
public static extern int GetFileInformationByHandle(HANDLE hFile, ref
BY_HANDLE_FILE_INFORMATION
lpFileInformation);
[DllImport("kernel32")] public static extern
int GetFileSize(HANDLE hFile, ref int
lpFileSizeHigh);
[DllImport("kernel32")] public static extern int
GetFileTime(HANDLE hFile, ref FILETIME lpCreationTime, ref FILETIME
lpLastAccessTime, ref FILETIME
lpLastWriteTime);
[DllImport("kernel32")] public static extern
int GetFileType(HANDLE hFile);
[DllImport("kernel32")] public
static extern int GetFullPathName(string lpFileName, int nBufferLength,
StringBuilder lpBuffer, string
lpFilePart);
[DllImport("kernel32")] public static extern int
GetHandleInformation(HANDLE hObject, ref int
lpdwFlags);
[DllImport("kernel32")] public static extern int
GetLastError();
[DllImport("kernel32")] public static extern int
GetLocaleInfo(int Locale, int LCType, string lpLCData, int
cchData);
[DllImport("kernel32")] public static extern int
GetLogicalDriveStrings(int nBufferLength, StringBuilder
lpBuffer);
[DllImport("kernel32")] public static extern int
GetLogicalDrives();
[DllImport("kernel32")] public static extern
int GetMailslotInfo(HANDLE hMailslot, ref int lpMaxMessageSize, ref int
lpNextSize, ref int lpMessageCount, ref int
lpReadTimeout);
[DllImport("kernel32")] public static extern int
GetModuleFileName(HANDLE hModule, StringBuilder lpFileName, int
nSize);
[DllImport("kernel32")] public static extern int
GetModuleHandle(string lpModuleName);
[DllImport("kernel32")]
public static extern int GetNamedPipeHandleState(HANDLE hNamedPipe, ref int
lpState, ref int lpCurInstances, ref int lpMaxCollectionCount, ref int
lpCollectDataTimeout, string lpUserName, int
nMaxUserNameSize);
[DllImport("kernel32")] public static extern
int GetNamedPipeInfo(HANDLE hNamedPipe, ref int lpFlags, ref int
lpOutBufferSize, ref int lpInBufferSize, ref int
lpMaxInstances);
[DllImport("kernel32")] public static extern int
GetNumberFormat(int Locale, int dwFlags, string lpValue, ref NUMBERFMT lpFormat,
string lpNumberStr, int cchNumber);
[DllImport("kernel32")]
public static extern int GetNumberOfConsoleInputEvents(HANDLE hConsoleInput, ref
int lpNumberOfEvents);
[DllImport("kernel32")] public static
extern int GetNumberOfConsoleMouseButtons(int
lpNumberOfMouseButtons);
[DllImport("kernel32")] public static
extern int GetOEMCP();
[DllImport("kernel32")] public static
extern int GetOverlappedResult(HANDLE hFile, ref OVERLAPPED lpOverlapped, ref
int lpNumberOfBytesTransferred, int
bWait);
[DllImport("kernel32")] public static extern int
GetPriorityClass(HANDLE hProcess);
[DllImport("kernel32")] public
static extern int GetPrivateProfileInt(string lpApplicationName, string
lpKeyName, int nDefault, string
lpFileName);
[DllImport("kernel32")] public static extern int
GetPrivateProfileSection(string lpAppName, StringBuilder lpReturnedString, int
nSize, string lpFileName);
[DllImport("kernel32")] public static
extern int GetPrivateProfileString(string lpApplicationName, IntPtr lpKeyName,
string lpDefault, StringBuilder lpReturnedString, int nSize, string
lpFileName);
[DllImport("kernel32")] public static extern int
GetPrivateProfileString(string lpApplicationName, string lpKeyName, string
lpDefault, StringBuilder lpReturnedString, int nSize, string
lpFileName);
[DllImport("kernel32")] public static extern int
GetProcessAffinityMask(HANDLE hProcess, ref int lpProcessAffinityMask, int
SystemAffinityMask);
[DllImport("kernel32")] public static extern
int GetProcessHeap();
[DllImport("kernel32")] public static
extern int GetProcessHeaps(int NumberOfHeaps, int
ProcessHeaps);
[DllImport("kernel32")] public static extern int
GetProcessShutdownParameters(int lpdwLevel, ref int
lpdwFlags);
[DllImport("kernel32")] public static extern int
GetProcessTimes(HANDLE hProcess, ref FILETIME lpCreationTime, ref FILETIME
lpExitTime, ref FILETIME lpKernelTime, ref FILETIME
lpUserTime);
[DllImport("kernel32")] public static extern int
GetProcessWorkingSetSize(HANDLE hProcess, ref int lpMinimumWorkingSetSize, ref
int lpMaximumWorkingSetSize);
[DllImport("kernel32")] public
static extern int GetProfileInt(string lpAppName, string lpKeyName, int
nDefault);
[DllImport("kernel32")] public static extern int
GetProfileSection(string lpAppName, string lpReturnedString, int
nSize);
[DllImport("kernel32")] public static extern int
GetProfileString(string lpAppName, string lpKeyName, string lpDefault,
StringBuilder lpReturnedString, int
nSize);
[DllImport("kernel32")] public static extern int
GetQueuedCompletionStatus(int CompletionPort, ref int
lpNumberOfBytesTransferred, ref int lpCompletionKey, ref int lpOverlapped, int
dwMilliseconds);
[DllImport("kernel32")] public static extern int
GetShortPathName(string lpszLongPath, string lpszShortPath, int
cchBuffer);
[DllImport("kernel32")] public static extern int
GetStdHandle(int nStdHandle);
[DllImport("kernel32")] public
static extern int GetStringTypeA(int lcid, int dwInfoType, string lpSrcStr, int
cchSrc, ref int lpCharType);
[DllImport("kernel32")] public
static extern int GetStringTypeEx(int Locale, int dwInfoType, string lpSrcStr,
int cchSrc, short lpCharType);
[DllImport("kernel32")] public
static extern int GetStringTypeW(int dwInfoType, string lpSrcStr, int cchSrc,
short lpCharType);
[DllImport("kernel32")] public static extern
int GetSystemDefaultLCID();
[DllImport("kernel32")] public static
extern int GetSystemDirectory(StringBuilder lpBuffer, int
nSize);
[DllImport("kernel32")] public static extern int
GetSystemPowerStatus(ref SYSTEM_POWER_STATUS
lpSystemPowerStatus);
[DllImport("kernel32")] public static
extern int GetSystemTimeAdjustment(int lpTimeAdjustment, ref int
lpTimeIncrement, ref int
lpTimeAdjustmentDisabled);
[DllImport("kernel32")] public static
extern int GetTapeParameters(HANDLE hDevice, int dwOperation, ref int lpdwSize,
IntPtr lpTapeInformation);
[DllImport("kernel32")] public static
extern int GetTapePosition(HANDLE hDevice, int dwPositionType, ref int
lpdwPartition, ref int lpdwOffsetLow, ref int
lpdwOffsetHigh);
[DllImport("kernel32")] public static extern int
GetTapeStatus(HANDLE hDevice);
[DllImport("kernel32")] public
static extern int GetTempFileName(string lpszPath, string lpPrefixString, int
wUnique, StringBuilder lpTempFileName);
[DllImport("kernel32")]
public static extern int GetTempPath(int nBufferLength, StringBuilder
lpBuffer);
[DllImport("kernel32")] public static extern int
GetThreadContext(HANDLE hThread, ref CONTEXT
lpContext);
[DllImport("kernel32")] public static extern int
GetThreadPriority(HANDLE hThread);
[DllImport("kernel32")] public
static extern int GetThreadSelectorEntry(HANDLE hThread, int dwSelector, ref
LDT_ENTRY lpSelectorEntry);
[DllImport("kernel32")] public static
extern int GetThreadTimes(HANDLE hThread, ref FILETIME lpCreationTime, ref
FILETIME lpExitTime, ref FILETIME lpKernelTime, ref FILETIME
lpUserTime);
[DllImport("kernel32")] public static extern int
GetTickCount();
[DllImport("kernel32")] public static extern int
GetTimeFormat(int Locale, int dwFlags, ref SYSTEMTIME lpTime, string lpFormat,
string lpTimeStr, int cchTime);
[DllImport("kernel32")] public
static extern int GetTimeZoneInformation(ref TIME_ZONE_INFORMATION
lpTimeZoneInformation);
[DllImport("kernel32")] public static
extern int GetUserDefaultLCID();
[DllImport("kernel32")] public
static extern int GetVersion();
[DllImport("kernel32")] public
static extern int GetVersionEx(ref OSVERSIONINFO
lpVersionInformation);
[DllImport("kernel32")] public static
extern int GetVolumeInformation(string lpRootPathName, string
lpVolumeNameBuffer, int nVolumeNameSize, ref int lpVolumeSerialNumber, ref int
lpMaximumComponentLength, ref int lpFileSystemFlags, string
lpFileSystemNameBuffer, int
nFileSystemNameSize);
[DllImport("kernel32")] public static
extern int GetWindowsDirectory(StringBuilder lpBuffer, int
nSize);
[DllImport("kernel32")] public static extern int
GlobalAlloc(int wFlags, int dwBytes);
[DllImport("kernel32")]
public static extern int GlobalCompact(int
dwMinFree);
[DllImport("kernel32")] public static extern int
GlobalFlags(HANDLE hMem);
[DllImport("kernel32")] public static
extern int GlobalFree(HANDLE hMem);
[DllImport("kernel32")]
public static extern int GlobalGetAtomName(short nAtom, string lpBuffer, int
nSize);
[DllImport("kernel32")] public static extern int
GlobalHandle(IntPtr wMem);
[DllImport("kernel32")] public static
extern int GlobalLock(HANDLE hMem);
[DllImport("kernel32")]
public static extern int GlobalReAlloc(HANDLE hMem, int dwBytes, int
wFlags);
[DllImport("kernel32")] public static extern int
GlobalSize(HANDLE hMem);
[DllImport("kernel32")] public static
extern int GlobalUnWire(HANDLE hMem);
[DllImport("kernel32")]
public static extern int GlobalUnlock(HANDLE
hMem);
[DllImport("kernel32")] public static extern int
GlobalWire(HANDLE hMem);
[DllImport("kernel32")] public static
extern int HeapAlloc(HANDLE hHeap, int dwFlags, int
dwBytes);
[DllImport("kernel32")] public static extern int
HeapCompact(HANDLE hHeap, int dwFlags);
[DllImport("kernel32")]
public static extern int HeapCreate(int flOptions, int dwInitialSize, int
dwMaximumSize);
[DllImport("kernel32")] public static extern int
HeapDestroy(HANDLE hHeap);
[DllImport("kernel32")] public static
extern int HeapFree(HANDLE hHeap, int dwFlags, IntPtr
lpMem);
[DllImport("kernel32")] public static extern int
HeapLock(HANDLE hHeap);
[DllImport("kernel32")] public static
extern int HeapReAlloc(HANDLE hHeap, int dwFlags, IntPtr lpMem, int
dwBytes);
[DllImport("kernel32")] public static extern int
HeapSize(HANDLE hHeap, int dwFlags, IntPtr
lpMem);
[DllImport("kernel32")] public static extern int
HeapUnlock(HANDLE hHeap);
[DllImport("kernel32")] public static
extern int HeapValidate(HANDLE hHeap, int dwFlags, IntPtr
lpMem);
[DllImport("kernel32")] public static extern int
InitAtomTable(int nSize);
[DllImport("kernel32")] public static
extern int InterlockedDecrement(int
lpAddend);
[DllImport("kernel32")] public static extern int
InterlockedExchange(int Target, int
Value);
[DllImport("kernel32")] public static extern int
InterlockedIncrement(int lpAddend);
[DllImport("kernel32")]
public static extern int IsBadCodePtr(int
lpfn);
[DllImport("kernel32")] public static extern int
IsBadHugeReadPtr(IntPtr lp, int ucb);
[DllImport("kernel32")]
public static extern int IsBadHugeWritePtr(IntPtr lp, int
ucb);
[DllImport("kernel32")] public static extern int
IsBadReadPtr(IntPtr lp, int ucb);
[DllImport("kernel32")] public
static extern int IsBadStringPtr(string lpsz, int
ucchMax);
[DllImport("kernel32")] public static extern int
IsBadWritePtr(IntPtr lp, int ucb);
[DllImport("kernel32")] public
static extern int IsDBCSLeadByte(Byte
bTestChar);
[DllImport("kernel32")] public static extern int
IsValidCodePage(int CodePage);
[DllImport("kernel32")] public
static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int
cchSrc, string lpDestStr, int cchDest);
[DllImport("kernel32")]
public static extern int LoadLibrary(string
lpLibFileName);
[DllImport("kernel32")] public static extern int
LoadLibraryEx(string lpLibFileName, HANDLE hFile, int
dwFlags);
[DllImport("kernel32")] public static extern int
LoadModule(string lpModuleName, IntPtr
lpParameterBlock);
[DllImport("kernel32")] public static extern
int LoadResource(HANDLE hInstance, HANDLE
hResInfo);
[DllImport("kernel32")] public static extern int
LocalAlloc(int wFlags, int wBytes);
[DllImport("kernel32")]
public static extern int LocalCompact(int
uMinFree);
[DllImport("kernel32")] public static extern int
LocalFileTimeToFileTime(ref FILETIME lpLocalFileTime, ref FILETIME
lpFileTime);
[DllImport("kernel32")] public static extern int
LocalFlags(HANDLE hMem);
[DllImport("kernel32")] public static
extern int LocalFree(HANDLE hMem);
[DllImport("kernel32")] public
static extern int LocalHandle(HANDLE
hMem);
[DllImport("kernel32")] public static extern int
LocalLock(HANDLE hMem);
[DllImport("kernel32")] public static
extern int LocalReAlloc(HANDLE hMem, int wBytes, int
wFlags);
[DllImport("kernel32")] public static extern int
LocalShrink(HANDLE hMem, int cbNewSize);
[DllImport("kernel32")]
public static extern int LocalSize(HANDLE
hMem);
[DllImport("kernel32")] public static extern int
LocalUnlock(HANDLE hMem);
[DllImport("kernel32")] public static
extern int LockFile(HANDLE hFile, int dwFileOffsetLow, int dwFileOffsetHigh, int
nNumberOfBytesToLockLow, int
nNumberOfBytesToLockHigh);
[DllImport("kernel32")] public static
extern int LockFileEx(HANDLE hFile, int dwFlags, int dwReserved, int
nNumberOfBytesToLockLow, int nNumberOfBytesToLockHigh, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
LockResource(HANDLE hResData);
[DllImport("kernel32")] public
static extern int MapViewOfFile(HANDLE hFileMappingObject, int dwDesiredAccess,
int dwFileOffsetHigh, int dwFileOffsetLow, int
dwNumberOfBytesToMap);
[DllImport("kernel32")] public static
extern int MapViewOfFileEx(HANDLE hFileMappingObject, int dwDesiredAccess, int
dwFileOffsetHigh, int dwFileOffsetLow, int dwNumberOfBytesToMap, IntPtr
lpBaseAddress);
[DllImport("kernel32")] public static extern int
MoveFile(string lpExistingFileName, string
lpNewFileName);
[DllImport("kernel32")] public static extern int
MoveFileEx(string lpExistingFileName, string lpNewFileName, int
dwFlags);
[DllImport("kernel32")] public static extern int
MulDiv(int nNumber, int nNumerator, int
nDenominator);
[DllImport("kernel32")] public static extern int
MultiByteToWideChar(int CodePage, int dwFlags, string lpMultiByteStr, int
cchMultiByte, string lpWideCharStr, int
cchWideChar);
[DllImport("kernel32")] public static extern int
OpenEvent(int dwDesiredAccess, int bInheritHandle, string
lpName);
[DllImport("kernel32")] public static extern int
OpenFile(string lpFileName, ref OFSTRUCT lpReOpenBuff, int
wStyle);
[DllImport("kernel32")] public static extern int
OpenFileMapping(int dwDesiredAccess, int bInheritHandle, string
lpName);
[DllImport("kernel32")] public static extern int
OpenMutex(int dwDesiredAccess, int bInheritHandle, string
lpName);
[DllImport("kernel32")] public static extern int
OpenProcess(int dwDesiredAccess, int bInheritHandle, int
dwProcessId);
[DllImport("kernel32")] public static extern int
OpenSemaphore(int dwDesiredAccess, int bInheritHandle, string
lpName);
[DllImport("kernel32")] public static extern int
PeekNamedPipe(HANDLE hNamedPipe, IntPtr lpBuffer, int nBufferSize, ref int
lpBytesRead, ref int lpTotalBytesAvail, ref int
lpBytesLeftThisMessage);
[DllImport("kernel32")] public static
extern int PrepareTape(HANDLE hDevice, int dwOperation, int
bimmediate);
[DllImport("kernel32")] public static extern int
PulseEvent(HANDLE hEvent);
[DllImport("kernel32")] public static
extern int PurgeComm(HANDLE hFile, int
dwFlags);
[DllImport("kernel32")] public static extern int
QueryDosDevice(string lpDeviceName, string lpTargetPath, int
ucchMax);
[DllImport("kernel32")] public static extern int
QueryPerformanceCounter(ref LARGE_INTEGER
lpPerformanceCount);
[DllImport("kernel32")] public static extern
int QueryPerformanceFrequency(ref LARGE_INTEGER
lpFrequency);
[DllImport("kernel32")] public static extern int
ReadConsole(HANDLE hConsoleInput, IntPtr lpBuffer, int nNumberOfCharsToRead, ref
int lpNumberOfCharsRead, IntPtr
lpReserved);
[DllImport("kernel32")] public static extern int
ReadConsoleOutput(HANDLE hConsoleOutput, ref CHAR_INFO lpBuffer, COORD
dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT
lpReadRegion);
[DllImport("kernel32")] public static extern int
ReadConsoleOutputAttribute(HANDLE hConsoleOutput, ref int lpAttribute, int
nLength, COORD dwReadCoord, ref int
lpNumberOfAttrsRead);
[DllImport("kernel32")] public static
extern int ReadConsoleOutputCharacter(HANDLE hConsoleOutput, string lpCharacter,
int nLength, COORD dwReadCoord, ref int
lpNumberOfCharsRead);
[DllImport("kernel32")] public static
extern int ReadFile(HANDLE hFile, IntPtr lpBuffer, int nNumberOfBytesToRead, ref
int lpNumberOfBytesRead, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
ReadFileEx(HANDLE hFile, IntPtr lpBuffer, int nNumberOfBytesToRead, ref
OVERLAPPED lpOverlapped, ref int
lpCompletionRoutine);
[DllImport("kernel32")] public static
extern int ReadProcessMemory(HANDLE hProcess, IntPtr lpBaseAddress, IntPtr
lpBuffer, int nSize, ref int
lpNumberOfBytesWritten);
[DllImport("kernel32")] public static
extern int ReleaseMutex(HANDLE hMutex);
[DllImport("kernel32")]
public static extern int ReleaseSemaphore(HANDLE hSemaphore, int lReleaseCount,
ref int lpPreviousCount);
[DllImport("kernel32")] public static
extern int RemoveDirectory(string
lpPathName);
[DllImport("kernel32")] public static extern int
ResetEvent(HANDLE hEvent);
[DllImport("kernel32")] public static
extern int ResumeThread(HANDLE hThread);
[DllImport("kernel32")]
public static extern int ScrollConsoleScreenBuffer(HANDLE hConsoleOutput, ref
SMALL_RECT lpScrollRectangle, ref SMALL_RECT lpClipRectangle, COORD
dwDestinationOrigin, ref CHAR_INFO
lpFill);
[DllImport("kernel32")] public static extern int
SearchPath(string lpPath, string lpFileName, string lpExtension, int
nBufferLength, string lpBuffer, string
lpFilePart);
[DllImport("kernel32")] public static extern int
SetCommBreak(int nCid);
[DllImport("kernel32")] public static
extern int SetCommConfig(HANDLE hCommDev, ref COMMCONFIG lpCC, int
dwSize);
[DllImport("kernel32")] public static extern int
SetCommMask(HANDLE hFile, int dwEvtMask);
[DllImport("kernel32")]
public static extern int SetCommState(HANDLE hCommDev, ref DCB
lpDCB);
[DllImport("kernel32")] public static extern int
SetCommTimeouts(HANDLE hFile, ref COMMTIMEOUTS
lpCommTimeouts);
[DllImport("kernel32")] public static extern int
SetComputerName(string lpComputerName);
[DllImport("kernel32")]
public static extern int SetConsoleActiveScreenBuffer(HANDLE
hConsoleOutput);
[DllImport("kernel32")] public static extern int
SetConsoleCP(int wCodePageID);
[DllImport("kernel32")] public
static extern int SetConsoleCtrlHandler(int HandlerRoutine, int
Add);
[DllImport("kernel32")] public static extern int
SetConsoleCursorInfo(HANDLE hConsoleOutput, ref CONSOLE_CURSOR_INFO
lpConsoleCursorInfo);
[DllImport("kernel32")] public static
extern int SetConsoleCursorPosition(HANDLE hConsoleOutput, COORD
dwCursorPosition);
[DllImport("kernel32")] public static extern
int SetConsoleMode(HANDLE hConsoleHandle, int
dwMode);
[DllImport("kernel32")] public static extern int
SetConsoleOutputCP(int wCodePageID);
[DllImport("kernel32")]
public static extern int SetConsoleScreenBufferSize(HANDLE hConsoleOutput, COORD
dwSize);
[DllImport("kernel32")] public static extern int
SetConsoleTextAttribute(HANDLE hConsoleOutput, int
wAttributes);
[DllImport("kernel32")] public static extern int
SetConsoleTitle(string lpConsoleTitle);
[DllImport("kernel32")]
public static extern int SetConsoleWindowInfo(HANDLE hConsoleOutput, int
bAbsolute, ref SMALL_RECT
lpConsoleWindow);
[DllImport("kernel32")] public static extern
int SetCurrentDirectory(string
lpPathName);
[DllImport("kernel32")] public static extern int
SetDefaultCommConfig(string lpszName, ref COMMCONFIG lpCC, int
dwSize);
[DllImport("kernel32")] public static extern int
SetEndOfFile(HANDLE hFile);
[DllImport("kernel32")] public static
extern int SetEnvironmentVariable(string lpName, string
lpValue);
[DllImport("kernel32")] public static extern int
SetErrorMode(int wMode);
[DllImport("kernel32")] public static
extern int SetEvent(HANDLE hEvent);
[DllImport("kernel32")]
public static extern int SetFileAttributes(string lpFileName, int
dwFileAttributes);
[DllImport("kernel32")] public static extern
int SetFilePointer(HANDLE hFile, int lDistanceToMove, ref int
lpDistanceToMoveHigh, int dwMoveMethod);
[DllImport("kernel32")]
public static extern int SetFileTime(HANDLE hFile, ref FILETIME lpCreationTime,
ref FILETIME lpLastAccessTime, ref FILETIME
lpLastWriteTime);
[DllImport("kernel32")] public static extern
int SetHandleCount(int wNumber);
[DllImport("kernel32")] public
static extern int SetHandleInformation(HANDLE hObject, int dwMask, int
dwFlags);
[DllImport("kernel32")] public static extern int
SetLocalTime(ref SYSTEMTIME
lpSystemTime);
[DllImport("kernel32")] public static extern int
SetLocaleInfo(int Locale, int LCType, string
lpLCData);
[DllImport("kernel32")] public static extern int
SetMailslotInfo(HANDLE hMailslot, int
lReadTimeout);
[DllImport("kernel32")] public static extern int
SetNamedPipeHandleState(HANDLE hNamedPipe, ref int lpMode, ref int
lpMaxCollectionCount, ref int
lpCollectDataTimeout);
[DllImport("kernel32")] public static
extern int SetPriorityClass(HANDLE hProcess, int
dwPriorityClass);
[DllImport("kernel32")] public static extern
int SetProcessShutdownParameters(int dwLevel, int
dwFlags);
[DllImport("kernel32")] public static extern int
SetProcessWorkingSetSize(HANDLE hProcess, int dwMinimumWorkingSetSize, int
dwMaximumWorkingSetSize);
[DllImport("kernel32")] public static
extern int SetStdHandle(int nStdHandle, int
nHandle);
[DllImport("kernel32")] public static extern int
SetSystemPowerState(int fSuspend, int
fForce);
[DllImport("kernel32")] public static extern int
SetSystemTime(ref SYSTEMTIME
lpSystemTime);
[DllImport("kernel32")] public static extern int
SetTapeParameters(HANDLE hDevice, int dwOperation, IntPtr
lpTapeInformation);
[DllImport("kernel32")] public static extern
int SetTapePosition(HANDLE hDevice, int dwPositionMethod, int dwPartition, int
dwOffsetLow, int dwOffsetHigh, int
bimmediate);
[DllImport("kernel32")] public static extern int
SetThreadAffinityMask(HANDLE hThread, int
dwThreadAffinityMask);
[DllImport("kernel32")] public static
extern int SetThreadContext(HANDLE hThread, ref CONTEXT
lpContext);
[DllImport("kernel32")] public static extern int
SetThreadLocale(int Locale);
[DllImport("kernel32")] public
static extern int SetThreadPriority(HANDLE hThread, int
nPriority);
[DllImport("kernel32")] public static extern int
SetTimeZoneInformation(ref TIME_ZONE_INFORMATION
lpTimeZoneInformation);
[DllImport("kernel32")] public static
extern int SetUnhandledExceptionFilter(int
lpTopLevelExceptionFilter);
[DllImport("kernel32")] public static
extern int SetVolumeLabel(string lpRootPathName, string
lpVolumeName);
[DllImport("kernel32")] public static extern int
SetupComm(HANDLE hFile, int dwInQueue, int
dwOutQueue);
[DllImport("kernel32")] public static extern int
SizeofResource(HANDLE hInstance, HANDLE
hResInfo);
[DllImport("kernel32")] public static extern int
SleepEx(int dwMilliseconds, int
bAlertable);
[DllImport("kernel32")] public static extern int
SuspendThread(HANDLE hThread);
[DllImport("kernel32")] public
static extern int SystemTimeToFileTime(ref SYSTEMTIME lpSystemTime, ref FILETIME
lpFileTime);
[DllImport("kernel32")] public static extern int
SystemTimeToTzSpecificLocalTime(ref TIME_ZONE_INFORMATION lpTimeZoneInformation,
ref SYSTEMTIME lpUniversalTime, ref SYSTEMTIME
lpLocalTime);
[DllImport("kernel32")] public static extern int
TerminateProcess(HANDLE hProcess, int
uExitCode);
[DllImport("kernel32")] public static extern int
TerminateThread(HANDLE hThread, int
dwExitCode);
[DllImport("kernel32")] public static extern int
TlsAlloc();
[DllImport("kernel32")] public static extern int
TlsFree(int dwTlsIndex);
[DllImport("kernel32")] public static
extern int TlsGetValue(int dwTlsIndex);
[DllImport("kernel32")]
public static extern int TlsSetValue(int dwTlsIndex, IntPtr
lpTlsValue);
[DllImport("kernel32")] public static extern int
TransactNamedPipe(HANDLE hNamedPipe, IntPtr lpInBuffer, int nInBufferSize,
IntPtr lpOutBuffer, int nOutBufferSize, ref int lpBytesRead, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
TransmitCommChar(int nCid, Byte cChar);
[DllImport("kernel32")]
public static extern int UnhandledExceptionFilter(ref EXCEPTION_POINTERS
ExceptionInfo);
[DllImport("kernel32")] public static extern int
UnlockFile(HANDLE hFile, int dwFileOffsetLow, int dwFileOffsetHigh, int
nNumberOfBytesToUnlockLow, int
nNumberOfBytesToUnlockHigh);
[DllImport("kernel32")] public
static extern int UnlockFileEx(HANDLE hFile, int dwReserved, int
nNumberOfBytesToUnlockLow, int nNumberOfBytesToUnlockHigh, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("kernel32")]
public static extern int UpdateResource(HANDLE hUpdate, string lpType, string
lpName, int wLanguage, IntPtr lpData, int
cbData);
[DllImport("kernel32")] public static extern int
VerLanguageName(int wLang, string szLang, int
nSize);
[DllImport("kernel32")] public static extern int
VirtualAlloc(IntPtr lpAddress, int dwSize, int flAllocationType, int
flProtect);
[DllImport("kernel32")] public static extern int
VirtualFree(IntPtr lpAddress, int dwSize, int
dwFreeType);
[DllImport("kernel32")] public static extern int
VirtualLock(IntPtr lpAddress, int
dwSize);
[DllImport("kernel32")] public static extern int
VirtualProtect(IntPtr lpAddress, int dwSize, int flNewProtect, ref int
lpflOldProtect);
[DllImport("kernel32")] public static extern int
VirtualProtectEx(HANDLE hProcess, IntPtr lpAddress, int dwSize, int
flNewProtect, ref int lpflOldProtect);
[DllImport("kernel32")]
public static extern int VirtualQuery(IntPtr lpAddress, ref
MEMORY_BASIC_INFORMATION lpBuffer, int
dwLength);
[DllImport("kernel32")] public static extern int
VirtualQueryEx(HANDLE hProcess, IntPtr lpAddress, ref MEMORY_BASIC_INFORMATION
lpBuffer, int dwLength);
[DllImport("kernel32")] public static
extern int VirtualUnlock(IntPtr lpAddress, int
dwSize);
[DllImport("kernel32")] public static extern int
WaitCommEvent(HANDLE hFile, ref int lpEvtMask, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
WaitForMultipleObjects(int nCount, ref int lpHandles, int bWaitAll, int
dwMilliseconds);
[DllImport("kernel32")] public static extern int
WaitForMultipleObjectsEx(int nCount, ref int lpHandles, int bWaitAll, int
dwMilliseconds, int bAlertable);
[DllImport("kernel32")] public
static extern int WaitForSingleObject(HANDLE hHandle, int
dwMilliseconds);
[DllImport("kernel32")] public static extern int
WaitForSingleObjectEx(HANDLE hHandle, int dwMilliseconds, int
bAlertable);
[DllImport("kernel32")] public static extern int
WaitNamedPipe(string lpNamedPipeName, int
nTimeOut);
[DllImport("kernel32")] public static extern int
WideCharToMultiByte(int CodePage, int dwFlags, string lpWideCharStr, int
cchWideChar, string lpMultiByteStr, int cchMultiByte, string lpDefaultChar, ref
int lpUsedDefaultChar);
[DllImport("kernel32")] public static
extern int WinExec(string lpCmdLine, int
nCmdShow);
[DllImport("kernel32")] public static extern int
WriteConsole(HANDLE hConsoleOutput, IntPtr lpBuffer, int nNumberOfCharsToWrite,
ref int lpNumberOfCharsWritten, IntPtr
lpReserved);
[DllImport("kernel32")] public static extern int
WriteConsoleOutput(HANDLE hConsoleOutput, ref CHAR_INFO lpBuffer, COORD
dwBufferSize, COORD dwBufferCoord, ref SMALL_RECT
lpWriteRegion);
[DllImport("kernel32")] public static extern int
WriteConsoleOutputAttribute(HANDLE hConsoleOutput, short lpAttribute, int
nLength, COORD dwWriteCoord, ref int
lpNumberOfAttrsWritten);
[DllImport("kernel32")] public static
extern int WriteConsoleOutputCharacter(HANDLE hConsoleOutput, string
lpCharacter, int nLength, COORD dwWriteCoord, ref int
lpNumberOfCharsWritten);
[DllImport("kernel32")] public static
extern int WriteFile(HANDLE hFile, IntPtr lpBuffer, int nNumberOfBytesToWrite,
ref int lpNumberOfBytesWritten, ref OVERLAPPED
lpOverlapped);
[DllImport("kernel32")] public static extern int
WriteFileEx(HANDLE hFile, IntPtr lpBuffer, int nNumberOfBytesToWrite, ref
OVERLAPPED lpOverlapped, ref int
lpCompletionRoutine);
[DllImport("kernel32")] public static
extern int WritePrivateProfileSection(string lpAppName, string lpString, string
lpFileName);
[DllImport("kernel32")] public static extern int
WritePrivateProfileString(string lpApplicationName, IntPtr lpKeyName, IntPtr
lpString, string lpFileName);
[DllImport("kernel32")] public
static extern int WritePrivateProfileString(string lpApplicationName, string
lpKeyName, IntPtr lpString, string
lpFileName);
[DllImport("kernel32")] public static extern int
WriteProcessMemory(HANDLE hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int
nSize, ref int lpNumberOfBytesWritten);
[DllImport("kernel32")]
public static extern int WriteProfileSection(string lpAppName, string
lpString);
[DllImport("kernel32")] public static extern int
WriteProfileString(string lpszSection, string lpszKeyName, string
lpszString);
[DllImport("kernel32")] public static extern int
WriteTapemark(HANDLE hDevice, int dwTapemarkType, int dwTapemarkCount, int
bimmediate);
[DllImport("kernel32")] public static extern int
hread(HANDLE hFile, IntPtr lpBuffer, int
lBytes);
[DllImport("kernel32")] public static extern int
hwrite(HANDLE hFile, string lpBuffer, int
lBytes);
[DllImport("kernel32")] public static extern int
lclose(HANDLE hFile);
[DllImport("kernel32")] public static
extern int lcreat(string lpPathName, int
iAttribute);
[DllImport("kernel32")] public static extern int
llseek(HANDLE hFile, int lOffset, int
iOrigin);
[DllImport("kernel32")] public static extern int
lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32")]
public static extern int lread(HANDLE hFile, IntPtr lpBuffer, int
wBytes);
[DllImport("kernel32")] public static extern int
lstrcat(string lpString1, string
lpString2);
[DllImport("kernel32")] public static extern int
lstrcmp(string lpString1, string
lpString2);
[DllImport("kernel32")] public static extern int
lstrcmpi(string lpString1, string
lpString2);
[DllImport("kernel32")] public static extern int
lstrcpy(string lpString1, string
lpString2);
[DllImport("kernel32")] public static extern int
lstrcpyn(string lpString1, string lpString2, int
iMaxLength);
[DllImport("kernel32")] public static extern int
lstrlen(string lpString);
[DllImport("kernel32")] public static
extern int lwrite(HANDLE hFile, string lpBuffer, int
wBytes);
[DllImport("kernel32")] public static extern short
GetSystemDefaultLangID();
[DllImport("kernel32")] public static
extern short GetUserDefaultLangID();
[DllImport("kernel32")]
public static extern short GlobalAddAtom(string
lpString);
[DllImport("kernel32")] public static extern short
GlobalDeleteAtom(short nAtom);
[DllImport("kernel32")] public
static extern short GlobalFindAtom(string
lpString);
[DllImport("kernel32")] public static extern string
GetEnvironmentStrings();
[DllImport("kernel32")] public static
extern void CopyMemory(IntPtr Destination, IntPtr Source, int
Length);
[DllImport("kernel32")] public static extern void
DebugBreak();
[DllImport("kernel32")] public static extern void
DeleteCriticalSection(ref CRITICAL_SECTION
lpCriticalSection);
[DllImport("kernel32")] public static extern
void EnterCriticalSection(ref CRITICAL_SECTION
lpCriticalSection);
[DllImport("kernel32")] public static extern
void ExitProcess(int uExitCode);
[DllImport("kernel32")] public
static extern void ExitThread(int
dwExitCode);
[DllImport("kernel32")] public static extern void
FatalAppExit(int uAction, string
lpMessageText);
[DllImport("kernel32")] public static extern void
FatalExit(int code);
[DllImport("kernel32")] public static extern
void FreeLibraryAndExitThread(HANDLE hLibModule, int
dwExitCode);
[DllImport("kernel32")] public static extern void
GetLocalTime(ref SYSTEMTIME
lpSystemTime);
[DllImport("kernel32")] public static extern void
GetStartupInfo(ref STARTUPINFO
lpStartupInfo);
[DllImport("kernel32")] public static extern void
GetSystemInfo(ref SYSTEM_INFO
lpSystemInfo);
[DllImport("kernel32")] public static extern void
GetSystemTime(ref SYSTEMTIME
lpSystemTime);
[DllImport("kernel32")] public static extern void
GlobalFix(HANDLE hMem);
[DllImport("kernel32")] public static
extern void GlobalMemoryStatus(ref MEMORYSTATUS
lpBuffer);
[DllImport("kernel32")] public static extern void
GlobalUnfix(HANDLE hMem);
[DllImport("kernel32")] public static
extern void InitializeCriticalSection(ref CRITICAL_SECTION
lpCriticalSection);
[DllImport("kernel32")] public static extern
void LeaveCriticalSection(ref CRITICAL_SECTION
lpCriticalSection);
[DllImport("kernel32")] public static extern
void RaiseException(int dwExceptionCode, int dwExceptionFlags, int
nNumberOfArguments, ref int lpArguments);
[DllImport("kernel32")]
public static extern void
SetFileApisToANSI();
[DllImport("kernel32")] public static extern
void SetFileApisToOEM();
[DllImport("kernel32")] public static
extern void SetLastError(int dwErrCode);
[DllImport("kernel32")]
public static extern void Sleep(int
dwMilliseconds);
[DllImport("kernel32")] public static extern int
GetComputerNameW(IntPtr lpBuffer, int
nSize);
[DllImport("kernel32")] public static extern int
GetProcAddress(HANDLE hModule, string lpProcName);
public const int ACCESS_ALLOWED_ACE_TYPE = 0x0;
public const int ACCESS_DENIED_ACE_TYPE = 0x1;
public const int ACCESS_SYSTEM_SECURITY = 0x1000000;
public const int ACL_REVISION = (2);
public const int ACL_REVISION1 = (1);
public const int ACL_REVISION2 = (2);
public const int AC_LINE_BACKUP_POWER = 0x2;
public const int AC_LINE_OFFLINE = 0x0;
public const int AC_LINE_ONLINE = 0x1;
public const int AC_LINE_UNKNOWN = 0xFF;
public const int APPLICATION_ERROR_MASK = 0x20000000;
public const int AclRevisionInformation = 1;
public const int AclSizeInformation = 2;
public const int BACKGROUND_BLUE = 0x10;
public const int BACKGROUND_GREEN = 0x20;
public const int BACKGROUND_INTENSITY = 0x80;
public const int BACKGROUND_RED = 0x40;
public const int BACKUP_ALTERNATE_DATA = 0x4;
public const int BACKUP_DATA = 0x1;
public const int BACKUP_EA_DATA = 0x2;
public const int BACKUP_LINK = 0x5;
public const int BACKUP_SECURITY_DATA = 0x3;
public const int BATTERY_FLAG_CHARGING = 0x8;
public const int BATTERY_FLAG_CRITICAL = 0x4;
public const int BATTERY_FLAG_HIGH = 0x1;
public const int BATTERY_FLAG_LOW = 0x2;
public const int BATTERY_FLAG_NO_BATTERY = 0x80;
public const int BATTERY_FLAG_UNKNOWN = 0xFF;
public const int BATTERY_LIFE_UNKNOWN = 0xFFFF;
public const int BATTERY_PERCENTAGE_UNKNOWN = 0xFF;
public const int BAUD_075 = 0x1;
public const int BAUD_110 = 0x2;
public const int BAUD_115200 = 0x20000;
public const int BAUD_1200 = 0x40;
public const int BAUD_128K = 0x10000;
public const int BAUD_134_5 = 0x4;
public const int BAUD_14400 = 0x1000;
public const int BAUD_150 = 0x8;
public const int BAUD_1800 = 0x80;
public const int BAUD_19200 = 0x2000;
public const int BAUD_2400 = 0x100;
public const int BAUD_300 = 0x10;
public const int BAUD_38400 = 0x4000;
public const int BAUD_4800 = 0x200;
public const int BAUD_56K = 0x8000;
public const int BAUD_57600 = 0x40000;
public const int BAUD_600 = 0x20;
public const int BAUD_7200 = 0x400;
public const int BAUD_9600 = 0x800;
public const int BAUD_USER = 0x10000000;
public const int C1_ALPHA = 0x100;
public const int C1_BLANK = 0x40;
public const int C1_CNTRL = 0x20;
public const int C1_DIGIT = 0x4;
public const int C1_LOWER = 0x2;
public const int C1_PUNCT = 0x10;
public const int C1_SPACE = 0x8;
public const int C1_UPPER = 0x1;
public const int C1_XDIGIT = 0x80;
public const int C2_ARABICNUMBER = 0x6;
public const int C2_BLOCKSEPARATOR = 0x8;
public const int C2_COMMONSEPARATOR = 0x7;
public const int C2_EUROPENUMBER = 0x3;
public const int C2_EUROPESEPARATOR = 0x4;
public const int C2_EUROPETERMINATOR = 0x5;
public const int C2_LEFTTORIGHT = 0x1;
public const int C2_NOTAPPLICABLE = 0x0;
public const int C2_OTHERNEUTRAL = 0xB;
public const int C2_RIGHTTOLEFT = 0x2;
public const int C2_SEGMENTSEPARATOR = 0x9;
public const int C2_WHITESPACE = 0xA;
public const int C3_DIACRITIC = 0x2;
public const int C3_NONSPACING = 0x1;
public const int C3_NOTAPPLICABLE = 0x0;
public const int C3_SYMBOL = 0x8;
public const int C3_VOWELMARK = 0x4;
public const int CAL_GREGORIAN = 1;
public const int CAL_GREGORIAN_US = 2;
public const int CAL_ICALINTVALUE = 0x1;
public const int CAL_IYEAROFFSETRANGE = 0x3;
public const int CAL_JAPAN = 3;
public const int CAL_KOREA = 5;
public const int CAL_SABBREVDAYNAME1 = 0xE;
public const int CAL_SABBREVDAYNAME2 = 0xF;
public const int CAL_SABBREVDAYNAME3 = 0x10;
public const int CAL_SABBREVDAYNAME4 = 0x11;
public const int CAL_SABBREVDAYNAME5 = 0x12;
public const int CAL_SABBREVDAYNAME6 = 0x13;
public const int CAL_SABBREVDAYNAME7 = 0x14;
public const int CAL_SABBREVMONTHNAME1 = 0x22;
public const int CAL_SABBREVMONTHNAME10 = 0x2B;
public const int CAL_SABBREVMONTHNAME11 = 0x2C;
public const int CAL_SABBREVMONTHNAME12 = 0x2D;
public const int CAL_SABBREVMONTHNAME13 = 0x2E;
public const int CAL_SABBREVMONTHNAME2 = 0x23;
public const int CAL_SABBREVMONTHNAME3 = 0x24;
public const int CAL_SABBREVMONTHNAME4 = 0x25;
public const int CAL_SABBREVMONTHNAME5 = 0x26;
public const int CAL_SABBREVMONTHNAME6 = 0x27;
public const int CAL_SABBREVMONTHNAME7 = 0x28;
public const int CAL_SABBREVMONTHNAME8 = 0x29;
public const int CAL_SABBREVMONTHNAME9 = 0x2A;
public const int CAL_SCALNAME = 0x2;
public const int CAL_SDAYNAME1 = 0x7;
public const int CAL_SDAYNAME2 = 0x8;
public const int CAL_SDAYNAME3 = 0x9;
public const int CAL_SDAYNAME4 = 0xA;
public const int CAL_SDAYNAME5 = 0xB;
public const int CAL_SDAYNAME6 = 0xC;
public const int CAL_SDAYNAME7 = 0xD;
public const int CAL_SERASTRING = 0x4;
public const int CAL_SLONGDATE = 0x6;
public const int CAL_SMONTHNAME1 = 0x15;
public const int CAL_SMONTHNAME10 = 0x1E;
public const int CAL_SMONTHNAME11 = 0x1F;
public const int CAL_SMONTHNAME12 = 0x20;
public const int CAL_SMONTHNAME13 = 0x21;
public const int CAL_SMONTHNAME2 = 0x16;
public const int CAL_SMONTHNAME3 = 0x17;
public const int CAL_SMONTHNAME4 = 0x18;
public const int CAL_SMONTHNAME5 = 0x19;
public const int CAL_SMONTHNAME6 = 0x1A;
public const int CAL_SMONTHNAME7 = 0x1B;
public const int CAL_SMONTHNAME8 = 0x1C;
public const int CAL_SMONTHNAME9 = 0x1D;
public const int CAL_SSHORTDATE = 0x5;
public const int CAL_TAIWAN = 4;
public const int CAPSLOCK_ON = 0x80;
public const int CBR_110 = 110;
public const int CBR_115200 = 115200;
public const int CBR_1200 = 1200;
public const int CBR_128000 = 128000;
public const int CBR_14400 = 14400;
public const int CBR_19200 = 19200;
public const int CBR_2400 = 2400;
public const int CBR_256000 = 256000;
public const int CBR_300 = 300;
public const int CBR_38400 = 38400;
public const int CBR_4800 = 4800;
public const int CBR_56000 = 56000;
public const int CBR_57600 = 57600;
public const int CBR_600 = 600;
public const int CBR_9600 = 9600;
public const int CE_BREAK = 0x10;
public const int CE_DNS = 0x800;
public const int CE_FRAME = 0x8;
public const int CE_IOE = 0x400;
public const int CE_MODE = 0x8000;
public const int CE_OOP = 0x1000;
public const int CE_OVERRUN = 0x2;
public const int CE_PTO = 0x200;
public const int CE_RXOVER = 0x1;
public const int CE_RXPARITY = 0x4;
public const int CE_TXFULL = 0x100;
public const int CLRBREAK = 9;
public const int CLRDTR = 6;
public const int CLRRTS = 4;
public const int CONSOLE_TEXTMODE_BUFFER = 1;
public const int CONTAINER_INHERIT_ACE = 0x2;
public const int CP_ACP = 0;
public const int CP_OEMCP = 1;
public const int CREATE_ALWAYS = 2;
public const int CREATE_NEW = 1;
public const int CREATE_NEW_CONSOLE = 0x10;
public const int CREATE_NEW_PROCESS_GROUP = 0x200;
public const int CREATE_NO_WINDOW = 0x8000000;
public const int CREATE_PROCESS_DEBUG_EVENT = 3;
public const int CREATE_SUSPENDED = 0x4;
public const int CREATE_THREAD_DEBUG_EVENT = 2;
public const int CTRL_BREAK_EVENT = 1;
public const int CTRL_CLOSE_EVENT = 2;
public const int CTRL_C_EVENT = 0;
public const int CTRL_LOGOFF_EVENT = 5;
public const int CTRL_SHUTDOWN_EVENT = 6;
public const int CTRY_AUSTRALIA = 61;
public const int CTRY_AUSTRIA = 43;
public const int CTRY_BELGIUM = 32;
public const int CTRY_BRAZIL = 55;
public const int CTRY_CANADA = 2;
public const int CTRY_DEFAULT = 0;
public const int CTRY_DENMARK = 45;
public const int CTRY_FINLAND = 358;
public const int CTRY_FRANCE = 33;
public const int CTRY_GERMANY = 49;
public const int CTRY_ICELAND = 354;
public const int CTRY_IRELAND = 353;
public const int CTRY_ITALY = 39;
public const int CTRY_JAPAN = 81;
public const int CTRY_MEXICO = 52;
public const int CTRY_NETHERLANDS = 31;
public const int CTRY_NEW_ZEALAND = 64;
public const int CTRY_NORWAY = 47;
public const int CTRY_PORTUGAL = 351;
public const int CTRY_PRCHINA = 86;
public const int CTRY_SOUTH_KOREA = 82;
public const int CTRY_SPAIN = 34;
public const int CTRY_SWEDEN = 46;
public const int CTRY_SWITZERLAND = 41;
public const int CTRY_TAIWAN = 886;
public const int CTRY_UNITED_KINGDOM = 44;
public const int CTRY_UNITED_STATES = 1;
public const int CT_CTYPE1 = 0x1;
public const int CT_CTYPE2 = 0x2;
public const int CT_CTYPE3 = 0x4;
public const int DATABITS_16 = 0x10;
public const int DATABITS_16X = 0x20;
public const int DATABITS_5 = 0x1;
public const int DATABITS_6 = 0x2;
public const int DATABITS_7 = 0x4;
public const int DATABITS_8 = 0x8;
public const int DATE_LONGDATE = 0x2;
public const int DATE_SHORTDATE = 0x1;
public const int DDD_EXACT_MATCH_ON_REMOVE = 0x4;
public const int DDD_RAW_TARGET_PATH = 0x1;
public const int DDD_REMOVE_DEFINITION = 0x2;
public const int DEBUG_ONLY_THIS_PROCESS = 0x2;
public const int DEBUG_PROCESS = 0x1;
public const int DELETE = 0x10000;
public const int DETACHED_PROCESS = 0x8;
public const int DFCS_ADJUSTRECT = 0x2000;
public const int DFCS_BUTTON3STATE = 0x8;
public const int DFCS_BUTTONCHECK = 0x0;
public const int DFCS_BUTTONPUSH = 0x10;
public const int DFCS_BUTTONRADIO = 0x4;
public const int DFCS_BUTTONRADIOIMAGE = 0x1;
public const int DFCS_BUTTONRADIOMASK = 0x2;
public const int DFCS_CAPTIONCLOSE = 0x0;
public const int DFCS_CAPTIONHELP = 0x4;
public const int DFCS_CAPTIONMAX = 0x2;
public const int DFCS_CAPTIONMIN = 0x1;
public const int DFCS_CAPTIONRESTORE = 0x3;
public const int DFCS_CHECKED = 0x400;
public const int DFCS_FLAT = 0x4000;
public const int DFCS_INACTIVE = 0x100;
public const int DFCS_MENUARROW = 0x0;
public const int DFCS_MENUARROWRIGHT = 0x4;
public const int DFCS_MENUBULLET = 0x2;
public const int DFCS_MENUCHECK = 0x1;
public const int DFCS_MONO = 0x8000;
public const int DFCS_PUSHED = 0x200;
public const int DFCS_SCROLLCOMBOBOX = 0x5;
public const int DFCS_SCROLLDOWN = 0x1;
public const int DFCS_SCROLLLEFT = 0x2;
public const int DFCS_SCROLLRIGHT = 0x3;
public const int DFCS_SCROLLSIZEGRIP = 0x8;
public const int DFCS_SCROLLSIZEGRIPRIGHT = 0x10;
public const int DFCS_SCROLLUP = 0x0;
public const int DFC_BUTTON = 4;
public const int DFC_CAPTION = 1;
public const int DFC_MENU = 2;
public const int DFC_SCROLL = 3;
public const int DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224;
public const int DOMAIN_ALIAS_RID_ADMINS = 0x220;
public const int DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227;
public const int DOMAIN_ALIAS_RID_GUESTS = 0x222;
public const int DOMAIN_ALIAS_RID_POWER_USERS = 0x223;
public const int DOMAIN_ALIAS_RID_PRINT_OPS = 0x226;
public const int DOMAIN_ALIAS_RID_REPLICATOR = 0x228;
public const int DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225;
public const int DOMAIN_ALIAS_RID_USERS = 0x221;
public const int DOMAIN_GROUP_RID_ADMINS = 0x200;
public const int DOMAIN_GROUP_RID_GUESTS = 0x202;
public const int DOMAIN_GROUP_RID_USERS = 0x201;
public const int DOMAIN_USER_RID_ADMIN = 0x1F4;
public const int DOMAIN_USER_RID_GUEST = 0x1F5;
public const int DONT_RESOLVE_DLL_REFERENCES = 0x1;
public const int DOUBLE_CLICK = 0x2;
public const int DRIVE_CDROM = 5;
public const int DRIVE_FIXED = 3;
public const int DRIVE_RAMDISK = 6;
public const int DRIVE_REMOTE = 4;
public const int DRIVE_REMOVABLE = 2;
public const int DTR_CONTROL_DISABLE = 0x0;
public const int DTR_CONTROL_ENABLE = 0x1;
public const int DTR_CONTROL_HANDSHAKE = 0x2;
public const int DUPLICATE_CLOSE_SOURCE = 0x1;
public const int DUPLICATE_SAME_ACCESS = 0x2;
public const int ENABLE_ECHO_INPUT = 0x4;
public const int ENABLE_LINE_INPUT = 0x2;
public const int ENABLE_MOUSE_INPUT = 0x10;
public const int ENABLE_PROCESSED_INPUT = 0x1;
public const int ENABLE_PROCESSED_OUTPUT = 0x1;
public const int ENABLE_WINDOW_INPUT = 0x8;
public const int ENABLE_WRAP_AT_EOL_OUTPUT = 0x2;
public const int ENHANCED_KEY = 0x100;
public const int ENUM_ALL_CALENDARS = 0xFFFF;
public const int ERROR_SEVERITY_ERROR = unchecked((int)0xC0000000);
public const int ERROR_SEVERITY_INFORMATIONAL = 0x40000000;
public const int ERROR_SEVERITY_SUCCESS = 0x0;
public const int ERROR_SEVERITY_WARNING = unchecked((int)0x80000000);
public const int EVENPARITY = 2;
public const int EV_BREAK = 0x40;
public const int EV_CTS = 0x8;
public const int EV_DSR = 0x10;
public const int EV_ERR = 0x80;
public const int EV_EVENT1 = 0x800;
public const int EV_EVENT2 = 0x1000;
public const int EV_PERR = 0x200;
public const int EV_RING = 0x100;
public const int EV_RLSD = 0x20;
public const int EV_RX80FULL = 0x400;
public const int EV_RXCHAR = 0x1;
public const int EV_RXFLAG = 0x2;
public const int EV_TXEMPTY = 0x4;
public const int EXCEPTION_CONTINUE_EXECUTION = -1;
public const int EXCEPTION_CONTINUE_SEARCH = 0;
public const int EXCEPTION_DEBUG_EVENT = 1;
public const int EXCEPTION_EXECUTE_HANDLER = 1;
public const int EXCEPTION_MAXIMUM_PARAMETERS = 15;
public const int EXIT_PROCESS_DEBUG_EVENT = 5;
public const int EXIT_THREAD_DEBUG_EVENT = 4;
public const int FAILED_ACCESS_ACE_FLAG = 0x80;
public const int FILE_ADD_FILE = (0x2);
public const int FILE_ADD_SUBDIRECTORY = (0x4);
public const int FILE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF);
public const int FILE_APPEND_DATA = (0x4);
public const int FILE_ATTRIBUTE_ARCHIVE = 0x20;
public const int FILE_ATTRIBUTE_COMPRESSED = 0x800;
public const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
public const int FILE_ATTRIBUTE_HIDDEN = 0x2;
public const int FILE_ATTRIBUTE_NORMAL = 0x80;
public const int FILE_ATTRIBUTE_READONLY = 0x1;
public const int FILE_ATTRIBUTE_SYSTEM = 0x4;
public const int FILE_ATTRIBUTE_TEMPORARY = 0x100;
public const int FILE_BEGIN = 0;
public const int FILE_CASE_PRESERVED_NAMES = 0x2;
public const int FILE_CASE_SENSITIVE_SEARCH = 0x1;
public const int FILE_CREATE_PIPE_INSTANCE = (0x4);
public const int FILE_CURRENT = 1;
public const int FILE_DELETE_CHILD = (0x40);
public const int FILE_END = 2;
public const int FILE_EXECUTE = (0x20);
public const int FILE_FILE_COMPRESSION = 0x10;
public const int FILE_FLAG_BACKUP_SEMANTICS = 0x2000000;
public const int FILE_FLAG_DELETE_ON_CLOSE = 0x4000000;
public const int FILE_FLAG_NO_BUFFERING = 0x20000000;
public const int FILE_FLAG_OVERLAPPED = 0x40000000;
public const int FILE_FLAG_POSIX_SEMANTICS = 0x1000000;
public const int FILE_FLAG_RANDOM_ACCESS = 0x10000000;
public const int FILE_FLAG_SEQUENTIAL_SCAN = 0x8000000;
public const int FILE_FLAG_WRITE_THROUGH = unchecked((int)0x80000000);
public const int FILE_GENERIC_EXECUTE = (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE);
public const int FILE_GENERIC_READ = (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE);
public const int FILE_GENERIC_WRITE = (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE);
public const int FILE_LIST_DIRECTORY = (0x1);
public const int FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS;
public const int FILE_MAP_COPY = SECTION_QUERY;
public const int FILE_MAP_READ = SECTION_MAP_READ;
public const int FILE_MAP_WRITE = SECTION_MAP_WRITE;
public const int FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x4;
public const int FILE_NOTIFY_CHANGE_DIR_NAME = 0x2;
public const int FILE_NOTIFY_CHANGE_FILE_NAME = 0x1;
public const int FILE_NOTIFY_CHANGE_LAST_WRITE = 0x10;
public const int FILE_NOTIFY_CHANGE_SECURITY = 0x100;
public const int FILE_NOTIFY_CHANGE_SIZE = 0x8;
public const int FILE_PERSISTENT_ACLS = 0x8;
public const int FILE_READ_ATTRIBUTES = (0x80);
public const int FILE_READ_DATA = (0x1);
public const int FILE_READ_EA = (0x8);
public const int FILE_READ_PROPERTIES = FILE_READ_EA;
public const int FILE_SHARE_READ = 0x1;
public const int FILE_SHARE_WRITE = 0x2;
public const int FILE_TRAVERSE = (0x20);
public const int FILE_TYPE_CHAR = 0x2;
public const int FILE_TYPE_DISK = 0x1;
public const int FILE_TYPE_PIPE = 0x3;
public const int FILE_TYPE_REMOTE = 0x8000;
public const int FILE_TYPE_UNKNOWN = 0x0;
public const int FILE_UNICODE_ON_DISK = 0x4;
public const int FILE_VOLUME_IS_COMPRESSED = 0x8000;
public const int FILE_WRITE_ATTRIBUTES = (0x100);
public const int FILE_WRITE_DATA = (0x2);
public const int FILE_WRITE_EA = (0x10);
public const int FILE_WRITE_PROPERTIES = FILE_WRITE_EA;
public const int FOCUS_EVENT = 0x10;
public const int FOREGROUND_BLUE = 0x1;
public const int FOREGROUND_GREEN = 0x2;
public const int FOREGROUND_INTENSITY = 0x8;
public const int FOREGROUND_RED = 0x4;
public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100;
public const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x2000;
public const int FORMAT_MESSAGE_FROM_HMODULE = 0x800;
public const int FORMAT_MESSAGE_FROM_STRING = 0x400;
public const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;
public const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x200;
public const int FORMAT_MESSAGE_MAX_WIDTH_MASK = 0xFF;
public const int FROM_LEFT_1ST_BUTTON_PRESSED = 0x1;
public const int FROM_LEFT_2ND_BUTTON_PRESSED = 0x4;
public const int FROM_LEFT_3RD_BUTTON_PRESSED = 0x8;
public const int FROM_LEFT_4TH_BUTTON_PRESSED = 0x10;
public const int FS_CASE_IS_PRESERVED = FILE_CASE_PRESERVED_NAMES;
public const int FS_CASE_SENSITIVE = FILE_CASE_SENSITIVE_SEARCH;
public const int FS_PERSISTENT_ACLS = FILE_PERSISTENT_ACLS;
public const int FS_UNICODE_STORED_ON_DISK = FILE_UNICODE_ON_DISK;
public const int GENERIC_ALL = 0x10000000;
public const int GENERIC_EXECUTE = 0x20000000;
public const int GENERIC_READ = unchecked((int)0x80000000);
public const int GENERIC_WRITE = 0x40000000;
public const int GET_TAPE_DRIVE_INFORMATION = 1;
public const int GET_TAPE_MEDIA_INFORMATION = 0;
public const int GHND = (GMEM_MOVEABLE | GMEM_ZEROINIT);
public const int GMEM_DDESHARE = 0x2000;
public const int GMEM_DISCARDABLE = 0x100;
public const int GMEM_DISCARDED = 0x4000;
public const int GMEM_FIXED = 0x0;
public const int GMEM_INVALID_HANDLE = 0x8000;
public const int GMEM_LOCKCOUNT = 0xFF;
public const int GMEM_LOWER = GMEM_NOT_BANKED;
public const int GMEM_MODIFY = 0x80;
public const int GMEM_MOVEABLE = 0x2;
public const int GMEM_NOCOMPACT = 0x10;
public const int GMEM_NODISCARD = 0x20;
public const int GMEM_NOTIFY = 0x4000;
public const int GMEM_NOT_BANKED = 0x1000;
public const int GMEM_SHARE = 0x2000;
public const int GMEM_VALID_FLAGS = 0x7F72;
public const int GMEM_ZEROINIT = 0x40;
public const int GPTR = (GMEM_FIXED | GMEM_ZEROINIT);
public const int HIGH_PRIORITY_CLASS = 0x80;
public const int HKEY_CLASSES_ROOT = unchecked((int)0x80000000);
public const int HKEY_CURRENT_CONFIG = unchecked((int)0x80000005);
public const int HKEY_CURRENT_USER = unchecked((int)0x80000001);
public const int HKEY_DYN_DATA = unchecked((int)0x80000006);
public const int HKEY_LOCAL_MACHINE = unchecked((int)0x80000002);
public const int HKEY_PERFORMANCE_DATA = unchecked((int)0x80000004);
public const int HKEY_USERS = unchecked((int)0x80000003);
public const int IDLE_PRIORITY_CLASS = 0x40;
public const int IE_BADID = (-1);
public const int IE_BAUDRATE = (-12);
public const int IE_BYTESIZE = (-11);
public const int IE_DEFAULT = (-5);
public const int IE_HARDWARE = (-10);
public const int IE_MEMORY = (-4);
public const int IE_NOPEN = (-3);
public const int IE_OPEN = (-2);
public const int IGNORE = 0;
public const int INFINITE = 0xFFFF;
public const int INHERIT_ONLY_ACE = 0x8;
public const int IO_COMPLETION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3);
public const int IO_COMPLETION_MODIFY_STATE = 0x2;
public const int KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | KEY_CREATE_LINK) & (~ SYNCHRONIZE));
public const int KEY_CREATE_LINK = 0x20;
public const int KEY_CREATE_SUB_KEY = 0x4;
public const int KEY_ENUMERATE_SUB_KEYS = 0x8;
public const int KEY_EVENT = 0x1;
public const int KEY_EXECUTE = ((KEY_READ) & (~ SYNCHRONIZE));
public const int KEY_NOTIFY = 0x10;
public const int KEY_QUERY_VALUE = 0x1;
public const int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~ SYNCHRONIZE));
public const int KEY_SET_VALUE = 0x2;
public const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~ SYNCHRONIZE));
public const int LANG_BULGARIAN = 0x2;
public const int LANG_CHINESE = 0x4;
public const int LANG_CROATIAN = 0x1A;
public const int LANG_CZECH = 0x5;
public const int LANG_DANISH = 0x6;
public const int LANG_DUTCH = 0x13;
public const int LANG_ENGLISH = 0x9;
public const int LANG_FINNISH = 0xB;
public const int LANG_FRENCH = 0xC;
public const int LANG_GERMAN = 0x7;
public const int LANG_GREEK = 0x8;
public const int LANG_HUNGARIAN = 0xE;
public const int LANG_ICELANDIC = 0xF;
public const int LANG_ITALIAN = 0x10;
public const int LANG_JAPANESE = 0x11;
public const int LANG_KOREAN = 0x12;
public const int LANG_NEUTRAL = 0x0;
public const int LANG_NORWEGIAN = 0x14;
public const int LANG_POLISH = 0x15;
public const int LANG_PORTUGUESE = 0x16;
public const int LANG_ROMANIAN = 0x18;
public const int LANG_RUSSIAN = 0x19;
public const int LANG_SLOVAK = 0x1B;
public const int LANG_SLOVENIAN = 0x24;
public const int LANG_SPANISH = 0xA;
public const int LANG_SWEDISH = 0x1D;
public const int LANG_TURKISH = 0x1F;
public const int LCMAP_BYTEREV = 0x800;
public const int LCMAP_LOWERCASE = 0x100;
public const int LCMAP_SORTKEY = 0x400;
public const int LCMAP_UPPERCASE = 0x200;
public const int LEFT_ALT_PRESSED = 0x2;
public const int LEFT_CTRL_PRESSED = 0x8;
public const int LHND = (LMEM_MOVEABLE + LMEM_ZEROINIT);
public const int LMEM_DISCARDABLE = 0xF00;
public const int LMEM_DISCARDED = 0x4000;
public const int LMEM_FIXED = 0x0;
public const int LMEM_INVALID_HANDLE = 0x8000;
public const int LMEM_LOCKCOUNT = 0xFF;
public const int LMEM_MODIFY = 0x80;
public const int LMEM_MOVEABLE = 0x2;
public const int LMEM_NOCOMPACT = 0x10;
public const int LMEM_NODISCARD = 0x20;
public const int LMEM_VALID_FLAGS = 0xF72;
public const int LMEM_ZEROINIT = 0x40;
public const int LNOTIFY_DISCARD = 2;
public const int LNOTIFY_MOVE = 1;
public const int LNOTIFY_OUTOFMEM = 0;
public const int LOAD_DLL_DEBUG_EVENT = 6;
public const int LOCALE_ICENTURY = 0x24;
public const int LOCALE_ICOUNTRY = 0x5;
public const int LOCALE_ICURRDIGITS = 0x19;
public const int LOCALE_ICURRENCY = 0x1B;
public const int LOCALE_IDATE = 0x21;
public const int LOCALE_IDAYLZERO = 0x26;
public const int LOCALE_IDEFAULTCODEPAGE = 0xB;
public const int LOCALE_IDEFAULTCOUNTRY = 0xA;
public const int LOCALE_IDEFAULTLANGUAGE = 0x9;
public const int LOCALE_IDIGITS = 0x11;
public const int LOCALE_IINTLCURRDIGITS = 0x1A;
public const int LOCALE_ILANGUAGE = 0x1;
public const int LOCALE_ILDATE = 0x22;
public const int LOCALE_ILZERO = 0x12;
public const int LOCALE_IMEASURE = 0xD;
public const int LOCALE_IMONLZERO = 0x27;
public const int LOCALE_INEGCURR = 0x1C;
public const int LOCALE_INEGSEPBYSPACE = 0x57;
public const int LOCALE_INEGSIGNPOSN = 0x53;
public const int LOCALE_INEGSYMPRECEDES = 0x56;
public const int LOCALE_IPOSSEPBYSPACE = 0x55;
public const int LOCALE_IPOSSIGNPOSN = 0x52;
public const int LOCALE_IPOSSYMPRECEDES = 0x54;
public const int LOCALE_ITIME = 0x23;
public const int LOCALE_ITLZERO = 0x25;
public const int LOCALE_NOUSEROVERRIDE = unchecked((int) 0x80000000);
public const int LOCALE_S1159 = 0x28;
public const int LOCALE_S2359 = 0x29;
public const int LOCALE_SABBREVCTRYNAME = 0x7;
public const int LOCALE_SABBREVDAYNAME1 = 0x31;
public const int LOCALE_SABBREVDAYNAME2 = 0x32;
public const int LOCALE_SABBREVDAYNAME3 = 0x33;
public const int LOCALE_SABBREVDAYNAME4 = 0x34;
public const int LOCALE_SABBREVDAYNAME5 = 0x35;
public const int LOCALE_SABBREVDAYNAME6 = 0x36;
public const int LOCALE_SABBREVDAYNAME7 = 0x37;
public const int LOCALE_SABBREVLANGNAME = 0x3;
public const int LOCALE_SABBREVMONTHNAME1 = 0x44;
public const int LOCALE_SABBREVMONTHNAME10 = 0x4D;
public const int LOCALE_SABBREVMONTHNAME11 = 0x4E;
public const int LOCALE_SABBREVMONTHNAME12 = 0x4F;
public const int LOCALE_SABBREVMONTHNAME13 = 0x100F;
public const int LOCALE_SABBREVMONTHNAME2 = 0x45;
public const int LOCALE_SABBREVMONTHNAME3 = 0x46;
public const int LOCALE_SABBREVMONTHNAME4 = 0x47;
public const int LOCALE_SABBREVMONTHNAME5 = 0x48;
public const int LOCALE_SABBREVMONTHNAME6 = 0x49;
public const int LOCALE_SABBREVMONTHNAME7 = 0x4A;
public const int LOCALE_SABBREVMONTHNAME8 = 0x4B;
public const int LOCALE_SABBREVMONTHNAME9 = 0x4C;
public const int LOCALE_SCOUNTRY = 0x6;
public const int LOCALE_SCURRENCY = 0x14;
public const int LOCALE_SDATE = 0x1D;
public const int LOCALE_SDAYNAME1 = 0x2A;
public const int LOCALE_SDAYNAME2 = 0x2B;
public const int LOCALE_SDAYNAME3 = 0x2C;
public const int LOCALE_SDAYNAME4 = 0x2D;
public const int LOCALE_SDAYNAME5 = 0x2E;
public const int LOCALE_SDAYNAME6 = 0x2F;
public const int LOCALE_SDAYNAME7 = 0x30;
public const int LOCALE_SDECIMAL = 0xE;
public const int LOCALE_SENGCOUNTRY = 0x1002;
public const int LOCALE_SENGLANGUAGE = 0x1001;
public const int LOCALE_SGROUPING = 0x10;
public const int LOCALE_SINTLSYMBOL = 0x15;
public const int LOCALE_SLANGUAGE = 0x2;
public const int LOCALE_SLIST = 0xC;
public const int LOCALE_SLONGDATE = 0x20;
public const int LOCALE_SMONDECIMALSEP = 0x16;
public const int LOCALE_SMONGROUPING = 0x18;
public const int LOCALE_SMONTHNAME1 = 0x38;
public const int LOCALE_SMONTHNAME10 = 0x41;
public const int LOCALE_SMONTHNAME11 = 0x42;
public const int LOCALE_SMONTHNAME12 = 0x43;
public const int LOCALE_SMONTHNAME2 = 0x39;
public const int LOCALE_SMONTHNAME3 = 0x3A;
public const int LOCALE_SMONTHNAME4 = 0x3B;
public const int LOCALE_SMONTHNAME5 = 0x3C;
public const int LOCALE_SMONTHNAME6 = 0x3D;
public const int LOCALE_SMONTHNAME7 = 0x3E;
public const int LOCALE_SMONTHNAME8 = 0x3F;
public const int LOCALE_SMONTHNAME9 = 0x40;
public const int LOCALE_SMONTHOUSANDSEP = 0x17;
public const int LOCALE_SNATIVECTRYNAME = 0x8;
public const int LOCALE_SNATIVEDIGITS = 0x13;
public const int LOCALE_SNATIVELANGNAME = 0x4;
public const int LOCALE_SNEGATIVESIGN = 0x51;
public const int LOCALE_SPOSITIVESIGN = 0x50;
public const int LOCALE_SSHORTDATE = 0x1F;
public const int LOCALE_STHOUSAND = 0xF;
public const int LOCALE_STIME = 0x1E;
public const int LOCALE_STIMEFORMAT = 0x1003;
public const int LOCKFILE_EXCLUSIVE_LOCK = 0x2;
public const int LOCKFILE_FAIL_IMMEDIATELY = 0x1;
public const int LOGON32_LOGON_BATCH = 4;
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_SERVICE = 5;
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_PROVIDER_WINNT35 = 1;
public const int LPTR = (LMEM_FIXED + LMEM_ZEROINIT);
public const int LPTx = 0x80;
public const int MAILSLOT_NO_MESSAGE = (-1);
public const int MAILSLOT_WAIT_FOREVER = (-1);
public const int MAP_COMPOSITE = 0x40;
public const int MAP_FOLDCZONE = 0x10;
public const int MAP_FOLDDIGITS = 0x80;
public const int MAP_PRECOMPOSED = 0x20;
public const int MARKPARITY = 3;
public const int MAXByte = 0xFF;
public const int MAXCHAR = 0x7F;
public const int MAXDWORD = unchecked((int)0xFFFFFFFF);
public const int MAXIMUM_ALLOWED = 0x2000000;
public const int MAXLONG = 0x7FFFFFFF;
public const int MAXSHORT = 0x7FFF;
public const int MAXWORD = 0xFFFF;
public const int MAX_DEFAULTCHAR = 2;
public const int MAX_LEADBYTES = 12;
public const int MAX_PATH = 260;
public const int MB_COMPOSITE = 0x2;
public const int MB_PRECOMPOSED = 0x1;
public const int MB_USEGLYPHCHARS = 0x4;
public const int MENU_EVENT = 0x8;
public const int MINCHAR = 0x80;
public const int MINLONG = unchecked((int)0x80000000);
public const int MINSHORT = 0x8000;
public const int MOUSE_MOVED = 0x1;
public const int MOVEFILE_COPY_ALLOWED = 0x2;
public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
public const int MOVEFILE_REPLACE_EXISTING = 0x1;
public const int MS_CTS_ON = 0x10;
public const int MS_DSR_ON = 0x20;
public const int MS_RING_ON = 0x40;
public const int MS_RLSD_ON = 0x80;
public const int NMPWAIT_NOWAIT = 0x1;
public const int NMPWAIT_USE_DEFAULT_WAIT = 0x0;
public const int NMPWAIT_WAIT_FOREVER = 0xFFFF;
public const int NONZEROLHND = (LMEM_MOVEABLE);
public const int NONZEROLPTR = (LMEM_FIXED);
public const int NOPARITY = 0;
public const int NORMAL_PRIORITY_CLASS = 0x20;
public const int NORM_IGNORECASE = 0x1;
public const int NORM_IGNORENONSPACE = 0x2;
public const int NORM_IGNORESYMBOLS = 0x4;
public const int NO_PROPAGATE_INHERIT_ACE = 0x4;
public const int NUMLOCK_ON = 0x20;
public const int OBJECT_INHERIT_ACE = 0x1;
public const int ODDPARITY = 1;
public const int OFS_MAXPATHNAME = 128;
public const int OF_CANCEL = 0x800;
public const int OF_CREATE = 0x1000;
public const int OF_DELETE = 0x200;
public const int OF_EXIST = 0x4000;
public const int OF_PARSE = 0x100;
public const int OF_PROMPT = 0x2000;
public const int OF_READ = 0x0;
public const int OF_READWRITE = 0x2;
public const int OF_REOPEN = 0x8000;
public const int OF_SHARE_COMPAT = 0x0;
public const int OF_SHARE_DENY_NONE = 0x40;
public const int OF_SHARE_DENY_READ = 0x30;
public const int OF_SHARE_DENY_WRITE = 0x20;
public const int OF_SHARE_EXCLUSIVE = 0x10;
public const int OF_VERIFY = 0x400;
public const int OF_WRITE = 0x1;
public const int ONE5STOPBITS = 1;
public const int ONESTOPBIT = 0;
public const int OPEN_ALWAYS = 4;
public const int OPEN_EXISTING = 3;
public const int OUTPUT_DEBUG_STRING_EVENT = 8;
public const int PARITY_EVEN = 0x400;
public const int PARITY_MARK = 0x800;
public const int PARITY_NONE = 0x100;
public const int PARITY_ODD = 0x200;
public const int PARITY_SPACE = 0x1000;
public const int PCF_16BITMODE = 0x200;
public const int PCF_DTRDSR = 0x1;
public const int PCF_INTTIMEOUTS = 0x80;
public const int PCF_PARITY_CHECK = 0x8;
public const int PCF_RLSD = 0x4;
public const int PCF_RTSCTS = 0x2;
public const int PCF_SETXCHAR = 0x20;
public const int PCF_SPECIALCHARS = 0x100;
public const int PCF_TOTALTIMEOUTS = 0x40;
public const int PCF_XONXOFF = 0x10;
public const int PERF_100NSEC_MULTI_TIMER = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_100NSEC_MULTI_TIMER_INV = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER | PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_100NSEC_TIMER = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_100NSEC_TIMER_INV = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_AVERAGE_BASE = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE | PERF_DISPLAY_NOSHOW | 0x2);
public const int PERF_AVERAGE_BULK = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION | PERF_DISPLAY_NOSHOW);
public const int PERF_AVERAGE_TIMER = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION | PERF_DISPLAY_SECONDS);
public const int PERF_COUNTER_BASE = 0x30000;
public const int PERF_COUNTER_BULK_COUNT = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC);
public const int PERF_COUNTER_COUNTER = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC);
public const int PERF_COUNTER_ELAPSED = 0x40000;
public const int PERF_COUNTER_FRACTION = 0x20000;
public const int PERF_COUNTER_HISTOGRAM = 0x60000;
public const int PERF_COUNTER_HISTOGRAM_TYPE = unchecked((int)0x80000000);
public const int PERF_COUNTER_MULTI_BASE = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_BASE | PERF_MULTI_COUNTER | PERF_DISPLAY_NOSHOW);
public const int PERF_COUNTER_MULTI_TIMER = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_DELTA_COUNTER | PERF_TIMER_TICK | PERF_MULTI_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_COUNTER_MULTI_TIMER_INV = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_DELTA_COUNTER | PERF_MULTI_COUNTER | PERF_TIMER_TICK | PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_COUNTER_NODATA = (PERF_SIZE_ZERO | PERF_DISPLAY_NOSHOW);
public const int PERF_COUNTER_QUEUELEN = 0x50000;
public const int PERF_COUNTER_QUEUELEN_TYPE = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN | PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX);
public const int PERF_COUNTER_RATE = 0x10000;
public const int PERF_COUNTER_RAWCOUNT = (PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL | PERF_DISPLAY_NO_SUFFIX);
public const int PERF_COUNTER_TEXT = (PERF_SIZE_VARIABLE_LEN | PERF_TYPE_TEXT | PERF_TEXT_UNICODE | PERF_DISPLAY_NO_SUFFIX);
public const int PERF_COUNTER_TIMER = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_COUNTER_TIMER_INV = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT);
public const int PERF_COUNTER_VALUE = 0x0;
public const int PERF_DATA_REVISION = 1;
public const int PERF_DATA_VERSION = 1;
public const int PERF_DELTA_BASE = 0x800000;
public const int PERF_DELTA_COUNTER = 0x400000;
public const int PERF_DETAIL_ADVANCED = 200;
public const int PERF_DETAIL_EXPERT = 300;
public const int PERF_DETAIL_NOVICE = 100;
public const int PERF_DETAIL_WIZARD = 400;
public const int PERF_DISPLAY_NOSHOW = 0x40000000;
public const int PERF_DISPLAY_NO_SUFFIX = 0x0;
public const int PERF_DISPLAY_PERCENT = 0x20000000;
public const int PERF_DISPLAY_PER_SEC = 0x10000000;
public const int PERF_DISPLAY_SECONDS = 0x30000000;
public const int PERF_ELAPSED_TIME = (PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_ELAPSED | PERF_OBJECT_TIMER | PERF_DISPLAY_SECONDS);
public const int PERF_INVERSE_COUNTER = 0x1000000;
public const int PERF_MULTI_COUNTER = 0x2000000;
public const int PERF_NO_INSTANCES = -1;
public const int PERF_NO_UNIQUE_ID = -1;
public const int PERF_NUMBER_DECIMAL = 0x10000;
public const int PERF_NUMBER_DEC_1000 = 0x20000;
public const int PERF_NUMBER_HEX = 0x0;
public const int PERF_OBJECT_TIMER = 0x200000;
public const int PERF_RAW_BASE = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE | PERF_DISPLAY_NOSHOW | 0x3);
public const int PERF_RAW_FRACTION = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION | PERF_DISPLAY_PERCENT);
public const int PERF_SAMPLE_BASE = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE | PERF_DISPLAY_NOSHOW | 0x1);
public const int PERF_SAMPLE_COUNTER = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE | PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX);
public const int PERF_SAMPLE_FRACTION = (PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION | PERF_DELTA_COUNTER | PERF_DELTA_BASE | PERF_DISPLAY_PERCENT);
public const int PERF_SIZE_DWORD = 0x0;
public const int PERF_SIZE_LARGE = 0x100;
public const int PERF_SIZE_VARIABLE_LEN = 0x300;
public const int PERF_SIZE_ZERO = 0x200;
public const int PERF_TEXT_ASCII = 0x10000;
public const int PERF_TEXT_UNICODE = 0x0;
public const int PERF_TIMER_100NS = 0x100000;
public const int PERF_TIMER_TICK = 0x0;
public const int PERF_TYPE_COUNTER = 0x400;
public const int PERF_TYPE_NUMBER = 0x0;
public const int PERF_TYPE_TEXT = 0x800;
public const int PERF_TYPE_ZERO = 0xC00;
public const int PIPE_ACCESS_DUPLEX = 0x3;
public const int PIPE_ACCESS_INBOUND = 0x1;
public const int PIPE_ACCESS_OUTBOUND = 0x2;
public const int PIPE_CLIENT_END = 0x0;
public const int PIPE_NOWAIT = 0x1;
public const int PIPE_READMODE_BYTE = 0x0;
public const int PIPE_READMODE_MESSAGE = 0x2;
public const int PIPE_SERVER_END = 0x1;
public const int PIPE_TYPE_BYTE = 0x0;
public const int PIPE_TYPE_MESSAGE = 0x4;
public const int PIPE_UNLIMITED_INSTANCES = 255;
public const int PIPE_WAIT = 0x0;
public const int PRIVILEGE_SET_ALL_NECESSARY = (1);
public const int PROCESSOR_ALPHA_21064 = 21064;
public const int PROCESSOR_ARCHITECTURE_ALPHA = 2;
public const int PROCESSOR_ARCHITECTURE_INTEL = 0;
public const int PROCESSOR_ARCHITECTURE_MIPS = 1;
public const int PROCESSOR_ARCHITECTURE_PPC = 3;
public const int PROCESSOR_ARCHITECTURE_UNKNOWN = 0xFFFF;
public const int PROCESSOR_INTEL_386 = 386;
public const int PROCESSOR_INTEL_486 = 486;
public const int PROCESSOR_INTEL_PENTIUM = 586;
public const int PROCESSOR_MIPS_R4000 = 4000;
public const int PROCESS_HEAP_ENTRY_BUSY = 0x4;
public const int PROCESS_HEAP_ENTRY_DDESHARE = 0x20;
public const int PROCESS_HEAP_ENTRY_MOVEABLE = 0x10;
public const int PROCESS_HEAP_REGION = 0x1;
public const int PROCESS_HEAP_UNCOMMITTED_RANGE = 0x2;
public const int PROFILE_KERNEL = 0x20000000;
public const int PROFILE_SERVER = 0x40000000;
public const int PROFILE_USER = 0x10000000;
public const int PST_FAX = 0x21;
public const int PST_LAT = 0x101;
public const int PST_NETWORK_BRIDGE = 0x100;
public const int PST_PARALLELPORT = 0x2;
public const int PST_RS232 = 0x1;
public const int PST_RS422 = 0x3;
public const int PST_RS423 = 0x4;
public const int PST_RS449 = 0x5;
public const int PST_SCANNER = 0x22;
public const int PST_TCPIP_TELNET = 0x102;
public const int PST_UNSPECIFIED = 0x0;
public const int PST_X25 = 0x103;
public const int PURGE_RXABORT = 0x2;
public const int PURGE_RXCLEAR = 0x8;
public const int PURGE_TXABORT = 0x1;
public const int PURGE_TXCLEAR = 0x4;
public const int READ_CONTROL = 0x20000;
public const int REALTIME_PRIORITY_CLASS = 0x100;
public const int REG_BINARY = 3;
public const int REG_CREATED_NEW_KEY = 0x1;
public const int REG_DWORD = 4;
public const int REG_DWORD_BIG_ENDIAN = 5;
public const int REG_DWORD_LITTLE_ENDIAN = 4;
public const int REG_EXPAND_SZ = 2;
public const int REG_FULL_RESOURCE_DESCRIPTOR = 9;
public const int REG_LEGAL_CHANGE_FILTER = (REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_ATTRIBUTES | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_CHANGE_SECURITY);
public const int REG_LEGAL_OPTION = (REG_OPTION_RESERVED | REG_OPTION_NON_VOLATILE | REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK | REG_OPTION_BACKUP_RESTORE);
public const int REG_LINK = 6;
public const int REG_MULTI_SZ = 7;
public const int REG_NONE = 0;
public const int REG_NOTIFY_CHANGE_ATTRIBUTES = 0x2;
public const int REG_NOTIFY_CHANGE_LAST_SET = 0x4;
public const int REG_NOTIFY_CHANGE_NAME = 0x1;
public const int REG_NOTIFY_CHANGE_SECURITY = 0x8;
public const int REG_OPENED_EXISTING_KEY = 0x2;
public const int REG_OPTION_BACKUP_RESTORE = 4;
public const int REG_OPTION_CREATE_LINK = 2;
public const int REG_OPTION_NON_VOLATILE = 0;
public const int REG_OPTION_RESERVED = 0;
public const int REG_OPTION_VOLATILE = 1;
public const int REG_REFRESH_HIVE = 0x2;
public const int REG_RESOURCE_LIST = 8;
public const int REG_RESOURCE_REQUIREMENTS_LIST = 10;
public const int REG_SZ = 1;
public const int REG_WHOLE_HIVE_VOLATILE = 0x1;
public const int RESETDEV = 7;
public const int RIGHTMOST_BUTTON_PRESSED = 0x2;
public const int RIGHT_ALT_PRESSED = 0x1;
public const int RIGHT_CTRL_PRESSED = 0x4;
public const int RIP_EVENT = 9;
public const int RTS_CONTROL_DISABLE = 0x0;
public const int RTS_CONTROL_ENABLE = 0x1;
public const int RTS_CONTROL_HANDSHAKE = 0x2;
public const int RTS_CONTROL_TOGGLE = 0x3;
public const int RT_ACCELERATOR = 9;
public const int RT_BITMAP = 2;
public const int RT_CURSOR = 1;
public const int RT_DIALOG = 5;
public const int RT_FONT = 8;
public const int RT_FONTDIR = 7;
public const int RT_ICON = 3;
public const int RT_MENU = 4;
public const int RT_RCDATA = 10;
public const int RT_STRING = 6;
public const int SCROLLLOCK_ON = 0x40;
public const int SCS_32BIT_BINARY = 0;
public const int SCS_DOS_BINARY = 1;
public const int SCS_OS216_BINARY = 5;
public const int SCS_PIF_BINARY = 3;
public const int SCS_POSIX_BINARY = 4;
public const int SCS_WOW_BINARY = 2;
public const int SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG);
public const int SC_MANAGER_CONNECT = 0x1;
public const int SC_MANAGER_CREATE_SERVICE = 0x2;
public const int SC_MANAGER_ENUMERATE_SERVICE = 0x4;
public const int SC_MANAGER_LOCK = 0x8;
public const int SC_MANAGER_MODIFY_BOOT_CONFIG = 0x20;
public const int SC_MANAGER_QUERY_LOCK_STATUS = 0x10;
public const int SECTION_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE;
public const int SECTION_EXTEND_SIZE = 0x10;
public const int SECTION_MAP_EXECUTE = 0x8;
public const int SECTION_MAP_READ = 0x4;
public const int SECTION_MAP_WRITE = 0x2;
public const int SECTION_QUERY = 0x1;
public const int SECURITY_ANONYMOUS_LOGON_RID = 0x7;
public const int SECURITY_BATCH_RID = 0x3;
public const int SECURITY_BUILTIN_DOMAIN_RID = 0x20;
public const int SECURITY_CONTEXT_TRACKING = 0x40000;
public const int SECURITY_CREATOR_GROUP_RID = 0x1;
public const int SECURITY_CREATOR_OWNER_RID = 0x0;
public const int SECURITY_DESCRIPTOR_MIN_LENGTH = (20);
public const int SECURITY_DESCRIPTOR_REVISION = (1);
public const int SECURITY_DESCRIPTOR_REVISION1 = (1);
public const int SECURITY_DIALUP_RID = 0x1;
public const int SECURITY_EFFECTIVE_ONLY = 0x80000;
public const int SECURITY_INTERACTIVE_RID = 0x4;
public const int SECURITY_LOCAL_RID = 0x0;
public const int SECURITY_LOCAL_SYSTEM_RID = 0x12;
public const int SECURITY_LOGON_IDS_RID = 0x5;
public const int SECURITY_NETWORK_RID = 0x2;
public const int SECURITY_NT_NON_UNIQUE = 0x15;
public const int SECURITY_NULL_RID = 0x0;
public const int SECURITY_SERVICE_RID = 0x6;
public const int SECURITY_SQOS_PRESENT = 0x100000;
public const int SECURITY_VALID_SQOS_FLAGS = 0x1F0000;
public const int SECURITY_WORLD_RID = 0x0;
public const int SEM_FAILCRITICALERRORS = 0x1;
public const int SEM_NOGPFAULTERRORBOX = 0x2;
public const int SEM_NOOPENFILEERRORBOX = 0x8000;
public const int SERVICE_ACCEPT_PAUSE_CONTINUE = 0x2;
public const int SERVICE_ACCEPT_SHUTDOWN = 0x4;
public const int SERVICE_ACCEPT_STOP = 0x1;
public const int SERVICE_ACTIVE = 0x1;
public const int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL);
public const int SERVICE_CHANGE_CONFIG = 0x2;
public const int SERVICE_CONTINUE_PENDING = 0x5;
public const int SERVICE_CONTROL_CONTINUE = 0x3;
public const int SERVICE_CONTROL_INTERROGATE = 0x4;
public const int SERVICE_CONTROL_PAUSE = 0x2;
public const int SERVICE_CONTROL_SHUTDOWN = 0x5;
public const int SERVICE_CONTROL_STOP = 0x1;
public const int SERVICE_ENUMERATE_DEPENDENTS = 0x8;
public const int SERVICE_INACTIVE = 0x2;
public const int SERVICE_INTERROGATE = 0x80;
public const int SERVICE_NO_CHANGE = 0xFFFF;
public const int SERVICE_PAUSED = 0x7;
public const int SERVICE_PAUSE_CONTINUE = 0x40;
public const int SERVICE_PAUSE_PENDING = 0x6;
public const int SERVICE_QUERY_CONFIG = 0x1;
public const int SERVICE_QUERY_STATUS = 0x4;
public const int SERVICE_RUNNING = 0x4;
public const int SERVICE_START = 0x10;
public const int SERVICE_START_PENDING = 0x2;
public const int SERVICE_STATE_ALL = (SERVICE_ACTIVE | SERVICE_INACTIVE);
public const int SERVICE_STOP = 0x20;
public const int SERVICE_STOPPED = 0x1;
public const int SERVICE_STOP_PENDING = 0x3;
public const int SERVICE_USER_DEFINED_CONTROL = 0x100;
public const int SETBREAK = 8;
public const int SETDTR = 5;
public const int SETRTS = 3;
public const int SETXOFF = 1;
public const int SETXON = 2;
public const int SET_TAPE_DRIVE_INFORMATION = 1;
public const int SET_TAPE_MEDIA_INFORMATION = 0;
public const int SE_DACL_DEFAULTED = 0x8;
public const int SE_DACL_PRESENT = 0x4;
public const int SE_GROUP_DEFAULTED = 0x2;
public const int SE_GROUP_ENABLED = 0x4;
public const int SE_GROUP_ENABLED_BY_DEFAULT = 0x2;
public const int SE_GROUP_LOGON_ID = unchecked((int)0xC0000000);
public const int SE_GROUP_MANDATORY = 0x1;
public const int SE_GROUP_OWNER = 0x8;
public const int SE_OWNER_DEFAULTED = 0x1;
public const int SE_PRIVILEGE_ENABLED = 0x2;
public const int SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x1;
public const int SE_PRIVILEGE_USED_FOR_ACCESS = unchecked((int)0x80000000);
public const int SE_SACL_DEFAULTED = 0x20;
public const int SE_SACL_PRESENT = 0x10;
public const int SE_SELF_RELATIVE = 0x8000;
public const int SHIFT_PRESSED = 0x10;
public const int SHUTDOWN_NORETRY = 0x1;
public const int SID_MAX_SUB_AUTHORITIES = (15);
public const int SID_RECOMMENDED_SUB_AUTHORITIES = (1);
public const int SID_REVISION = (1);
public const int SLE_ERROR = 0x1;
public const int SLE_MINORERROR = 0x2;
public const int SLE_WARNING = 0x3;
public const int SORT_CHINESE_BIG5 = 0x0;
public const int SORT_CHINESE_UNICODE = 0x1;
public const int SORT_DEFAULT = 0x0;
public const int SORT_JAPANESE_UNICODE = 0x1;
public const int SORT_JAPANESE_XJIS = 0x0;
public const int SORT_KOREAN_KSC = 0x0;
public const int SORT_KOREAN_UNICODE = 0x1;
public const int SORT_STRINGSORT = 0x1000;
public const int SPACEPARITY = 4;
public const int SPECIFIC_RIGHTS_ALL = 0xFFFF;
public const int SP_BAUD = 0x2;
public const int SP_DATABITS = 0x4;
public const int SP_HANDSHAKING = 0x10;
public const int SP_PARITY = 0x1;
public const int SP_PARITY_CHECK = 0x20;
public const int SP_RLSD = 0x40;
public const int SP_SERIALCOMM = 0x1;
public const int SP_STOPBITS = 0x8;
public const int STANDARD_RIGHTS_ALL = 0x1F0000;
public const int STANDARD_RIGHTS_EXECUTE = (READ_CONTROL);
public const int STANDARD_RIGHTS_READ = (READ_CONTROL);
public const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
public const int STANDARD_RIGHTS_WRITE = (READ_CONTROL);
public const int STARTF_FORCEOFFFEEDBACK = 0x80;
public const int STARTF_FORCEONFEEDBACK = 0x40;
public const int STARTF_RUNFULLSCREEN = 0x20;
public const int STARTF_USECOUNTCHARS = 0x8;
public const int STARTF_USEFILLATTRIBUTE = 0x10;
public const int STARTF_USEPOSITION = 0x4;
public const int STARTF_USESHOWWINDOW = 0x1;
public const int STARTF_USESIZE = 0x2;
public const int STARTF_USESTDHANDLES = 0x100;
public const int STD_ERROR_HANDLE = -12;
public const int STD_INPUT_HANDLE = -10;
public const int STD_OUTPUT_HANDLE = -11;
public const int STOPBITS_10 = 0x1;
public const int STOPBITS_15 = 0x2;
public const int STOPBITS_20 = 0x4;
public const int STREAM_CONTAINS_SECURITY = 0x2;
public const int STREAM_MODIFIED_WHEN_READ = 0x1;
public const int SUBLANG_CHINESE_HONGKONG = 0x3;
public const int SUBLANG_CHINESE_SIMPLIFIED = 0x2;
public const int SUBLANG_CHINESE_SINGAPORE = 0x4;
public const int SUBLANG_CHINESE_TRADITIONAL = 0x1;
public const int SUBLANG_DEFAULT = 0x1;
public const int SUBLANG_DUTCH = 0x1;
public const int SUBLANG_DUTCH_BELGIAN = 0x2;
public const int SUBLANG_ENGLISH_AUS = 0x3;
public const int SUBLANG_ENGLISH_CAN = 0x4;
public const int SUBLANG_ENGLISH_EIRE = 0x6;
public const int SUBLANG_ENGLISH_NZ = 0x5;
public const int SUBLANG_ENGLISH_UK = 0x2;
public const int SUBLANG_ENGLISH_US = 0x1;
public const int SUBLANG_FRENCH = 0x1;
public const int SUBLANG_FRENCH_BELGIAN = 0x2;
public const int SUBLANG_FRENCH_CANADIAN = 0x3;
public const int SUBLANG_FRENCH_SWISS = 0x4;
public const int SUBLANG_GERMAN = 0x1;
public const int SUBLANG_GERMAN_AUSTRIAN = 0x3;
public const int SUBLANG_GERMAN_SWISS = 0x2;
public const int SUBLANG_ITALIAN = 0x1;
public const int SUBLANG_ITALIAN_SWISS = 0x2;
public const int SUBLANG_NEUTRAL = 0x0;
public const int SUBLANG_NORWEGIAN_BOKMAL = 0x1;
public const int SUBLANG_NORWEGIAN_NYNORSK = 0x2;
public const int SUBLANG_PORTUGUESE = 0x2;
public const int SUBLANG_PORTUGUESE_BRAZILIAN = 0x1;
public const int SUBLANG_SPANISH = 0x1;
public const int SUBLANG_SPANISH_MEXICAN = 0x2;
public const int SUBLANG_SPANISH_MODERN = 0x3;
public const int SUBLANG_SYS_DEFAULT = 0x2;
public const int SUCCESSFUL_ACCESS_ACE_FLAG = 0x40;
public const int SYNCHRONIZE = 0x100000;
public const int SYSTEM_ALARM_ACE_TYPE = 0x3;
public const int SYSTEM_AUDIT_ACE_TYPE = 0x2;
public const int S_ALLTHRESHOLD = 2;
public const int S_LEGATO = 1;
public const int S_NORMAL = 0;
public const int S_PERIOD1024 = 1;
public const int S_PERIOD2048 = 2;
public const int S_PERIOD512 = 0;
public const int S_PERIODVOICE = 3;
public const int S_QUEUEEMPTY = 0;
public const int S_SERBDNT = (-5);
public const int S_SERDCC = (-7);
public const int S_SERDDR = (-14);
public const int S_SERDFQ = (-13);
public const int S_SERDLN = (-6);
public const int S_SERDMD = (-10);
public const int S_SERDPT = (-12);
public const int S_SERDSH = (-11);
public const int S_SERDSR = (-15);
public const int S_SERDST = (-16);
public const int S_SERDTP = (-8);
public const int S_SERDVL = (-9);
public const int S_SERDVNA = (-1);
public const int S_SERMACT = (-3);
public const int S_SEROFM = (-2);
public const int S_SERQFUL = (-4);
public const int S_STACCATO = 2;
public const int S_THRESHOLD = 1;
public const int S_WHITE1024 = 5;
public const int S_WHITE2048 = 6;
public const int S_WHITE512 = 4;
public const int S_WHITEVOICE = 7;
public const int SecurityAnonymous = 1;
public const int SecurityIdentification = 2;
public const int SidTypeAlias = 4;
public const int SidTypeDeletedAccount = 6;
public const int SidTypeDomain = 3;
public const int SidTypeGroup = 2;
public const int SidTypeInvalid = 7;
public const int SidTypeUnknown = 8;
public const int SidTypeUser = 1;
public const int SidTypeWellKnownGroup = 5;
public const int TC_GP_TRAP = 2;
public const int TC_HARDERR = 1;
public const int TC_NORMAL = 0;
public const int TC_SIGNAL = 3;
public const int TF_FORCEDRIVE = 0x80;
public const int THREAD_BASE_PRIORITY_IDLE = -15;
public const int THREAD_BASE_PRIORITY_LOWRT = 15;
public const int THREAD_BASE_PRIORITY_MAX = 2;
public const int THREAD_BASE_PRIORITY_MIN = -2;
public const int THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST - 1);
public const int THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST + 1);
public const int THREAD_PRIORITY_ERROR_RETURN = (MAXLONG);
public const int THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX;
public const int THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE;
public const int THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN;
public const int THREAD_PRIORITY_NORMAL = 0;
public const int THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT;
public const int TIME_FORCE24HOURFORMAT = 0x8;
public const int TIME_NOMINUTESORSECONDS = 0x1;
public const int TIME_NOSECONDS = 0x2;
public const int TIME_NOTIMEMARKER = 0x4;
public const int TLS_OUT_OF_INDEXES = 0xFFFF;
public const int TRUNCATE_EXISTING = 5;
public const int TWOSTOPBITS = 2;
public const int TokenDefaultDacl = 6;
public const int TokenGroups = 2;
public const int TokenImpersonationLevel = 9;
public const int TokenOwner = 4;
public const int TokenPrimaryGroup = 5;
public const int TokenPrivileges = 3;
public const int TokenSource = 7;
public const int TokenStatistics = 10;
public const int TokenType = 8;
public const int TokenUser = 1;
public const int UNLOAD_DLL_DEBUG_EVENT = 7;
public const int VALID_INHERIT_FLAGS = 0xF;
public const int VER_PLATFORM_WIN32_NT = 2;
public const int VER_PLATFORM_WIN32_WINDOWS = 1;
public const int VER_PLATFORM_WIN32s = 0;
public const int WC_COMPOSITECHECK = 0x200;
public const int WC_DEFAULTCHAR = 0x40;
public const int WC_DEFAULTCHECK = 0x100;
public const int WC_DISCARDNS = 0x10;
public const int WC_SEPCHARS = 0x20;
public const int WINDOW_BUFFER_SIZE_EVENT = 0x4;
public const int WRITE_DAC = 0x40000;
public const int WRITE_OWNER = 0x80000;
public const int mouse_eventC = 0x2;
public const string SC_GROUP_IDENTIFIER = "+";
public const string SERVICES_ACTIVE_DATABASE = "ServicesActive";
public const string SERVICES_FAILED_DATABASE = "ServicesFailed";
public const string SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege";
public const string SE_AUDIT_NAME = "SeAuditPrivilege";
public const string SE_BACKUP_NAME = "SeBackupPrivilege";
public const string SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege";
public const string SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege";
public const string SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege";
public const string SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege";
public const string SE_DEBUG_NAME = "SeDebugPrivilege";
public const string SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege";
public const string SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege";
public const string SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege";
public const string SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege";
public const string SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege";
public const string SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege";
public const string SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege";
public const string SE_RESTORE_NAME = "SeRestorePrivilege";
public const string SE_SECURITY_NAME = "SeSecurityPrivilege";
public const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
public const string SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege";
public const string SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege";
public const string SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege";
public const string SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege";
public const string SE_TCB_NAME = "SeTcbPrivilege";
public const string SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege";
}
}


using System;
using System.Runtime.InteropServices;
using System.Text;
using HANDLE = System.IntPtr;
using HWND = System.IntPtr;
using HDC = System.IntPtr;
namespace Win32
{
public struct CBTACTIVATESTRUCT
{
public int fMouse;
public HWND
hwndActive;
}
public struct EVENTMSG
{
public int message;
public int
paramL;
public int paramH;
public int
time;
public HWND hwnd;
}
public struct
CWPSTRUCT
{
public int lParam;
public
int wParam;
public int message;
public HWND
hwnd;
}
public struct DEBUGHOOKINFO
{
public HANDLE hModuleHook;
public int
Reserved;
public int lParam;
public int
wParam;
public int code;
}
public struct
MOUSEHOOKSTRUCT
{
public POINT
pt;
public HWND hwnd;
public int
wHitTestCode;
public int dwExtraInfo;
}
public
struct MINMAXINFO
{
public POINT
ptReserved;
public POINT ptMaxSize;
public POINT
ptMaxPosition;
public POINT ptMinTrackSize;
public
POINT ptMaxTrackSize;
}
public struct COPYDATASTRUCT
{
public int dwData;
public int
cbData;
public int lpData;
}
public struct
WINDOWPOS
{
public HWND hwnd;
public
HWND hwndInsertAfter;
public int x;
public int
y;
public int cx;
public int
cy;
public int flags;
}
public struct ACCEL
{
public byte fVirt;
public short
key;
public short cmd;
}
public struct
PAINTSTRUCT
{
public HDC hdc;
public int
fErase;
public RECT rcPaint;
public int
fRestore;
public int
fIncUpdate;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte rgbReserved;
}
public struct CREATESTRUCT
{
public int lpCreateParams;
public
HANDLE hInstance;
public HANDLE hMenu;
public HWND
hwndParent;
public int cy;
public int
cx;
public int y;
public int
x;
public int style;
public string
lpszName;
public string lpszClass;
public int
ExStyle;
}
public struct CBT_CREATEWND
{
public CREATESTRUCT lpcs;
public HWND
hwndInsertAfter;
}
public struct WINDOWPLACEMENT
{
public int Length;
public int
flags;
public int showCmd;
public POINT
ptMinPosition;
public POINT ptMaxPosition;
public
RECT rcNormalPosition;
}
public struct MEASUREITEMSTRUCT
{
public int CtlType;
public int
CtlID;
public int itemID;
public int
itemWidth;
public int itemHeight;
public int
itemData;
}
public struct DRAWITEMSTRUCT
{
public int CtlType;
public int
CtlID;
public int itemID;
public int
itemAction;
public int itemState;
public HWND
hwndItem;
public HDC hdc;
public RECT
rcItem;
public int itemData;
}
public struct
DELETEITEMSTRUCT
{
public int
CtlType;
public int CtlID;
public int
itemID;
public HWND hwndItem;
public int
itemData;
}
public struct COMPAREITEMSTRUCT
{
public int CtlType;
public int
CtlID;
public HWND hwndItem;
public int
itemID1;
public int itemData1;
public int
itemID2;
public int itemData2;
}
public struct
MSG
{
public HWND hwnd;
public int
message;
public int wParam;
public int
lParam;
public int time;
public POINT
pt;
}
public struct WNDCLASS
{
public
int style;
public int lpfnwndproc;
public int
cbClsextra;
public int cbWndExtra2;
public HANDLE
hInstance;
public HANDLE hIcon;
public HANDLE
hCursor;
public HANDLE hbrBackground;
public
string lpszMenuName;
public string
lpszClassName;
}
public struct DLGTEMPLATE
{
public int style;
public int
dwExtendedStyle;
public short cdit;
public short
x;
public short y;
public short
cx;
public short cy;
}
public struct
DLGITEMTEMPLATE
{
public int
style;
public int dwExtendedStyle;
public short
x;
public short y;
public short
cx;
public short cy;
public short
id;
}
public struct MENUITEMTEMPLATEHEADER
{
public short versionNumber;
public
short offset;
}
public struct MENUITEMTEMPLATE
{
public short mtOption;
public short
mtID;
public byte mtString;
}
public struct
ICONINFO
{
public int fIcon;
public int
xHotspot;
public int yHotspot;
public HANDLE
hbmMask;
public HANDLE hbmColor;
}
public
struct MDICREATESTRUCT
{
public string
szClass;
public string szTitle;
public HWND
hOwner;
public int x;
public int
y;
public int cx;
public int
cy;
public int style;
public int
lParam;
}
public struct CLIENTCREATESTRUCT
{
public HANDLE hWindowMenu;
public int
idFirstChild;
}
public struct MULTIKEYHELP
{
public int mkSize;
public byte
mkKeylist;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=253)]
public string szKeyphrase;
}
public struct HELPWININFO
{
public int wStructSize;
public int
x;
public int y;
public int
dx;
public int dy;
public int
wMax;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=2)] public
string rgchMember;
}
public struct DDEACK
{
public short bAppReturnCode;
public
short Reserved;
public short fbusy;
public short
fack;
}
public struct DDEADVISE
{
public short Reserved;
public short
fDeferUpd;
public short fAckReq;
public short
cfFormat;
}
public struct DDEDATA
{
public short unused;
public short
fresponse;
public short fRelease;
public short
Reserved;
public short fAckReq;
public short
cfFormat;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public byte Value;
}
public struct DDEPOKE
{
public short unused;
public short
fRelease;
public short fReserved;
public short
cfFormat;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public byte Value;
}
public struct DDELN
{
public short unused;
public short
fRelease;
public short fDeferUpd;
public short
fAckReq;
public short cfFormat;
}
public struct
DDEUP
{
public short unused;
public
short fAck;
public short fRelease;
public short
fReserved;
public short fAckReq;
public short
cfFormat;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public byte rgb;
}
public struct HSZPAIR
{
public HANDLE hszSvc;
public HANDLE
hszTopic;
}
public struct SECURITY_QUALITY_OF_SERVICE
{
public int Length;
public short
Impersonationlevel;
public short
ContextTrackingMode;
public int
EffectiveOnly;
}
public struct CONVCONTEXT
{
public int cb;
public int
wFlags;
public int wCountryID;
public int
iCodePage;
public int dwLangID;
public int
dwSecurity;
public SECURITY_QUALITY_OF_SERVICE
qos;
}
public struct CONVINFO
{
public int cb;
public HANDLE
hUser;
public HANDLE hConvPartner;
public HANDLE
hszSvcPartner;
public HANDLE hszServiceReq;
public
HANDLE hszTopic;
public HANDLE hszItem;
public int
wFmt;
public int wType;
public int
wStatus;
public int wConvst;
public int
wLastError;
public HANDLE hConvList;
public
CONVCONTEXT ConvCtxt;
public HWND hwnd;
public
HWND hwndPartner;
}
public struct DDEML_MSG_HOOK_DATA
{
public int uiLo;
public int
uiHi;
public int cbData;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)] public int
Data;
}
public struct MONMSGSTRUCT
{
public int cb;
public HWND
hwndTo;
public int dwTime;
public HANDLE
htask;
public int wMsg;
public int
wParam;
public int lParam;
public
DDEML_MSG_HOOK_DATA dmhd;
}
public struct MONCBSTRUCT
{
public int cb;
public int
dwTime;
public HANDLE htask;
public int
dwRet;
public int wType;
public int
wFmt;
public HANDLE hConv;
public HANDLE
hsz1;
public HANDLE hsz2;
public HANDLE
hData;
public int dwData1;
public int
dwData2;
public CONVCONTEXT cc;
public int
cbData;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public int Data;
}
public struct MONHSZSTRUCT
{
public int cb;
public int fsAction;
public int dwTime;
public HANDLE
hsz;
public HANDLE htask;
public byte
str;
}
public struct MONERRSTRUCT
{
public int cb;
public int
wLastError;
public int dwTime;
public HANDLE
htask;
}
public struct MONLINKSTRUCT
{
public int cb;
public int
dwTime;
public HANDLE htask;
public int
fEstablished;
public int fNoData;
public HANDLE
hszSvc;
public HANDLE hszTopic;
public HANDLE
hszItem;
public int wFmt;
public int
fServer;
public HANDLE hConvServer;
public HANDLE
hConvClient;
}
public struct MONCONVSTRUCT
{
public int cb;
public int
fConnect;
public int dwTime;
public HANDLE
htask;
public HANDLE hszSvc;
public HANDLE
hszTopic;
public HANDLE hConvClient;
public
HANDLE hConvServer;
}
public struct DRAWTEXTPARAMS
{
public int cbSize;
public int
iTabLength;
public int iLeftMargin;
public int
iRightMargin;
public int
uiLengthDrawn;
}
public struct MENUITEMINFO
{
public int cbSize;
public int
fMask;
public int fType;
public int
fState;
public int wID;
public HANDLE
hSubMenu;
public HANDLE hbmpChecked;
public HANDLE
hbmpUnchecked;
public int dwItemData;
public
string dwTypeData;
public int cch;
}
public
struct SCROLLINFO
{
public int
cbSize;
public int fMask;
public int
nMin;
public int nMax;
public int
nPage;
public int nPos;
public int
nTrackPos;
}
public struct MSGBOXPARAMS
{
public int cbSize;
public HWND
hwndOwner;
public HANDLE hInstance;
public string
lpszText;
public string lpszCaption;
public int
dwStyle;
public string lpszIcon;
public int
dwContextHelpId;
public int
lpfnMsgBoxCallback;
public int
dwLanguageId;
}
public struct WNDCLASSEX
{
public int cbSize;
public int
style;
public int lpfnWndProc;
public int
cbClsExtra;
public int cbWndExtra;
public HANDLE
hInstance;
public HANDLE hIcon;
public HANDLE
hCursor;
public HANDLE hbrBackground;
public
string lpszMenuName;
public string
lpszClassName;
public HANDLE hIconSm;
}
public
struct TPMPARAMS
{
public int
cbSize;
public RECT rcExclude;
}
public struct
BROWSEINFO
{
public HWND
hwndOwner;
public int pIDLRoot;
public int
pszDisplayName;
public int lpszTitle;
public int
ulFlags;
public int lpfnCallback;
public int
lParam;
public int iImage;
}
 public abstract class
ComCtl
{
[DllImport("COMCTL32")] public static extern
int ImageList_AddIcon(HANDLE himl, HANDLE
hIcon);
[DllImport("COMCTL32")] public static extern int
ImageList_Create(int MinCx, int MinCy, int flags, int cInitial, int
cGrow);
[DllImport("COMCTL32")] public static extern int
ImageList_Draw(HANDLE hIMAGELIST, int ImgIndex, HWND hdcDest, int xDest, int
yDest, int lStyle);
[DllImport("COMCTL32")] public static extern
int ImageList_GetIcon(HANDLE hIMAGELIST, int ImgIndex, HANDLE
hbmMask);
[DllImport("COMCTL32")] public static extern int
InitCommonControls();
}
 public abstract class
Ole
{
[DllImport("ole32")] public static extern int
OleInitialize(IntPtr vbNullString);
[DllImport("ole32")] public
static extern void CoTaskMemFree(HANDLE
hMem);
[DllImport("ole32")] public static extern void
OleUninitialize();
}

public class
User
{
[DllImport("advapi32")] public static extern int
SetServiceBits(HANDLE hServiceStatus, int dwServiceBits, int bSetBitsOn, int
bUpdateImmediately);
[DllImport("kernel32")] public static extern
int SetSystemTimeAdjustment(int dwTimeAdjustment, int
bTimeAdjustmentDisabled);
[DllImport("mpr")] public static extern
int WNetGetUniversalName(string lpLocalPath, int dwInfoLevel, StringBuilder
lpBuffer, ref int lpBufferSize);
[DllImport("user32")] public
static extern int ActivateKeyboardLayout(HANDLE hKL, int
flags);
[DllImport("user32")] public static extern int
AdjustWindowRect(ref RECT lpRect, int dwStyle, int
bMenu);
[DllImport("user32")] public static extern int
AdjustWindowRectEx(ref RECT lpRect, int dsStyle, int bMenu, int
dwEsStyle);
[DllImport("user32")] public static extern int
AnyPopup();
[DllImport("user32")] public static extern int
AppendMenu(HANDLE hMenu, int wFlags, int wIDNewItem, IntPtr
lpNewItem);
[DllImport("user32")] public static extern int
ArrangeIconicWindows(HWND hwnd);
[DllImport("user32")] public
static extern int AttachThreadInput(int idAttach, int idAttachTo, int
fAttach);
[DllImport("user32")] public static extern int
BeginDeferWindowPos(int nNumWindows);
[DllImport("user32")]
public static extern int BeginPaint(HWND hwnd, ref PAINTSTRUCT
lpPaint);
[DllImport("user32")] public static extern int
BringWindowToTop(HWND hwnd);
[DllImport("user32")] public static
extern int BroadcastSystemMessage(int dw, ref int pdw, int un, int wParam, int
lParam);
[DllImport("user32")] public static extern int
CallMsgFilter(ref MSG lpMsg, int ncode);
[DllImport("user32")]
public static extern int CallNextHookEx(HANDLE hHook, int ncode, int wParam,
IntPtr lParam);
[DllImport("user32")] public static extern int
CallWindowProc(int lpPrevWndFunc, HWND hwnd, int Msg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
ChangeClipboardChain(HWND hwnd, HWND
hwndNext);
[DllImport("user32")] public static extern int
ChangeMenu(HANDLE hMenu, int cmd, string lpszNewItem, int cmdInsert, int
flags);
[DllImport("user32")] public static extern int
CharLowerBuff(string lpsz, int cchLength);
[DllImport("user32")]
public static extern int CharToOem(string lpszSrc, string
lpszDst);
[DllImport("user32")] public static extern int
CharToOemBuff(string lpszSrc, string lpszDst, int
cchDstLength);
[DllImport("user32")] public static extern int
CharUpperBuff(string lpsz, int cchLength);
[DllImport("user32")]
public static extern int CheckDlgButton(HANDLE hDlg, int nIDButton, int
wCheck);
[DllImport("user32")] public static extern int
CheckMenuItem(HANDLE hMenu, int wIDCheckItem, int
wCheck);
[DllImport("user32")] public static extern int
CheckMenuRadioItem(HANDLE hMenu, int un1, int un2, int un3, int
un4);
[DllImport("user32")] public static extern int
CheckRadioButton(HANDLE hDlg, int nIDFirstButton, int nIDLastButton, int
nIDCheckButton);
[DllImport("user32")] public static extern int
ChildWindowFromPoint(HWND hwnd, int xPoint, int
yPoint);
[DllImport("user32")] public static extern int
ChildWindowFromPointEx(HWND hwnd, int xPoint, int yPoint, int
un);
[DllImport("user32")] public static extern int
ClientToScreen(HWND hwnd, ref POINT
lpPoint);
[DllImport("user32")] public static extern int
ClipCursor(ref RECT lpRect);
[DllImport("user32")] public static
extern int CloseClipboard();
[DllImport("user32")] public static
extern int CloseDesktop(HANDLE hDesktop);
[DllImport("user32")]
public static extern int CloseWindow(HWND
hwnd);
[DllImport("user32")] public static extern int
CloseWindowStation(HANDLE hWinSta);
[DllImport("user32")] public
static extern int CopyAcceleratorTable(HANDLE hAccelSrc, ACCEL[] lpAccelDst, int
cAccelEntries);
[DllImport("user32")] public static extern int
CopyCursor(HANDLE hcur);
[DllImport("user32")] public static
extern int CopyIcon(HANDLE hIcon);
[DllImport("user32")] public
static extern int CopyImage(HANDLE handle, int un1, int n1, int n2, int
un2);
[DllImport("user32")] public static extern int CopyRect(ref
RECT lpDestRect, ref RECT lpSourceRect);
[DllImport("user32")]
public static extern int
CountClipboardFormats();
[DllImport("user32")] public static
extern int CreateAcceleratorTable(ref ACCEL lpaccl, int
cEntries);
[DllImport("user32")] public static extern int
CreateCaret(HWND hwnd, HANDLE hBitmap, int nWidth, int
nHeight);
[DllImport("user32")] public static extern int
CreateCursor(HANDLE hInstance, int nXhotspot, int nYhotspot, int nWidth, int
nHeight, IntPtr lpANDbitPlane, IntPtr
lpXORbitPlane);
[DllImport("user32")] public static extern int
CreateDesktop(string lpszDesktop, string lpszDevice, ref DEVMODE pDevmode, int
dwFlags, int dwDesiredAccess, ref SECURITY_ATTRIBUTES
lpsa);
[DllImport("user32")] public static extern int
CreateDialogIndirectParam(HANDLE hInstance, ref DLGTEMPLATE lpTemplate, HWND
hwndParent, ref int lpDialogFunc, int
dwInitParam);
[DllImport("user32")] public static extern int
CreateDialogParam(HANDLE hInstance, string lpName, HWND hwndParent, ref int
lpDialogFunc, int lParamInit);
[DllImport("user32")] public
static extern int CreateIcon(HANDLE hInstance, int nWidth, int nHeight, Byte
nPlanes, Byte nBitsPixel, Byte lpANDbits, Byte
lpXORbits);
[DllImport("user32")] public static extern int
CreateIconFromResource(Byte presbits, int dwResSize, int fIcon, int
dwVer);
[DllImport("user32")] public static extern int
CreateIconIndirect(ref ICONINFO piconinfo);
[DllImport("user32")]
public static extern int CreateMDIWindow(string lpClassName, string
lpWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, HWND
hwndParent, HANDLE hInstance, int lParam);
[DllImport("user32")]
public static extern int CreateMenu();
[DllImport("user32")]
public static extern int CreatePopupMenu();
[DllImport("user32")]
public static extern int CreateWindowEx(int dwExStyle, string lpClassName,
string lpWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, HWND
hwndParent, HANDLE hMenu, HANDLE hInstance, IntPtr
lpParam);
[DllImport("user32")] public static extern int
DdeAbandonTransaction(int idInst, HANDLE hConv, int
idTransaction);
[DllImport("user32")] public static extern int
DdeAccessData(HANDLE hData, ref int
pcbDataSize);
[DllImport("user32")] public static extern int
DdeAddData(HANDLE hData, Byte pSrc, int cb, int
cbOff);
[DllImport("user32")] public static extern int
DdeClientTransaction(Byte pData, int cbData, HANDLE hConv, HANDLE hszItem, int
wFmt, int wType, int dwTimeout, ref int
pdwResult);
[DllImport("user32")] public static extern int
DdeCmpStringHandles(HANDLE hsz1, HANDLE
hsz2);
[DllImport("user32")] public static extern int
DdeConnect(int idInst, HANDLE hszService, HANDLE hszTopic, ref CONVCONTEXT
pCC);
[DllImport("user32")] public static extern int
DdeConnectList(int idInst, HANDLE hszService, HANDLE hszTopic, HANDLE hConvList,
ref CONVCONTEXT pCC);
[DllImport("user32")] public static extern
int DdeCreateDataHandle(int idInst, Byte pSrc, int cb, int cbOff, HANDLE
hszItem, int wFmt, int afCmd);
[DllImport("user32")] public
static extern int DdeCreateStringHandle(int idInst, string psz, int
iCodePage);
[DllImport("user32")] public static extern int
DdeDisconnect(HANDLE hConv);
[DllImport("user32")] public static
extern int DdeDisconnectList(HANDLE
hConvList);
[DllImport("user32")] public static extern int
DdeEnableCallback(int idInst, HANDLE hConv, int
wCmd);
[DllImport("user32")] public static extern int
DdeFreeDataHandle(HANDLE hData);
[DllImport("user32")] public
static extern int DdeFreeStringHandle(int idInst, HANDLE
hsz);
[DllImport("user32")] public static extern int
DdeGetData(HANDLE hData, Byte pDst, int cbMax, int
cbOff);
[DllImport("user32")] public static extern int
DdeGetLastError(int idInst);
[DllImport("user32")] public static
extern int DdeImpersonateClient(HANDLE
hConv);
[DllImport("user32")] public static extern int
DdeKeepStringHandle(int idInst, HANDLE
hsz);
[DllImport("user32")] public static extern int
DdeNameService(int idInst, HANDLE hsz1, HANDLE hsz2, int
afCmd);
[DllImport("user32")] public static extern int
DdePostAdvise(int idInst, HANDLE hszTopic, HANDLE
hszItem);
[DllImport("user32")] public static extern int
DdeQueryConvInfo(HANDLE hConv, int idTransaction, ref CONVINFO
pConvInfo);
[DllImport("user32")] public static extern int
DdeQueryNextServer(HANDLE hConvList, HANDLE
hConvPrev);
[DllImport("user32")] public static extern int
DdeQueryString(int idInst, HANDLE hsz, string psz, int cchMax, int
iCodePage);
[DllImport("user32")] public static extern int
DdeReconnect(HANDLE hConv);
[DllImport("user32")] public static
extern int DdeSetQualityOfService(HWND hwndClient, ref
SECURITY_QUALITY_OF_SERVICE pqosNew, ref SECURITY_QUALITY_OF_SERVICE
pqosPrev);
[DllImport("user32")] public static extern int
DdeSetUserHandle(HANDLE hConv, int id, HANDLE
hUser);
[DllImport("user32")] public static extern int
DdeUnaccessData(HANDLE hData);
[DllImport("user32")] public
static extern int DdeUninitialize(int
idInst);
[DllImport("user32")] public static extern int
DefDlgProc(HANDLE hDlg, int wMsg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
DefFrameProc(HWND hwnd, HWND hwndMDIClient, int wMsg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
DefMDIChildProc(HWND hwnd, int wMsg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
DefWindowProc(HWND hwnd, int wMsg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
DeferWindowPos(HANDLE hWinPosInfo, HWND hwnd, HWND hwndInsertAfter, int x, int
y, int cx, int cy, int wFlags);
[DllImport("user32")] public
static extern int DeleteMenu(HANDLE hMenu, int nPosition, int
wFlags);
[DllImport("user32")] public static extern int
DestroyAcceleratorTable(HANDLE haccel);
[DllImport("user32")]
public static extern int DestroyCaret();
[DllImport("user32")]
public static extern int DestroyCursor(HANDLE
hCursor);
[DllImport("user32")] public static extern int
DestroyIcon(HANDLE hIcon);
[DllImport("user32")] public static
extern int DestroyMenu(HANDLE hMenu);
[DllImport("user32")]
public static extern int DestroyWindow(HWND
hwnd);
[DllImport("user32")] public static extern int
DialogBoxIndirectParam(HANDLE hInstance, DLGTEMPLATE hDialogTemplate, HWND
hwndParent, ref int lpDialogFunc, int
dwInitParam);
[DllImport("user32")] public static extern int
DispatchMessage(ref MSG lpMsg);
[DllImport("user32")] public
static extern int DlgDirList(HANDLE hDlg, string lpPathSpec, int nIDListBox, int
nIDStaticPath, int wFileType);
[DllImport("user32")] public
static extern int DlgDirListComboBox(HANDLE hDlg, string lpPathSpec, int
nIDComboBox, int nIDStaticPath, int
wFileType);
[DllImport("user32")] public static extern int
DlgDirSelectComboBoxEx(HWND hwndDlg, string lpszPath, int cbPath, int
idComboBox);
[DllImport("user32")] public static extern int
DlgDirSelectEx(HWND hwndDlg, string lpszPath, int cbPath, int
idListBox);
[DllImport("user32")] public static extern int
DragDetect(HWND hwnd, POINT pt);
[DllImport("user32")] public
static extern int DragObject(HWND hwnd1, HWND hwnd2, int un, int dw, HANDLE
hCursor);
[DllImport("user32")] public static extern int
DrawAnimatedRects(HWND hwnd, int idAni, ref RECT lprcFrom, ref RECT
lprcTo);
[DllImport("user32")] public static extern int
DrawCaption(HWND hwnd, HWND hdc, ref RECT pcRect, int
un);
[DllImport("user32")] public static extern int DrawEdge(HDC
hdc, ref RECT qrc, int edge, int grfFlags);
[DllImport("user32")]
public static extern int DrawFocusRect(HDC hdc, ref RECT
lpRect);
[DllImport("user32")] public static extern int
DrawFrameControl(HWND hdc, ref RECT lpRect, int un1, int
un2);
[DllImport("user32")] public static extern int DrawIcon(HDC
hdc, int x, int y, HANDLE hIcon);
[DllImport("user32")] public
static extern int DrawIconEx(HDC hdc, int xLeft, int yTop, HANDLE hIcon, int
cxWidth, int cyWidth, int istepIfAniCur, HANDLE hbrFlickerFreeDraw, int
diFlags);
[DllImport("user32")] public static extern int
DrawMenuBar(HWND hwnd);
[DllImport("user32")] public static
extern int DrawState(HWND hdc, HANDLE hBrush, ref int lpDrawStateProc, int
lParam, int wParam, int n1, int n2, int n3, int n4, int
un);
[DllImport("user32")] public static extern int DrawText(HDC
hdc, string lpStr, int nCount, ref RECT lpRect, int
wFormat);
[DllImport("user32")] public static extern int
DrawTextEx(HWND hdc, string lpsz, int n, ref RECT lpRect, int un, ref
DRAWTEXTPARAMS lpDrawTextParams);
[DllImport("user32")] public
static extern int EmptyClipboard();
[DllImport("user32")] public
static extern int EnableMenuItem(HANDLE hMenu, int wIDEnableItem, int
wEnable);
[DllImport("user32")] public static extern int
EnableScrollBar(HWND hwnd, int wSBflags, int
wArrows);
[DllImport("user32")] public static extern int
EnableWindow(HWND hwnd, int fEnable);
[DllImport("user32")]
public static extern int EndDeferWindowPos(HANDLE
hWinPosInfo);
[DllImport("user32")] public static extern int
EndDialog(HANDLE hDlg, int nResult);
[DllImport("user32")] public
static extern int EndPaint(HWND hwnd, ref PAINTSTRUCT
lpPaint);
[DllImport("user32")] public static extern int
EnumChildWindows(HWND hwndParent, ref int lpEnumFunc, int
lParam);
[DllImport("user32")] public static extern int
EnumClipboardFormats(int wFormat);
[DllImport("user32")] public
static extern int EnumDesktopWindows(HANDLE hDesktop, ref int lpfn, int
lParam);
[DllImport("user32")] public static extern int
EnumDesktops(HANDLE hwinsta, ref int lpEnumFunc, int
lParam);
[DllImport("user32")] public static extern int
EnumProps(HWND hwnd, ref int lpEnumFunc);
[DllImport("user32")]
public static extern int EnumPropsEx(HWND hwnd, ref int lpEnumFunc, int
lParam);
[DllImport("user32")] public static extern int
EnumThreadWindows(int dwThreadId, ref int lpfn, int
lParam);
[DllImport("user32")] public static extern int
EnumWindowStations(int lpEnumFunc, int
lParam);
[DllImport("user32")] public static extern int
EnumWindows(int lpEnumFunc, int lParam);
[DllImport("user32")]
public static extern int EqualRect(ref RECT lpRect1, ref RECT
lpRect2);
[DllImport("user32")] public static extern int
ExcludeUpdateRgn(HDC hdc, HWND hwnd);
[DllImport("user32")]
public static extern int ExitWindows(int dwReserved, int
uReturnCode);
[DllImport("user32")] public static extern int
ExitWindowsEx(int uFlags, int dwReserved);
[DllImport("user32")]
public static extern int FillRect(HDC hdc, ref RECT lpRect, HANDLE
hBrush);
[DllImport("user32")] public static extern int
FindWindow(string lpClassName, string
lpWindowName);
[DllImport("user32")] public static extern int
FindWindowEx(HWND hwnd1, HWND hwnd2, string lpsz1, string
lpsz2);
[DllImport("user32")] public static extern int
FlashWindow(HWND hwnd, int bInvert);
[DllImport("user32")] public
static extern int FrameRect(HDC hdc, ref RECT lpRect, HANDLE
hBrush);
[DllImport("user32")] public static extern int
FreeDDElParam(int msg, int lParam);
[DllImport("user32")] public
static extern int GetActiveWindow();
[DllImport("user32")] public
static extern int GetCapture();
[DllImport("user32")] public
static extern int GetCaretBlinkTime();
[DllImport("user32")]
public static extern int GetCaretPos(ref POINT
lpPoint);
[DllImport("user32")] public static extern int
GetClassInfo(HANDLE hInstance, string lpClassName, out WNDCLASS
lpWndClass);
[DllImport("user32")] public static extern int
GetClassLong(HWND hwnd, int nIndex);
[DllImport("user32")] public
static extern int GetClassName(HWND hwnd, string lpClassName, int
nMaxCount);
[DllImport("user32")] public static extern int
GetClassWord(HWND hwnd, int nIndex);
[DllImport("user32")] public
static extern int GetClientRect(HWND hwnd, ref RECT
lpRect);
[DllImport("user32")] public static extern int
GetClipCursor(out RECT lprc);
[DllImport("user32")] public static
extern int GetClipboardData(int wFormat);
[DllImport("user32")]
public static extern int GetClipboardFormatName(int wFormat, string lpString,
int nMaxCount);
[DllImport("user32")] public static extern int
GetClipboardOwner();
[DllImport("user32")] public static extern
int GetClipboardViewer();
[DllImport("user32")] public static
extern int GetCursor();
[DllImport("user32")] public static
extern int GetCursorPos(out POINT lpPoint);
[DllImport("user32")]
public static extern int GetDC(HWND hwnd);
[DllImport("user32")]
public static extern int GetDCEx(HWND hwnd, HANDLE hrgnclip, int
fdwOptions);
[DllImport("user32")] public static extern int
GetDesktopWindow();
[DllImport("user32")] public static extern
int GetDialogBaseUnits();
[DllImport("user32")] public static
extern int GetDlgCtrlID(HWND hwnd);
[DllImport("user32")] public
static extern int GetDlgItem(HANDLE hDlg, int
nIDDlgItem);
[DllImport("user32")] public static extern int
GetDlgItemInt(HANDLE hDlg, int nIDDlgItem, ref int lpTranslated, int
bSigned);
[DllImport("user32")] public static extern int
GetDlgItemText(HANDLE hDlg, int nIDDlgItem, StringBuilder lpString, int
nMaxCount);
[DllImport("user32")] public static extern int
GetDoubleClickTime();
[DllImport("user32")] public static extern
int GetFocus();
[DllImport("user32")] public static extern int
GetForegroundWindow();
[DllImport("user32")] public static extern
int GetIconInfo(HANDLE hIcon, out ICONINFO
piconinfo);
[DllImport("user32")] public static extern int
GetInputState();
[DllImport("user32")] public static extern int
GetKBCodePage();
[DllImport("user32")] public static extern int
GetKeyNameText(int lParam, StringBuilder lpBuffer, int
nSize);
[DllImport("user32")] public static extern int
GetKeyboardLayout(int dwLayout);
[DllImport("user32")] public
static extern int GetKeyboardLayoutList(int nBuff, ref int
lpList);
[DllImport("user32")] public static extern int
GetKeyboardLayoutName(string pwszKLID);
[DllImport("user32")]
public static extern int GetKeyboardState(Byte
pbKeyState);
[DllImport("user32")] public static extern int
GetKeyboardType(int nTypeFlag);
[DllImport("user32")] public
static extern int GetLastActivePopup(HWND
hwndOwnder);
[DllImport("user32")] public static extern int
GetMenu(HWND hwnd);
[DllImport("user32")] public static extern
int GetMenuCheckMarkDimensions();
[DllImport("user32")] public
static extern int GetMenuContextHelpId(HANDLE
hMenu);
[DllImport("user32")] public static extern int
GetMenuDefaultItem(HANDLE hMenu, int fByPos, int
gmdiFlags);
[DllImport("user32")] public static extern int
GetMenuItemCount(HANDLE hMenu);
[DllImport("user32")] public
static extern int GetMenuItemID(HANDLE hMenu, int
nPos);
[DllImport("user32")] public static extern int
GetMenuItemInfo(HANDLE hMenu, int un, int b, ref MENUITEMINFO
lpMenuItemInfo);
[DllImport("user32")] public static extern int
GetMenuItemRect(HWND hwnd, HANDLE hMenu, int uItem, ref RECT
lprcItem);
[DllImport("user32")] public static extern int
GetMenuState(HANDLE hMenu, int wID, int
wFlags);
[DllImport("user32")] public static extern int
GetMenuString(HANDLE hMenu, int wIDItem, StringBuilder lpString, int nMaxCount,
int wFlag);
[DllImport("user32")] public static extern int
GetMessage(ref MSG lpMsg, HWND hwnd, int wMsgFilterMin, int
wMsgFilterMax);
[DllImport("user32")] public static extern int
GetMessageExtraInfo();
[DllImport("user32")] public static extern
int GetMessagePos();
[DllImport("user32")] public static extern
int GetMessageTime();
[DllImport("user32")] public static extern
int GetNextDlgGroupItem(HANDLE hDlg, HANDLE hCtl, int
bPrevious);
[DllImport("user32")] public static extern int
GetNextDlgTabItem(HANDLE hDlg, HANDLE hCtl, int
bPrevious);
[DllImport("user32")] public static extern int
GetNextWindow(HWND hwnd, int wFlag);
[DllImport("user32")] public
static extern int GetOpenClipboardWindow();
[DllImport("user32")]
public static extern int GetParent(HWND
hwnd);
[DllImport("user32")] public static extern int
GetPriorityClipboardFormat(int lpPriorityList, int
nCount);
[DllImport("user32")] public static extern int
GetProcessWindowStation();
[DllImport("user32")] public static
extern int GetProp(HWND hwnd, string
lpString);
[DllImport("user32")] public static extern int
GetQueueStatus(int fuFlags);
[DllImport("user32")] public static
extern int GetScrollInfo(HWND hwnd, int n, ref SCROLLINFO
lpScrollInfo);
[DllImport("user32")] public static extern int
GetScrollPos(HWND hwnd, int nBar);
[DllImport("user32")] public
static extern int GetScrollRange(HWND hwnd, int nBar, ref int lpMinPos, ref int
lpMaxPos);
[DllImport("user32")] public static extern int
GetSubMenu(HANDLE hMenu, int nPos);
[DllImport("user32")] public
static extern int GetSysColor(int nIndex);
[DllImport("user32")]
public static extern int GetSysColorBrush(int
nIndex);
[DllImport("user32")] public static extern int
GetSystemMenu(HWND hwnd, int bRevert);
[DllImport("user32")]
public static extern int GetSystemMetrics(int
nIndex);
[DllImport("user32")] public static extern int
GetTabbedTextExtent(HDC hdc, string lpString, int nCount, int nTabPositions, ref
int lpnTabStopPositions);
[DllImport("user32")] public static
extern int GetThreadDesktop(int dwThread);
[DllImport("user32")]
public static extern int GetTopWindow(HWND
hwnd);
[DllImport("user32")] public static extern int
GetUpdateRect(HWND hwnd, ref RECT lpRect, int
bErase);
[DllImport("user32")] public static extern int
GetUpdateRgn(HWND hwnd, HANDLE hRgn, int
fErase);
[DllImport("user32")] public static extern int
GetUserObjectInformation(HANDLE hObj, int nIndex, IntPtr pvInfo, int nLength,
ref int lpnLengthNeeded);
[DllImport("user32")] public static
extern int GetUserObjectSecurity(HANDLE hObj, ref int pSIRequested, ref
SECURITY_DESCRIPTOR pSd, int nLength, ref int
lpnLengthNeeded);
[DllImport("user32")] public static extern int
GetWindow(HWND hwnd, int wCmd);
[DllImport("user32")] public
static extern int GetWindowContextHelpId(HWND
hwnd);
[DllImport("user32")] public static extern int
GetWindowDC(HWND hwnd);
[DllImport("user32")] public static
extern int GetWindowLong(HWND hwnd, int
nIndex);
[DllImport("user32")] public static extern int
GetWindowPlacement(HWND hwnd, ref WINDOWPLACEMENT
lpwndpl);
[DllImport("user32")] public static extern int
GetWindowRect(HWND hwnd, ref RECT lpRect);
[DllImport("user32")]
public static extern int GetWindowRgn(HWND hwnd, HANDLE
hRgn);
[DllImport("user32")] public static extern int
GetWindowText(HWND hwnd, StringBuilder lpString, int
cch);
[DllImport("user32")] public static extern int
GetWindowTextLength(HWND hwnd);
[DllImport("user32")] public
static extern int GetWindowThreadProcessId(HWND hwnd, ref int
lpdwProcessId);
[DllImport("user32")] public static extern int
GrayString(HWND hdc, HANDLE hBrush, ref int lpOutputFunc, ref int lpData, int
nCount, int X, int Y, int nWidth, int
nHeight);
[DllImport("user32")] public static extern int
HideCaret(HWND hwnd);
[DllImport("user32")] public static extern
int HiliteMenuItem(HWND hwnd, HANDLE hMenu, int wIDHiliteItem, int
wHilite);
[DllImport("user32")] public static extern int
ImpersonateDdeClientWindow(HWND hwndClient, HWND
hwndServer);
[DllImport("user32")] public static extern int
InSendMessage();
[DllImport("user32")] public static extern int
InflateRect(ref RECT lpRect, int x, int y);
[DllImport("user32")]
public static extern int InsertMenu(HANDLE hMenu, int nPosition, int wFlags, int
wIDNewItem, IntPtr lpNewItem);
[DllImport("user32")] public
static extern int InsertMenuItem(HANDLE hMenu, int un, bool b, ref MENUITEMINFO
lpcMenuItemInfo);
[DllImport("user32")] public static extern int
IntersectRect(ref RECT lpDestRect, ref RECT lpSrc1Rect, ref RECT
lpSrc2Rect);
[DllImport("user32")] public static extern int
InvalidateRect(HWND hwnd, ref RECT lpRect, int
bErase);
[DllImport("user32")] public static extern int
InvalidateRgn(HWND hwnd, HANDLE hRgn, int
bErase);
[DllImport("user32")] public static extern int
InvertRect(HDC hdc, ref RECT lpRect);
[DllImport("user32")]
public static extern int IsCharAlpha(Byte
cChar);
[DllImport("user32")] public static extern int
IsCharAlphaNumeric(Byte cChar);
[DllImport("user32")] public
static extern int IsCharLower(Byte cChar);
[DllImport("user32")]
public static extern int IsCharUpper(Byte
cChar);
[DllImport("user32")] public static extern int
IsChild(HWND hwndParent, HWND hwnd);
[DllImport("user32")] public
static extern int IsClipboardFormatAvailable(int
wFormat);
[DllImport("user32")] public static extern int
IsDialogMessage(HANDLE hDlg, ref MSG
lpMsg);
[DllImport("user32")] public static extern int
IsDlgButtonChecked(HANDLE hDlg, int
nIDButton);
[DllImport("user32")] public static extern int
IsIconic(HWND hwnd);
[DllImport("user32")] public static extern
int IsMenu(HANDLE hMenu);
[DllImport("user32")] public static
extern int IsRectEmpty(ref RECT lpRect);
[DllImport("user32")]
public static extern int IsWindow(HWND
hwnd);
[DllImport("user32")] public static extern int
IsWindowEnabled(HWND hwnd);
[DllImport("user32")] public static
extern int IsWindowUnicode(HWND hwnd);
[DllImport("user32")]
public static extern int IsWindowVisible(HWND
hwnd);
[DllImport("user32")] public static extern int
IsZoomed(HWND hwnd);
[DllImport("user32")] public static extern
int KillTimer(HWND hwnd, int nIDEvent);
[DllImport("user32")]
public static extern int LoadAccelerators(HANDLE hInstance, string
lpTableName);
[DllImport("user32")] public static extern int
LoadBitmap(HANDLE hInstance, string
lpBitmapName);
[DllImport("user32")] public static extern int
LoadCursor(HANDLE hInstance, string
lpCursorName);
[DllImport("user32")] public static extern int
LoadCursorFromFile(string lpFileName);
[DllImport("user32")]
public static extern int LoadIcon(HANDLE hInstance, string
lpIconName);
[DllImport("user32")] public static extern int
LoadImage(HANDLE hInst, string lpsz, int un1, int n1, int n2, int
un2);
[DllImport("user32")] public static extern int
LoadKeyboardLayout(string pwszKLID, int
flags);
[DllImport("user32")] public static extern int
LoadMenu(HANDLE hInstance, string
lpString);
[DllImport("user32")] public static extern int
LoadMenuIndirect(int lpMenuTemplate);
[DllImport("user32")]
public static extern int LoadString(HANDLE hInstance, int wID, string lpBuffer,
int nBufferMax);
[DllImport("user32")] public static extern int
LockWindowUpdate(HWND hwndLock);
[DllImport("user32")] public
static extern int LookupIconIdFromDirectory(Byte presbits, int
fIcon);
[DllImport("user32")] public static extern int
LookupIconIdFromDirectoryEx(Byte presbits, int fIcon, int cxDesired, int
cyDesired, int Flags);
[DllImport("user32")] public static extern
int MapDialogRect(HANDLE hDlg, ref RECT
lpRect);
[DllImport("user32")] public static extern int
MapVirtualKey(int wCode, int wMapType);
[DllImport("user32")]
public static extern int MapVirtualKeyEx(int uCode, int uMapType, int
dwhkl);
[DllImport("user32")] public static extern int
MapWindowPoints(HWND hwndFrom, HWND hwndTo, POINT [] lppt, int
cPoints);
[DllImport("user32")] public static extern int
MenuItemFromPoint(HWND hwnd, HANDLE hMenu, POINT
ptScreen);
[DllImport("user32")] public static extern int
MessageBeep(int wType);
[DllImport("user32")] public static
extern int MessageBox(HWND hwnd, string lpText, string lpCaption, int
wType);
[DllImport("user32")] public static extern int
MessageBoxEx(HWND hwnd, string lpText, string lpCaption, int uType, int
wLanguageId);
[DllImport("user32")] public static extern int
MessageBoxIndirect(ref MSGBOXPARAMS
lpMsgBoxParams);
[DllImport("user32")] public static extern int
ModifyMenu(HANDLE hMenu, int nPosition, int wFlags, int wIDNewItem, IntPtr
lpString);
[DllImport("user32")] public static extern int
MoveWindow(HWND hwnd, int x, int y, int nWidth, int nHeight, int
bRepaint);
[DllImport("user32")] public static extern int
MsgWaitForMultipleObjects(int nCount, ref int pHandles, int fWaitAll, int
dwMilliseconds, int dwWakeMask);
[DllImport("user32")] public
static extern int OemKeyScan(int wOemChar);
[DllImport("user32")]
public static extern int OemToChar(string lpszSrc, string
lpszDst);
[DllImport("user32")] public static extern int
OemToCharBuff(string lpszSrc, string lpszDst, int
cchDstLength);
[DllImport("user32")] public static extern int
OffsetRect(ref RECT lpRect, int x, int y);
[DllImport("user32")]
public static extern int OpenClipboard(HWND
hwnd);
[DllImport("user32")] public static extern int
OpenDesktop(string lpszDesktop, int dwFlags, int fInherit, int
dwDesiredAccess);
[DllImport("user32")] public static extern int
OpenIcon(HWND hwnd);
[DllImport("user32")] public static extern
int OpenInputDesktop(int dwFlags, int fInherit, int
dwDesiredAccess);
[DllImport("user32")] public static extern int
OpenWindowStation(string lpszWinSta, int fInherit, int
dwDesiredAccess);
[DllImport("user32")] public static extern int
PackDDElParam(int msg, int uiLo, int uiHi);
[DllImport("user32")]
public static extern int PaintDesktop(HDC
hdc);
[DllImport("user32")] public static extern int
PeekMessage(ref MSG lpMsg, HWND hwnd, int wMsgFilterMin, int wMsgFilterMax, int
wRemoveMsg);
[DllImport("user32")] public static extern int
PostMessage(HWND hwnd, int wMsg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
PostThreadMessage(int idThread, int msg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
PtInRect(ref RECT lpRect, int ptX, int
ptY);
[DllImport("user32")] public static extern int
RedrawWindow(HWND hwnd, ref RECT lprcUpdate, HANDLE hrgnUpdate, int
fuRedraw);
[DllImport("user32")] public static extern int
RegisterClass(ref WNDCLASS Class);
[DllImport("user32")] public
static extern int RegisterClipboardFormat(string
lpString);
[DllImport("user32")] public static extern int
RegisterHotKey(HWND hwnd, int id, int fsModifiers, int
vk);
[DllImport("user32")] public static extern int
RegisterWindowMessage(string lpString);
[DllImport("user32")]
public static extern int ReleaseCapture();
[DllImport("user32")]
public static extern int ReleaseDC(HWND hwnd, HDC
hdc);
[DllImport("user32")] public static extern int
RemoveMenu(HANDLE hMenu, int nPosition, int
wFlags);
[DllImport("user32")] public static extern int
RemoveProp(HWND hwnd, string lpString);
[DllImport("user32")]
public static extern int ReplyMessage(int
lReply);
[DllImport("user32")] public static extern int
ReuseDDElParam(int lParam, int msgIn, int msgOut, int uiLo, int
uiHi);
[DllImport("user32")] public static extern int
ScreenToClient(HWND hwnd, ref POINT
lpPoint);
[DllImport("user32")] public static extern int
ScrollDC(HDC hdc, int dx, int dy, ref RECT lprcScroll, ref RECT lprcClip, HANDLE
hrgnUpdate, ref RECT lprcUpdate);
[DllImport("user32")] public
static extern int ScrollWindow(HWND hwnd, int XAmount, int YAmount, ref RECT
lpRect, ref RECT lpClipRect);
[DllImport("user32")] public static
extern int ScrollWindowEx(HWND hwnd, int dx, int dy, ref RECT lprcScroll, ref
RECT lprcClip, HANDLE hrgnUpdate, ref RECT lprcUpdate, int
fuScroll);
[DllImport("user32")] public static extern int
SendDlgItemMessage(HANDLE hDlg, int nIDDlgItem, int wMsg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
SendMessage(HWND hwnd, int wMsg, int wParam, IntPtr
lParam);
[DllImport("user32")] public static extern int
SendMessageCallback(HWND hwnd, int msg, int wParam, int lParam, ref int
lpResultCallBack, int dwData);
[DllImport("user32")] public
static extern int SendMessageTimeout(HWND hwnd, int msg, int wParam, int lParam,
int fuFlags, int uTimeout, ref int
lpdwResult);
[DllImport("user32")] public static extern int
SendNotifyMessage(HWND hwnd, int msg, int wParam, int
lParam);
[DllImport("user32")] public static extern int
SetActiveWindow(HWND hwnd);
[DllImport("user32")] public static
extern int SetCapture(HWND hwnd);
[DllImport("user32")] public
static extern int SetCaretBlinkTime(int
wMSeconds);
[DllImport("user32")] public static extern int
SetCaretPos(int x, int y);
[DllImport("user32")] public static
extern int SetClassLong(HWND hwnd, int nIndex, int
dwNewLong);
[DllImport("user32")] public static extern int
SetClassWord(HWND hwnd, int nIndex, int
wNewWord);
[DllImport("user32")] public static extern int
SetClipboardData(int wFormat, HANDLE hMem);
[DllImport("user32")]
public static extern int SetClipboardViewer(HWND
hwnd);
[DllImport("user32")] public static extern int
SetCursor(HANDLE hCursor);
[DllImport("user32")] public static
extern int SetCursorPos(int x, int y);
[DllImport("user32")]
public static extern int SetDlgItemInt(HANDLE hDlg, int nIDDlgItem, int wValue,
int bSigned);
[DllImport("user32")] public static extern int
SetDlgItemText(HANDLE hDlg, int nIDDlgItem, string
lpString);
[DllImport("user32")] public static extern int
SetDoubleClickTime(int wCount);
[DllImport("user32")] public
static extern int SetFocus(HWND hwnd);
[DllImport("user32")]
public static extern int SetForegroundWindow(HWND
hwnd);
[DllImport("user32")] public static extern int
SetKeyboardState(Byte lppbKeyState);
[DllImport("user32")] public
static extern int SetMenu(HWND hwnd, HANDLE
hMenu);
[DllImport("user32")] public static extern int
SetMenuContextHelpId(HANDLE hMenu, int dw);
[DllImport("user32")]
public static extern int SetMenuDefaultItem(HANDLE hMenu, int uItem, int
fByPos);
[DllImport("user32")] public static extern int
SetMenuItemBitmaps(HANDLE hMenu, int nPosition, int wFlags, HANDLE
hBitmapUnchecked, HANDLE hBitmapChecked);
[DllImport("user32")]
public static extern int SetMenuItemInfo(HANDLE hMenu, int un, bool b, ref
MENUITEMINFO lpcMenuItemInfo);
[DllImport("user32")] public
static extern int SetMessageExtraInfo(int
lParam);
[DllImport("user32")] public static extern int
SetMessageQueue(int cMessagesMax);
[DllImport("user32")] public
static extern int SetParent(HWND hwndChild, HWND
hwndNewParent);
[DllImport("user32")] public static extern int
SetProcessWindowStation(HANDLE hWinSta);
[DllImport("user32")]
public static extern int SetProp(HWND hwnd, string lpString, HANDLE
hData);
[DllImport("user32")] public static extern int
SetRect(ref RECT lpRect, int X1, int Y1, int X2, int
Y2);
[DllImport("user32")] public static extern int
SetRectEmpty(ref RECT lpRect);
[DllImport("user32")] public
static extern int SetScrollInfo(HWND hwnd, int n, ref SCROLLINFO lpcScrollInfo,
bool redraw);
[DllImport("user32")] public static extern int
SetScrollPos(HWND hwnd, int nBar, int nPos, int
bRedraw);
[DllImport("user32")] public static extern int
SetScrollRange(HWND hwnd, int nBar, int nMinPos, int nMaxPos, int
bRedraw);
[DllImport("user32")] public static extern int
SetSysColors(int nChanges, ref int lpSysColor, ref int
lpColorValues);
[DllImport("user32")] public static extern int
SetSystemCursor(HANDLE hcur, int id);
[DllImport("user32")]
public static extern int SetThreadDesktop(HANDLE
hDesktop);
[DllImport("user32")] public static extern int
SetTimer(HWND hwnd, int nIDEvent, int uElapse, ref int
lpTimerFunc);
[DllImport("user32")] public static extern int
SetUserObjectInformation(HANDLE hObj, int nIndex, IntPtr pvInfo, int
nLength);
[DllImport("user32")] public static extern int
SetUserObjectSecurity(HANDLE hObj, ref int pSIRequested, ref SECURITY_DESCRIPTOR
pSd);
[DllImport("user32")] public static extern int
SetWindowContextHelpId(HWND hwnd, int dw);
[DllImport("user32")]
public static extern int SetWindowLong(HWND hwnd, int nIndex, int
dwNewLong);
[DllImport("user32")] public static extern int
SetWindowPlacement(HWND hwnd, ref WINDOWPLACEMENT
lpwndpl);
[DllImport("user32")] public static extern int
SetWindowPos(HWND hwnd, HWND hwndInsertAfter, int x, int y, int cx, int cy, int
wFlags);
[DllImport("user32")] public static extern int
SetWindowRgn(HWND hwnd, HANDLE hRgn, int
bRedraw);
[DllImport("user32")] public static extern int
SetWindowText(HWND hwnd, string lpString);
[DllImport("user32")]
public static extern int SetWindowWord(HWND hwnd, int nIndex, int
wNewWord);
[DllImport("user32")] public static extern int
SetWindowsHook(int nFilterType, ref int
pfnFilterProc);
[DllImport("user32")] public static extern int
SetWindowsHookEx(int idHook, ref int lpfn, HANDLE hmod, int
dwThreadId);
[DllImport("user32")] public static extern int
ShowCaret(HWND hwnd);
[DllImport("user32")] public static extern
int ShowCursor(int bShow);
[DllImport("user32")] public static
extern int ShowOwnedPopups(HWND hwnd, int
fShow);
[DllImport("user32")] public static extern int
ShowScrollBar(HWND hwnd, int wBar, int
bShow);
[DllImport("user32")] public static extern int
ShowWindow(HWND hwnd, int nCmdShow);
[DllImport("user32")] public
static extern int ShowWindowAsync(HWND hwnd, int
nCmdShow);
[DllImport("user32")] public static extern int
SubtractRect(ref RECT lprcDst, ref RECT lprcSrc1, ref RECT
lprcSrc2);
[DllImport("user32")] public static extern int
SwapMouseButton(int bSwap);
[DllImport("user32")] public static
extern int SwitchDesktop(HANDLE hDesktop);
[DllImport("user32")]
public static extern int SystemParametersInfo(int uAction, int uParam, ref
IntPtr lpvParam, int fuWinIni);
[DllImport("user32")] public
static extern int TabbedTextOut(HDC hdc, int x, int y, string lpString, int
nCount, int nTabPositions, ref int lpnTabStopPositions, int
nTabOrigin);
[DllImport("user32")] public static extern int
ToAscii(int uVirtKey, int uScanCode, Byte lpbKeyState, ref int lpwTransKey, int
fuState);
[DllImport("user32")] public static extern int
ToAsciiEx(int uVirtKey, int uScanCode, Byte lpKeyState, short lpChar, int
uFlags, int dwhkl);
[DllImport("user32")] public static extern
int ToUnicode(int wVirtKey, int wScanCode, Byte lpKeyState, string pwszBuff, int
cchBuff, int wFlags);
[DllImport("user32")] public static extern
int TrackPopupMenu(HANDLE hMenu, int wFlags, int x, int y, int nReserved, HWND
hwnd, ref RECT lprc);
[DllImport("user32")] public static extern
int TrackPopupMenuEx(HANDLE hMenu, int un, int n1, int n2, HWND hwnd, ref
TPMPARAMS lpTPMParams);
[DllImport("user32")] public static
extern int TranslateAccelerator(HWND hwnd, HANDLE hAccTable, ref MSG
lpMsg);
[DllImport("user32")] public static extern int
TranslateMDISysAccel(HWND hwndClient, ref MSG
lpMsg);
[DllImport("user32")] public static extern int
TranslateMessage(ref MSG lpMsg);
[DllImport("user32")] public
static extern int UnhookWindowsHook(int nCode, ref int
pfnFilterProc);
[DllImport("user32")] public static extern int
UnhookWindowsHookEx(HANDLE hHook);
[DllImport("user32")] public
static extern int UnionRect(ref RECT lpDestRect, ref RECT lpSrc1Rect, ref RECT
lpSrc2Rect);
[DllImport("user32")] public static extern int
UnloadKeyboardLayout(HANDLE hKL);
[DllImport("user32")] public
static extern int UnpackDDElParam(int msg, int lParam, ref int puiLo, ref int
puiHi);
[DllImport("user32")] public static extern int
UnregisterClass(string lpClassName, HANDLE
hInstance);
[DllImport("user32")] public static extern int
UnregisterHotKey(HWND hwnd, int id);
[DllImport("user32")] public
static extern int UpdateWindow(HWND hwnd);
[DllImport("user32")]
public static extern int ValidateRect(HWND hwnd, ref RECT
lpRect);
[DllImport("user32")] public static extern int
ValidateRgn(HWND hwnd, HANDLE hRgn);
[DllImport("user32")] public
static extern int WaitForInputIdle(HANDLE hProcess, int
dwMilliseconds);
[DllImport("user32")] public static extern int
WaitMessage();
[DllImport("user32")] public static extern int
WinHelp(HWND hwnd, string lpHelpFile, int wCommand, int
dwData);
[DllImport("user32")] public static extern int
WindowFromDC(HDC hdc);
[DllImport("user32")] public static extern
int WindowFromPoint(int xPoint, int
yPoint);
[DllImport("user32")] public static extern short
CascadeWindows(HWND hwndParent, int wHow, ref RECT lpRect, int cKids, ref int
lpkids);
[DllImport("user32")] public static extern short
GetAsyncKeyState(int vKey);
[DllImport("user32")] public static
extern short GetKeyState(int nVirtKey);
[DllImport("user32")]
public static extern short GetWindowWord(HWND hwnd, int
nIndex);
[DllImport("user32")] public static extern short
RegisterClassEx(ref WNDCLASSEX
pcWndClassEx);
[DllImport("user32")] public static extern short
TileWindows(HWND hwndParent, int wHow, ref RECT lpRect, int cKids, ref int
lpKids);
[DllImport("user32")] public static extern short
VkKeyScan(Byte cChar);
[DllImport("user32")] public static extern
short VkKeyScanEx(Byte ch, int dwhkl);
[DllImport("user32")]
public static extern string CharLower(string
lpsz);
[DllImport("user32")] public static extern string
CharNext(string lpsz);
[DllImport("user32")] public static extern
string CharPrev(string lpszStart, string
lpszCurrent);
[DllImport("user32")] public static extern string
CharUpper(string lpsz);
[DllImport("user32")] public static
extern void PostQuitMessage(int nExitCode);
[DllImport("user32")]
public static extern void keybd_event(Byte bVk, Byte bScan, int dwFlags, int
dwExtraInfo);
[DllImport("user32")] public static extern void
mouse_event(int dwFlags, int dx, int dy, int cButtons, int
dwExtraInfo);
[DllImport("user32")] public static extern void
SetDebugErrorLevel(int dwLevel);
[DllImport("user32")] public
static extern void SetLastErrorEx(int dwErrCode, int dwType);
public const int APPCLASS_MASK = 0xF;
public const int APPCLASS_MONITOR = 0x1;
public const int APPCLASS_STANDARD = 0x0;
public const int APPCMD_CLIENTONLY = 0x10;
public const int APPCMD_FILTERINITS = 0x20;
public const int APPCMD_MASK = 0xFF0;
public const int BDR_INNER = 0xC;
public const int BDR_OUTER = 0x3;
public const int BDR_RAISED = 0x5;
public const int BDR_RAISEDINNER = 0x4;
public const int BDR_RAISEDOUTER = 0x1;
public const int BDR_SUNKEN = 0xA;
public const int BDR_SUNKENINNER = 0x8;
public const int BDR_SUNKENOUTER = 0x2;
public const int BF_ADJUST = 0x2000;
public const int BF_BOTTOM = 0x8;
public const int BF_BOTTOMLEFT = (BF_BOTTOM | BF_LEFT);
public const int BF_BOTTOMRIGHT = (BF_BOTTOM | BF_RIGHT);
public const int BF_DIAGONAL = 0x10;
public const int BF_DIAGONAL_ENDBOTTOMLEFT = (BF_DIAGONAL | BF_BOTTOM | BF_LEFT);
public const int BF_DIAGONAL_ENDBOTTOMRIGHT = (BF_DIAGONAL | BF_BOTTOM | BF_RIGHT);
public const int BF_DIAGONAL_ENDTOPLEFT = (BF_DIAGONAL | BF_TOP | BF_LEFT);
public const int BF_DIAGONAL_ENDTOPRIGHT = (BF_DIAGONAL | BF_TOP | BF_RIGHT);
public const int BF_FLAT = 0x4000;
public const int BF_LEFT = 0x1;
public const int BF_MIDDLE = 0x800;
public const int BF_MONO = 0x8000;
public const int BF_RECT = (BF_LEFT | BF_TOP | BF_RIGHT | BF_BOTTOM);
public const int BF_RIGHT = 0x4;
public const int BF_SOFT = 0x1000;
public const int BF_TOP = 0x2;
public const int BF_TOPLEFT = (BF_TOP | BF_LEFT);
public const int BF_TOPRIGHT = (BF_TOP | BF_RIGHT);
public const int BIF_BROWSEFORCOMPUTER = 4096;
public const int BIF_BROWSEFORPRINTER = 8192;
public const int BIF_BROWSEINCLUDEFILES = 16384;
public const int BIF_BROWSEINCLUDEURLS = 128;
public const int BIF_DONTGOBELOWDOMAIN = 2;
public const int BIF_EDITBOX = 16;
public const int BIF_RETURNFSANCESTORS = 8;
public const int BIF_RETURNONLYFSDIRS = 1;
public const int BIF_SHAREABLE = 32768;
public const int BIF_STATUSTEXT = 4;
public const int BIF_USENEWUI = 64;
public const int BIF_VALIDATE = 32;
public const int BM_GETCHECK = 0xF0;
public const int BM_GETSTATE = 0xF2;
public const int BM_SETCHECK = 0xF1;
public const int BM_SETSTATE = 0xF3;
public const int BM_SETSTYLE = 0xF4;
public const int BN_CLICKED = 0;
public const int BN_DISABLE = 4;
public const int BN_DOUBLECLICKED = 5;
public const int BN_HILITE = 2;
public const int BN_PAINT = 1;
public const int BN_UNHILITE = 3;
public const int BS_3STATE = 0x5;
public const int BS_AUTO3STATE = 0x6;
public const int BS_AUTOCHECKBOX = 0x3;
public const int BS_AUTORADIOBUTTON = 0x9;
public const int BS_CHECKBOX = 0x2;
public const int BS_DEFPUSHBUTTON = 0x1;
public const int BS_GROUPBOX = 0x7;
public const int BS_LEFTTEXT = 0x20;
public const int BS_OWNERDRAW = 0xB;
public const int BS_PUSHBUTTON = 0x0;
public const int BS_RADIOBUTTON = 0x4;
public const int BS_USERBUTTON = 0x8;
public const int CADV_LATEACK = 0xFFFF;
public const int CBF_FAIL_ADVISES = 0x4000;
public const int CBF_FAIL_ALLSVRXACTIONS = 0x3F000;
public const int CBF_FAIL_CONNECTIONS = 0x2000;
public const int CBF_FAIL_EXECUTES = 0x8000;
public const int CBF_FAIL_POKES = 0x10000;
public const int CBF_FAIL_REQUESTS = 0x20000;
public const int CBF_FAIL_SELFCONNECTIONS = 0x1000;
public const int CBF_SKIP_ALLNOTIFICATIONS = 0x3C0000;
public const int CBF_SKIP_CONNECT_CONFIRMS = 0x40000;
public const int CBF_SKIP_DISCONNECTS = 0x200000;
public const int CBF_SKIP_REGISTRATIONS = 0x80000;
public const int CBF_SKIP_UNREGISTRATIONS = 0x100000;
public const int CBN_CLOSEUP = 8;
public const int CBN_DBLCLK = 2;
public const int CBN_DROPDOWN = 7;
public const int CBN_EDITCHANGE = 5;
public const int CBN_EDITUPDATE = 6;
public const int CBN_ERRSPACE = (-1);
public const int CBN_KILLFOCUS = 4;
public const int CBN_SELCHANGE = 1;
public const int CBN_SELENDCANCEL = 10;
public const int CBN_SELENDOK = 9;
public const int CBN_SETFOCUS = 3;
public const int CBR_BLOCK = 0xFFFF;
public const int CBS_AUTOHSCROLL = 0x40;
public const int CBS_DISABLENOSCROLL = 0x800;
public const int CBS_DROPDOWN = 0x2;
public const int CBS_DROPDOWNLIST = 0x3;
public const int CBS_HASSTRINGS = 0x200;
public const int CBS_NOINTEGRALHEIGHT = 0x400;
public const int CBS_OEMCONVERT = 0x80;
public const int CBS_OWNERDRAWFIXED = 0x10;
public const int CBS_OWNERDRAWVARIABLE = 0x20;
public const int CBS_SIMPLE = 0x1;
public const int CBS_SORT = 0x100;
public const int CB_ADDSTRING = 0x143;
public const int CB_DELETESTRING = 0x144;
public const int CB_DIR = 0x145;
public const int CB_ERR = (-1);
public const int CB_ERRSPACE = (-2);
public const int CB_FINDSTRING = 0x14C;
public const int CB_FINDSTRINGEXACT = 0x158;
public const int CB_GETCOUNT = 0x146;
public const int CB_GETCURSEL = 0x147;
public const int CB_GETDROPPEDCONTROLRECT = 0x152;
public const int CB_GETDROPPEDSTATE = 0x157;
public const int CB_GETEDITSEL = 0x140;
public const int CB_GETEXTENDEDUI = 0x156;
public const int CB_GETITEMDATA = 0x150;
public const int CB_GETITEMHEIGHT = 0x154;
public const int CB_GETLBTEXT = 0x148;
public const int CB_GETLBTEXTLEN = 0x149;
public const int CB_GETLOCALE = 0x15A;
public const int CB_INSERTSTRING = 0x14A;
public const int CB_LIMITTEXT = 0x141;
public const int CB_MSGMAX = 0x15B;
public const int CB_OKAY = 0;
public const int CB_RESETCONTENT = 0x14B;
public const int CB_SELECTSTRING = 0x14D;
public const int CB_SETCURSEL = 0x14E;
public const int CB_SETEDITSEL = 0x142;
public const int CB_SETEXTENDEDUI = 0x155;
public const int CB_SETITEMDATA = 0x151;
public const int CB_SETITEMHEIGHT = 0x153;
public const int CB_SETLOCALE = 0x159;
public const int CB_SHOWDROPDOWN = 0x14F;
public const int CF_BITMAP = 2;
public const int CF_DIB = 8;
public const int CF_DIF = 5;
public const int CF_DSPBITMAP = 0x82;
public const int CF_DSPENHMETAFILE = 0x8E;
public const int CF_DSPMETAFILEPICT = 0x83;
public const int CF_DSPTEXT = 0x81;
public const int CF_ENHMETAFILE = 14;
public const int CF_GDIOBJFIRST = 0x300;
public const int CF_GDIOBJLAST = 0x3FF;
public const int CF_METAFILEPICT = 3;
public const int CF_OEMTEXT = 7;
public const int CF_OWNERDISPLAY = 0x80;
public const int CF_PALETTE = 9;
public const int CF_PENDATA = 10;
public const int CF_PRIVATEFIRST = 0x200;
public const int CF_PRIVATELAST = 0x2FF;
public const int CF_RIFF = 11;
public const int CF_SYLK = 4;
public const int CF_TEXT = 1;
public const int CF_TIFF = 6;
public const int CF_UNICODETEXT = 13;
public const int CF_WAVE = 12;
public const int CN_EVENT = 0x4;
public const int CN_RECEIVE = 0x1;
public const int CN_TRANSMIT = 0x2;
public const int COLOR_ACTIVEBORDER = 10;
public const int COLOR_ACTIVECAPTION = 2;
public const int COLOR_APPWORKSPACE = 12;
public const int COLOR_BACKGROUND = 1;
public const int COLOR_BTNFACE = 15;
public const int COLOR_BTNHIGHLIGHT = 20;
public const int COLOR_BTNSHADOW = 16;
public const int COLOR_BTNTEXT = 18;
public const int COLOR_CAPTIONTEXT = 9;
public const int COLOR_GRAYTEXT = 17;
public const int COLOR_HIGHLIGHT = 13;
public const int COLOR_HIGHLIGHTTEXT = 14;
public const int COLOR_INACTIVEBORDER = 11;
public const int COLOR_INACTIVECAPTION = 3;
public const int COLOR_INACTIVECAPTIONTEXT = 19;
public const int COLOR_MENU = 4;
public const int COLOR_MENUTEXT = 7;
public const int COLOR_SCROLLBAR = 0;
public const int COLOR_WINDOW = 5;
public const int COLOR_WINDOWFRAME = 6;
public const int COLOR_WINDOWTEXT = 8;
public const int CP_WINANSI = 1004;
public const int CP_WINUNICODE = 1200;
public const int CS_BYTEALIGNCLIENT = 0x1000;
public const int CS_BYTEALIGNWINDOW = 0x2000;
public const int CS_CLASSDC = 0x40;
public const int CS_DBLCLKS = 0x8;
public const int CS_HREDRAW = 0x2;
public const int CS_KEYCVTWINDOW = 0x4;
public const int CS_NOCLOSE = 0x200;
public const int CS_NOKEYCVT = 0x100;
public const int CS_OWNDC = 0x20;
public const int CS_PARENTDC = 0x80;
public const int CS_PUBLICCLASS = 0x4000;
public const int CS_SAVEBITS = 0x800;
public const int CS_VREDRAW = 0x1;
public const int CTLCOLOR_BTN = 3;
public const int CTLCOLOR_DLG = 4;
public const int CTLCOLOR_EDIT = 1;
public const int CTLCOLOR_LISTBOX = 2;
public const int CTLCOLOR_MAX = 8;
public const int CTLCOLOR_MSGBOX = 0;
public const int CTLCOLOR_SCROLLBAR = 5;
public const int CTLCOLOR_STATIC = 6;
public const int CW_USEDEFAULT = unchecked((int)0x80000000);
public const int DCX_CACHE = 0x2;
public const int DCX_CLIPCHILDREN = 0x8;
public const int DCX_CLIPSIBLINGS = 0x10;
public const int DCX_EXCLUDERGN = 0x40;
public const int DCX_EXCLUDEUPDATE = 0x100;
public const int DCX_INTERSECTRGN = 0x80;
public const int DCX_INTERSECTUPDATE = 0x200;
public const int DCX_LOCKWINDOWUPDATE = 0x400;
public const int DCX_NORECOMPUTE = 0x100000;
public const int DCX_NORESETATTRS = 0x4;
public const int DCX_PARENTCLIP = 0x20;
public const int DCX_VALIDATE = 0x200000;
public const int DCX_WINDOW = 0x1;
public const int DC_HASDEFID = 0x534;
public const int DDE_FACK = 0x8000;
public const int DDE_FACKREQ = 0x8000;
public const int DDE_FACKRESERVED = (~ (DDE_FACK | DDE_FBUSY | DDE_FAPPSTATUS));
public const int DDE_FADVRESERVED = (~ (DDE_FACKREQ | DDE_FDEFERUPD));
public const int DDE_FAPPSTATUS = 0xFF;
public const int DDE_FBUSY = 0x4000;
public const int DDE_FDATRESERVED = (~ (DDE_FACKREQ | DDE_FRELEASE | DDE_FREQUESTED));
public const int DDE_FDEFERUPD = 0x4000;
public const int DDE_FNOTPROCESSED = 0x0;
public const int DDE_FPOKRESERVED = (~ (DDE_FRELEASE));
public const int DDE_FRELEASE = 0x2000;
public const int DDE_FREQUESTED = 0x1000;
public const int DDL_ARCHIVE = 0x20;
public const int DDL_DIRECTORY = 0x10;
public const int DDL_DRIVES = 0x4000;
public const int DDL_EXCLUSIVE = 0x8000;
public const int DDL_HIDDEN = 0x2;
public const int DDL_POSTMSGS = 0x2000;
public const int DDL_READONLY = 0x1;
public const int DDL_READWRITE = 0x0;
public const int DDL_SYSTEM = 0x4;
public const int DESKTOP_CREATEMENU = 0x4;
public const int DESKTOP_CREATEWINDOW = 0x2;
public const int DESKTOP_ENUMERATE = 0x40;
public const int DESKTOP_HOOKCONTROL = 0x8;
public const int DESKTOP_JOURNALPLAYBACK = 0x20;
public const int DESKTOP_JOURNALRECORD = 0x10;
public const int DESKTOP_READOBJECTS = 0x1;
public const int DESKTOP_WRITEOBJECTS = 0x80;
public const int DLGC_BUTTON = 0x2000;
public const int DLGC_DEFPUSHBUTTON = 0x10;
public const int DLGC_HASSETSEL = 0x8;
public const int DLGC_RADIOBUTTON = 0x40;
public const int DLGC_STATIC = 0x100;
public const int DLGC_UNDEFPUSHBUTTON = 0x20;
public const int DLGC_WANTALLKEYS = 0x4;
public const int DLGC_WANTARROWS = 0x1;
public const int DLGC_WANTCHARS = 0x80;
public const int DLGC_WANTMESSAGE = 0x4;
public const int DLGC_WANTTAB = 0x2;
public const int DLGWINDOWEXTRA = 30;
public const int DMLERR_ADVACKTIMEOUT = 0x4000;
public const int DMLERR_BUSY = 0x4001;
public const int DMLERR_DATAACKTIMEOUT = 0x4002;
public const int DMLERR_DLL_NOT_INITIALIZED = 0x4003;
public const int DMLERR_DLL_USAGE = 0x4004;
public const int DMLERR_EXECACKTIMEOUT = 0x4005;
public const int DMLERR_FIRST = 0x4000;
public const int DMLERR_INVALIDPARAMETER = 0x4006;
public const int DMLERR_LAST = 0x4011;
public const int DMLERR_LOW_MEMORY = 0x4007;
public const int DMLERR_MEMORY_ERROR = 0x4008;
public const int DMLERR_NOTPROCESSED = 0x4009;
public const int DMLERR_NO_CONV_ESTABLISHED = 0x400A;
public const int DMLERR_NO_ERROR = 0;
public const int DMLERR_POKEACKTIMEOUT = 0x400B;
public const int DMLERR_POSTMSG_FAILED = 0x400C;
public const int DMLERR_REENTRANCY = 0x400D;
public const int DMLERR_SERVER_DIED = 0x400E;
public const int DMLERR_SYS_ERROR = 0x400F;
public const int DMLERR_UNADVACKTIMEOUT = 0x4010;
public const int DMLERR_UNFOUND_QUEUE_ID = 0x4011;
public const int DM_GETDEFID = WM_USER + 0;
public const int DM_SETDEFID = WM_USER + 1;
public const int DNS_FILTEROFF = 0x8;
public const int DNS_FILTERON = 0x4;
public const int DNS_REGISTER = 0x1;
public const int DNS_UNREGISTER = 0x2;
public const int DS_ABSALIGN = 0x1;
public const int DS_LOCALEDIT = 0x20;
public const int DS_MODALFRAME = 0x80;
public const int DS_NOIDLEMSG = 0x100;
public const int DS_SETFONT = 0x40;
public const int DS_SETFOREGROUND = 0x200;
public const int DS_SYSMODAL = 0x2;
public const int DT_BOTTOM = 0x8;
public const int DT_CALCRECT = 0x400;
public const int DT_CENTER = 0x1;
public const int DT_EDITCONTROL = 0x2000;
public const int DT_END_ELLIPSIS = 0x8000;
public const int DT_EXPANDTABS = 0x40;
public const int DT_EXTERNALLEADING = 0x200;
public const int DT_INTERNAL = 0x1000;
public const int DT_LEFT = 0x0;
public const int DT_MODIFYSTRING = 0x10000;
public const int DT_NOCLIP = 0x100;
public const int DT_NOPREFIX = 0x800;
public const int DT_PATH_ELLIPSIS = 0x4000;
public const int DT_RIGHT = 0x2;
public const int DT_RTLREADING = 0x20000;
public const int DT_SINGLELINE = 0x20;
public const int DT_TABSTOP = 0x80;
public const int DT_TOP = 0x0;
public const int DT_VCENTER = 0x4;
public const int DT_WORDBREAK = 0x10;
public const int DT_WORD_ELLIPSIS = 0x40000;
public const int DWL_DLGPROC = 4;
public const int DWL_MSGRESULT = 0;
public const int DWL_USER = 8;
public const int EC_DISABLE = ST_BLOCKED;
public const int EC_ENABLEALL = 0;
public const int EC_ENABLEONE = ST_BLOCKNEXT;
public const int EC_QUERYWAITING = 2;
public const int EDGE_BUMP = (BDR_RAISEDOUTER | BDR_SUNKENINNER);
public const int EDGE_ETCHED = (BDR_SUNKENOUTER | BDR_RAISEDINNER);
public const int EDGE_RAISED = (BDR_RAISEDOUTER | BDR_RAISEDINNER);
public const int EDGE_SUNKEN = (BDR_SUNKENOUTER | BDR_SUNKENINNER);
public const int EM_CANPASTE = 0x432;
public const int EM_CANREDO = 0x455;
public const int EM_CANUNDO = 0xC6;
public const int EM_CHARFROMPOS = 0x427;
public const int EM_DISPLAYBAND = 0x433;
public const int EM_EMPTYUNDOBUFFER = 0xCD;
public const int EM_EXGETSEL = 0x434;
public const int EM_EXLIMITTEXT = 0x435;
public const int EM_EXLINEFROMCHAR = 0x436;
public const int EM_EXSETSEL = 0x437;
public const int EM_FINDTEXT = 0x438;
public const int EM_FINDTEXTEX = 0x44F;
public const int EM_FINDWORDBREAK = 0x44C;
public const int EM_FMTLINES = 0xC8;
public const int EM_FORMATRANGE = 0x439;
public const int EM_GETCHARFORMAT = 0x43A;
public const int EM_GETEVENTMASK = 0x43B;
public const int EM_GETFIRSTVISIBLELINE = 0xCE;
public const int EM_GETLIMITTEXT = 0x425;
public const int EM_GETLINE = 0xC4;
public const int EM_GETLINECOUNT = 0xBA;
public const int EM_GETMODIFY = 0xB8;
public const int EM_GETOLEINTERFACE = 0x43C;
public const int EM_GETOPTIONS = 0x44E;
public const int EM_GETPARAFORMAT = 0x43D;
public const int EM_GETPASSWORDCHAR = 0xD2;
public const int EM_GETRECT = 0xB2;
public const int EM_GETREDONAME = 0x457;
public const int EM_GETSEL = 0xB0;
public const int EM_GETSELTEXT = 0x43E;
public const int EM_GETTEXTMODE = 0x45A;
public const int EM_GETTEXTRANGE = 0x44B;
public const int EM_GETTHUMB = 0xBE;
public const int EM_GETUNDONAME = 0x456;
public const int EM_GETWORDBREAKPROC = 0xD1;
public const int EM_HIDESELECTION = 0x43F;
public const int EM_LIMITTEXT = 0xC5;
public const int EM_LINEFROMCHAR = 0xC9;
public const int EM_LINEINDEX = 0xBB;
public const int EM_LINELENGTH = 0xC1;
public const int EM_LINESCROLL = 0xB6;
public const int EM_PASTESPECIAL = 0x440;
public const int EM_POSFROMCHAR = 0x426;
public const int EM_REDO = 0x454;
public const int EM_REPLACESEL = 0xC2;
public const int EM_REQUESTRESIZE = 0x441;
public const int EM_SCROLL = 0xB5;
public const int EM_SCROLLCARET = 0xB7;
public const int EM_SELECTIONTYPE = 0x442;
public const int EM_SETBKGNDCOLOR = 0x443;
public const int EM_SETCHARFORMAT = 0x444;
public const int EM_SETEVENTMASK = 0x445;
public const int EM_SETMODIFY = 0xB9;
public const int EM_SETOLECALLBACK = 0x446;
public const int EM_SETOPTIONS = 0x44D;
public const int EM_SETPARAFORMAT = 0x447;
public const int EM_SETPASSWORDCHAR = 0xCC;
public const int EM_SETREADONLY = 0xCF;
public const int EM_SETRECT = 0xB3;
public const int EM_SETRECTNP = 0xB4;
public const int EM_SETSEL = 0xB1;
public const int EM_SETTABSTOPS = 0xCB;
public const int EM_SETTARGETDEVICE = 0x448;
public const int EM_SETTEXTMODE = 0x459;
public const int EM_SETUNDOLIMIT = 0x452;
public const int EM_SETWORDBREAKPROC = 0xD0;
public const int EM_STOPGROUPTYPING = 0x458;
public const int EM_STREAMIN = 0x449;
public const int EM_STREAMOUT = 0x44A;
public const int EM_UNDO = 0xC7;
public const int EN_CHANGE = 0x300;
public const int EN_ERRSPACE = 0x500;
public const int EN_HSCROLL = 0x601;
public const int EN_KILLFOCUS = 0x200;
public const int EN_MAXTEXT = 0x501;
public const int EN_SETFOCUS = 0x100;
public const int EN_UPDATE = 0x400;
public const int EN_VSCROLL = 0x602;
public const int ESB_DISABLE_BOTH = 0x3;
public const int ESB_DISABLE_DOWN = 0x2;
public const int ESB_DISABLE_LEFT = 0x1;
public const int ESB_DISABLE_LTUP = ESB_DISABLE_LEFT;
public const int ESB_DISABLE_RIGHT = 0x2;
public const int ESB_DISABLE_RTDN = ESB_DISABLE_RIGHT;
public const int ESB_DISABLE_UP = 0x1;
public const int ESB_ENABLE_BOTH = 0x0;
public const int ES_AUTOHSCROLL = 0x80;
public const int ES_AUTOVSCROLL = 0x40;
public const int ES_CENTER = 0x1;
public const int ES_LEFT = 0x0;
public const int ES_LOWERCASE = 0x10;
public const int ES_MULTILINE = 0x4;
public const int ES_NOHIDESEL = 0x100;
public const int ES_OEMCONVERT = 0x400;
public const int ES_PASSWORD = 0x20;
public const int ES_READONLY = 0x800;
public const int ES_RIGHT = 0x2;
public const int ES_UPPERCASE = 0x8;
public const int ES_WANTRETURN = 0x1000;
public const int EWX_FORCE = 4;
public const int EWX_LOGOFF = 0;
public const int EWX_REBOOT = 2;
public const int EWX_SHUTDOWN = 1;
public const int FALT = 0x10;
public const int FCONTROL = 0x8;
public const int FNOINVERT = 0x2;
public const int FSHIFT = 0x4;
public const int FVIRTKEY = 0x1;
public const int GCL_CBCLSEXTRA = (-20);
public const int GCL_CBWNDEXTRA = (-18);
public const int GCL_HBRBACKGROUND = (-10);
public const int GCL_HCURSOR = (-12);
public const int GCL_HICON = (-14);
public const int GCL_HMODULE = (-16);
public const int GCL_MENUNAME = (-8);
public const int GCL_STYLE = (-26);
public const int GCL_WNDPROC = (-24);
public const int GCW_ATOM = (-32);
public const int GWL_EXSTYLE = (-20);
public const int GWL_HINSTANCE = (-6);
public const int GWL_HWNDPARENT = (-8);
public const int GWL_ID = (-12);
public const int GWL_STYLE = (-16);
public const int GWL_USERDATA = (-21);
public const int GWL_WNDPROC = (-4);
public const int GW_CHILD = 5;
public const int GW_HWNDFIRST = 0;
public const int GW_HWNDLAST = 1;
public const int GW_HWNDNEXT = 2;
public const int GW_HWNDPREV = 3;
public const int GW_MAX = 5;
public const int GW_OWNER = 4;
public const int HCBT_ACTIVATE = 5;
public const int HCBT_CLICKSKIPPED = 6;
public const int HCBT_CREATEWND = 3;
public const int HCBT_DESTROYWND = 4;
public const int HCBT_KEYSKIPPED = 7;
public const int HCBT_MINMAX = 1;
public const int HCBT_MOVESIZE = 0;
public const int HCBT_QS = 2;
public const int HCBT_SETFOCUS = 9;
public const int HCBT_SYSCOMMAND = 8;
public const int HC_ACTION = 0;
public const int HC_GETNEXT = 1;
public const int HC_NOREM = HC_NOREMOVE;
public const int HC_NOREMOVE = 3;
public const int HC_SKIP = 2;
public const int HC_SYSMODALOFF = 5;
public const int HC_SYSMODALON = 4;
public const int HDATA_APPOWNED = 0x1;
public const int HELP_COMMAND = 0x102;
public const int HELP_CONTENTS = 0x3;
public const int HELP_CONTEXT = 0x1;
public const int HELP_CONTEXTPOPUP = 0x8;
public const int HELP_FORCEFILE = 0x9;
public const int HELP_HELPONHELP = 0x4;
public const int HELP_INDEX = 0x3;
public const int HELP_KEY = 0x101;
public const int HELP_MULTIKEY = 0x201;
public const int HELP_PARTIALKEY = 0x105;
public const int HELP_QUIT = 0x2;
public const int HELP_SETCONTENTS = 0x5;
public const int HELP_SETINDEX = 0x5;
public const int HELP_SETWINPOS = 0x203;
public const int HIDE_WINDOW = 0;
public const int HKL_NEXT = 1;
public const int HKL_PREV = 0;
public const int HSHELL_ACTIVATESHELLWINDOW = 3;
public const int HSHELL_WINDOWCREATED = 1;
public const int HSHELL_WINDOWDESTROYED = 2;
public const int HTBORDER = 18;
public const int HTBOTTOM = 15;
public const int HTBOTTOMLEFT = 16;
public const int HTBOTTOMRIGHT = 17;
public const int HTCAPTION = 2;
public const int HTCLIENT = 1;
public const int HTERROR = (-2);
public const int HTGROWBOX = 4;
public const int HTHSCROLL = 6;
public const int HTLEFT = 10;
public const int HTMAXBUTTON = 9;
public const int HTMENU = 5;
public const int HTMINBUTTON = 8;
public const int HTNOWHERE = 0;
public const int HTREDUCE = HTMINBUTTON;
public const int HTRIGHT = 11;
public const int HTSIZE = HTGROWBOX;
public const int HTSIZEFIRST = HTLEFT;
public const int HTSIZELAST = HTBOTTOMRIGHT;
public const int HTSYSMENU = 3;
public const int HTTOP = 12;
public const int HTTOPLEFT = 13;
public const int HTTOPRIGHT = 14;
public const int HTTRANSPARENT = (-1);
public const int HTVSCROLL = 7;
public const int HTZOOM = HTMAXBUTTON;
public HWND HWND_BOTTOM
{
get { return (HWND) 1; }
}
public HWND HWND_BROADCAST
{
get { return (HWND) 0xFFFF; }
}
public HWND HWND_DESKTOP
{
get { return (HWND) 0; }
}
public HWND HWND_TOP
{
get { return (HWND) 0; }
}
public HWND HWND_NOTOPMOST
{
get { return (HWND) (-2); }
}
public HWND HWND_TOPMOST
{
get { return (HWND) (-2); }
}
public const int IDABORT = 3;
public const int IDCANCEL = 2;
public const int IDC_APPSTARTING = 32650;
public const int IDC_ARROW = 32512;
public const int IDC_CROSS = 32515;
public const int IDC_IBEAM = 32513;
public const int IDC_ICON = 32641;
public const int IDC_NO = 32648;
public const int IDC_SIZE = 32640;
public const int IDC_SIZEALL = 32646;
public const int IDC_SIZENESW = 32643;
public const int IDC_SIZENS = 32645;
public const int IDC_SIZENWSE = 32642;
public const int IDC_SIZEWE = 32644;
public const int IDC_UPARROW = 32516;
public const int IDC_WAIT = 32514;
public const int IDHOT_SNAPDESKTOP = (-2);
public const int IDHOT_SNAPWINDOW = (-1);
public const int IDIGNORE = 5;
public const int IDI_APPLICATION = 32512;
public const int IDI_ASTERISK = 32516;
public const int IDI_EXCLAMATION = 32515;
public const int IDI_HAND = 32513;
public const int IDI_QUESTION = 32514;
public const int IDNO = 7;
public const int IDOK = 1;
public const int IDRETRY = 4;
public const int IDYES = 6;
public const int INVALID_HANDLE_VALUE = -1;
public const int KEYEVENTF_EXTENDEDKEY = 0x1;
public const int KEYEVENTF_KEYUP = 0x2;
public const int KF_ALTDOWN = 0x2000;
public const int KF_DLGMODE = 0x800;
public const int KF_EXTENDED = 0x100;
public const int KF_MENUMODE = 0x1000;
public const int KF_REPEAT = 0x4000;
public const int KF_UP = 0x8000;
public const int KLF_ACTIVATE = 0x1;
public const int KLF_REORDER = 0x8;
public const int KLF_SUBSTITUTE_OK = 0x2;
public const int KLF_UNLOADPREVIOUS = 0x4;
public const int KL_NAMELENGTH = 9;
public const int LBN_DBLCLK = 2;
public const int LBN_ERRSPACE = (-2);
public const int LBN_KILLFOCUS = 5;
public const int LBN_SELCANCEL = 3;
public const int LBN_SELCHANGE = 1;
public const int LBN_SETFOCUS = 4;
public const int LBS_DISABLENOSCROLL = 0x1000;
public const int LBS_EXTENDEDSEL = 0x800;
public const int LBS_HASSTRINGS = 0x40;
public const int LBS_MULTICOLUMN = 0x200;
public const int LBS_MULTIPLESEL = 0x8;
public const int LBS_NODATA = 0x2000;
public const int LBS_NOINTEGRALHEIGHT = 0x100;
public const int LBS_NOREDRAW = 0x4;
public const int LBS_NOTIFY = 0x1;
public const int LBS_OWNERDRAWFIXED = 0x10;
public const int LBS_OWNERDRAWVARIABLE = 0x20;
public const int LBS_SORT = 0x2;
public const int LBS_STANDARD = (LBS_NOTIFY | LBS_SORT | WS_VSCROLL | WS_BORDER);
public const int LBS_USETABSTOPS = 0x80;
public const int LBS_WANTKEYBOARDINPUT = 0x400;
public const int LB_ADDFILE = 0x196;
public const int LB_ADDSTRING = 0x180;
public const int LB_CTLCODE = 0;
public const int LB_DELETESTRING = 0x182;
public const int LB_DIR = 0x18D;
public const int LB_ERR = (-1);
public const int LB_ERRSPACE = (-2);
public const int LB_FINDSTRING = 0x18F;
public const int LB_FINDSTRINGEXACT = 0x1A2;
public const int LB_GETANCHORINDEX = 0x19D;
public const int LB_GETCARETINDEX = 0x19F;
public const int LB_GETCOUNT = 0x18B;
public const int LB_GETCURSEL = 0x188;
public const int LB_GETHORIZONTALEXTENT = 0x193;
public const int LB_GETITEMDATA = 0x199;
public const int LB_GETITEMHEIGHT = 0x1A1;
public const int LB_GETITEMRECT = 0x198;
public const int LB_GETLOCALE = 0x1A6;
public const int LB_GETSEL = 0x187;
public const int LB_GETSELCOUNT = 0x190;
public const int LB_GETSELITEMS = 0x191;
public const int LB_GETTEXT = 0x189;
public const int LB_GETTEXTLEN = 0x18A;
public const int LB_GETTOPINDEX = 0x18E;
public const int LB_INSERTSTRING = 0x181;
public const int LB_MSGMAX = 0x1A8;
public const int LB_OKAY = 0;
public const int LB_RESETCONTENT = 0x184;
public const int LB_SELECTSTRING = 0x18C;
public const int LB_SELITEMRANGE = 0x19B;
public const int LB_SELITEMRANGEEX = 0x183;
public const int LB_SETANCHORINDEX = 0x19C;
public const int LB_SETCARETINDEX = 0x19E;
public const int LB_SETCOLUMNWIDTH = 0x195;
public const int LB_SETCOUNT = 0x1A7;
public const int LB_SETCURSEL = 0x186;
public const int LB_SETHORIZONTALEXTENT = 0x194;
public const int LB_SETITEMDATA = 0x19A;
public const int LB_SETITEMHEIGHT = 0x1A0;
public const int LB_SETLOCALE = 0x1A5;
public const int LB_SETSEL = 0x185;
public const int LB_SETTABSTOPS = 0x192;
public const int LB_SETTOPINDEX = 0x197;
public const int MAX_MONITORS = 4;
public const int MA_ACTIVATE = 1;
public const int MA_ACTIVATEANDEAT = 2;
public const int MA_NOACTIVATE = 3;
public const int MA_NOACTIVATEANDEAT = 4;
public const int MB_ABORTRETRYIGNORE = 0x2;
public const int MB_APPLMODAL = 0x0;
public const int MB_DEFAULT_DESKTOP_ONLY = 0x20000;
public const int MB_DEFBUTTON1 = 0x0;
public const int MB_DEFBUTTON2 = 0x100;
public const int MB_DEFBUTTON3 = 0x200;
public const int MB_DEFMASK = 0xF00;
public const int MB_ICONASTERISK = 0x40;
public const int MB_ICONEXCLAMATION = 0x30;
public const int MB_ICONHAND = 0x10;
public const int MB_ICONINFORMATION = MB_ICONASTERISK;
public const int MB_ICONMASK = 0xF0;
public const int MB_ICONQUESTION = 0x20;
public const int MB_ICONSTOP = MB_ICONHAND;
public const int MB_MISCMASK = 0xC000;
public const int MB_MODEMASK = 0x3000;
public const int MB_NOFOCUS = 0x8000;
public const int MB_OK = 0x0;
public const int MB_OKCANCEL = 0x1;
public const int MB_RETRYCANCEL = 0x5;
public const int MB_SETFOREGROUND = 0x10000;
public const int MB_SYSTEMMODAL = 0x1000;
public const int MB_TASKMODAL = 0x2000;
public const int MB_TYPEMASK = 0xF;
public const int MB_YESNO = 0x4;
public const int MB_YESNOCANCEL = 0x3;
public const int MDIS_ALLCHILDSTYLES = 0x1;
public const int MDITILE_HORIZONTAL = 0x1;
public const int MDITILE_SKIPDISABLED = 0x2;
public const int MDITILE_VERTICAL = 0x0;
public const int MF_APPEND = 0x100;
public const int MF_BITMAP = 0x4;
public const int MF_BYCOMMAND = 0x0;
public const int MF_BYPOSITION = 0x400;
public const int MF_CALLBACKS = 0x8000000;
public const int MF_CHANGE = 0x80;
public const int MF_CHECKED = 0x8;
public const int MF_CONV = 0x40000000;
public const int MF_DELETE = 0x200;
public const int MF_DISABLED = 0x2;
public const int MF_ENABLED = 0x0;
public const int MF_END = 0x80;
public const int MF_ERRORS = 0x10000000;
public const int MF_GRAYED = 0x1;
public const int MF_HELP = 0x4000;
public const int MF_HILITE = 0x80;
public const int MF_HSZ_INFO = 0x1000000;
public const int MF_INSERT = 0x0;
public const int MF_LINKS = 0x20000000;
public const int MF_MASK = unchecked((int)0xFF000000);
public const int MF_MENUBARBREAK = 0x20;
public const int MF_MENUBREAK = 0x40;
public const int MF_MOUSESELECT = 0x8000;
public const int MF_OWNERDRAW = 0x100;
public const int MF_POPUP = 0x10;
public const int MF_POSTMSGS = 0x4000000;
public const int MF_REMOVE = 0x1000;
public const int MF_SENDMSGS = 0x2000000;
public const int MF_SEPARATOR = 0x800;
public const int MF_STRING = 0x0;
public const int MF_SYSMENU = 0x2000;
public const int MF_UNCHECKED = 0x0;
public const int MF_UNHILITE = 0x0;
public const int MF_USECHECKBITMAPS = 0x200;
public const int MH_CLEANUP = 4;
public const int MH_CREATE = 1;
public const int MH_DELETE = 3;
public const int MH_KEEP = 2;
public const int MK_CONTROL = 0x8;
public const int MK_LBUTTON = 0x1;
public const int MK_MBUTTON = 0x10;
public const int MK_RBUTTON = 0x2;
public const int MK_SHIFT = 0x4;
public const int MOD_ALT = 0x1;
public const int MOD_CONTROL = 0x2;
public const int MOD_SHIFT = 0x4;
public const int MOUSEEVENTF_ABSOLUTE = 0x8000;
public const int MOUSEEVENTF_LEFTDOWN = 0x2;
public const int MOUSEEVENTF_LEFTUP = 0x4;
public const int MOUSEEVENTF_MIDDLEDOWN = 0x20;
public const int MOUSEEVENTF_MIDDLEUP = 0x40;
public const int MOUSEEVENTF_MOVE = 0x1;
public const int MOUSEEVENTF_RIGHTDOWN = 0x8;
public const int MOUSEEVENTF_RIGHTUP = 0x10;
public const int MSGF_DDEMGR = 0x8001;
public const int MSGF_DIALOGBOX = 0;
public const int MSGF_MAINLOOP = 8;
public const int MSGF_MAX = 8;
public const int MSGF_MENU = 2;
public const int MSGF_MESSAGEBOX = 1;
public const int MSGF_MOVE = 3;
public const int MSGF_NEXTWINDOW = 6;
public const int MSGF_SCROLLBAR = 5;
public const int MSGF_SIZE = 4;
public const int MSGF_USER = 4096;
public const int OBM_BTNCORNERS = 32758;
public const int OBM_BTSIZE = 32761;
public const int OBM_CHECK = 32760;
public const int OBM_CHECKBOXES = 32759;
public const int OBM_CLOSE = 32754;
public const int OBM_COMBO = 32738;
public const int OBM_DNARROW = 32752;
public const int OBM_DNARROWD = 32742;
public const int OBM_DNARROWI = 32736;
public const int OBM_LFARROW = 32750;
public const int OBM_LFARROWD = 32740;
public const int OBM_LFARROWI = 32734;
public const int OBM_MNARROW = 32739;
public const int OBM_OLD_CLOSE = 32767;
public const int OBM_OLD_DNARROW = 32764;
public const int OBM_OLD_LFARROW = 32762;
public const int OBM_OLD_REDUCE = 32757;
public const int OBM_OLD_RESTORE = 32755;
public const int OBM_OLD_RGARROW = 32763;
public const int OBM_OLD_UPARROW = 32765;
public const int OBM_OLD_ZOOM = 32756;
public const int OBM_REDUCE = 32749;
public const int OBM_REDUCED = 32746;
public const int OBM_RESTORE = 32747;
public const int OBM_RESTORED = 32744;
public const int OBM_RGARROW = 32751;
public const int OBM_RGARROWD = 32741;
public const int OBM_RGARROWI = 32735;
public const int OBM_SIZE = 32766;
public const int OBM_UPARROW = 32753;
public const int OBM_UPARROWD = 32743;
public const int OBM_UPARROWI = 32737;
public const int OBM_ZOOM = 32748;
public const int OBM_ZOOMD = 32745;
public const int OCR_CROSS = 32515;
public const int OCR_IBEAM = 32513;
public const int OCR_ICOCUR = 32647;
public const int OCR_ICON = 32641;
public const int OCR_NO = 32648;
public const int OCR_NORMAL = 32512;
public const int OCR_SIZE = 32640;
public const int OCR_SIZEALL = 32646;
public const int OCR_SIZENESW = 32643;
public const int OCR_SIZENS = 32645;
public const int OCR_SIZENWSE = 32642;
public const int OCR_SIZEWE = 32644;
public const int OCR_UP = 32516;
public const int OCR_WAIT = 32514;
public const int ODA_DRAWENTIRE = 0x1;
public const int ODA_FOCUS = 0x4;
public const int ODA_SELECT = 0x2;
public const int ODS_CHECKED = 0x8;
public const int ODS_DISABLED = 0x4;
public const int ODS_FOCUS = 0x10;
public const int ODS_GRAYED = 0x2;
public const int ODS_SELECTED = 0x1;
public const int ODT_BUTTON = 4;
public const int ODT_COMBOBOX = 3;
public const int ODT_LISTBOX = 2;
public const int ODT_MENU = 1;
public const int OIC_BANG = 32515;
public const int OIC_HAND = 32513;
public const int OIC_NOTE = 32516;
public const int OIC_QUES = 32514;
public const int OIC_SAMPLE = 32512;
public const int ORD_LANGDRIVER = 1;
public const int PAGE_EXECUTE = 0x10;
public const int PAGE_EXECUTE_READ = 0x20;
public const int PAGE_EXECUTE_READWRITE = 0x40;
public const int PAGE_EXECUTE_WRITECOPY = 0x80;
public const int PAGE_GUARD = 0x100;
public const int PAGE_NOACCESS = 0x1;
public const int PAGE_NOCACHE = 0x200;
public const int PAGE_READONLY = 0x2;
public const int PAGE_READWRITE = 0x4;
public const int PAGE_WRITECOPY = 0x8;
public const int PM_NOREMOVE = 0x0;
public const int PM_NOYIELD = 0x2;
public const int PM_REMOVE = 0x1;
public const int PWR_CRITICALRESUME = 3;
public const int PWR_FAIL = (-1);
public const int PWR_OK = 1;
public const int PWR_SUSPENDREQUEST = 1;
public const int PWR_SUSPENDRESUME = 2;
public const int QID_SYNC = 0xFFFF;
public const int QS_ALLEVENTS = (QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY);
public const int QS_ALLINPUT = (QS_SENDMESSAGE | QS_PAINT | QS_TIMER | QS_POSTMESSAGE | QS_MOUSEBUTTON | QS_MOUSEMOVE | QS_HOTKEY | QS_KEY);
public const int QS_HOTKEY = 0x80;
public const int QS_INPUT = (QS_MOUSE | QS_KEY);
public const int QS_KEY = 0x1;
public const int QS_MOUSE = (QS_MOUSEMOVE | QS_MOUSEBUTTON);
public const int QS_MOUSEBUTTON = 0x4;
public const int QS_MOUSEMOVE = 0x2;
public const int QS_PAINT = 0x20;
public const int QS_POSTMESSAGE = 0x8;
public const int QS_SENDMESSAGE = 0x40;
public const int QS_TIMER = 0x10;
public const int RDW_ALLCHILDREN = 0x80;
public const int RDW_ERASE = 0x4;
public const int RDW_ERASENOW = 0x200;
public const int RDW_FRAME = 0x400;
public const int RDW_INTERNALPAINT = 0x2;
public const int RDW_INVALIDATE = 0x1;
public const int RDW_NOCHILDREN = 0x40;
public const int RDW_NOERASE = 0x20;
public const int RDW_NOFRAME = 0x800;
public const int RDW_NOINTERNALPAINT = 0x10;
public const int RDW_UPDATENOW = 0x100;
public const int RDW_VALIDATE = 0x8;
public const int READ = 0;
public const int READ_WRITE = 2;
public const int SBM_ENABLE_ARROWS = 0xE4;
public const int SBM_GETPOS = 0xE1;
public const int SBM_GETRANGE = 0xE3;
public const int SBM_SETPOS = 0xE0;
public const int SBM_SETRANGE = 0xE2;
public const int SBM_SETRANGEREDRAW = 0xE6;
public const int SBS_BOTTOMALIGN = 0x4;
public const int SBS_HORZ = 0x0;
public const int SBS_LEFTALIGN = 0x2;
public const int SBS_RIGHTALIGN = 0x4;
public const int SBS_SIZEBOX = 0x8;
public const int SBS_SIZEBOXBOTTOMRIGHTALIGN = 0x4;
public const int SBS_SIZEBOXTOPLEFTALIGN = 0x2;
public const int SBS_TOPALIGN = 0x2;
public const int SBS_VERT = 0x1;
public const int SB_BOTH = 3;
public const int SB_BOTTOM = 7;
public const int SB_CTL = 2;
public const int SB_ENDSCROLL = 8;
public const int SB_HORZ = 0;
public const int SB_LEFT = 6;
public const int SB_LINEDOWN = 1;
public const int SB_LINELEFT = 0;
public const int SB_LINERIGHT = 1;
public const int SB_LINEUP = 0;
public const int SB_PAGEDOWN = 3;
public const int SB_PAGELEFT = 2;
public const int SB_PAGERIGHT = 3;
public const int SB_PAGEUP = 2;
public const int SB_RIGHT = 7;
public const int SB_THUMBPOSITION = 4;
public const int SB_THUMBTRACK = 5;
public const int SB_TOP = 6;
public const int SB_VERT = 1;
public const int SC_ARRANGE = 0xF110;
public const int SC_CLOSE = 0xF060;
public const int SC_HOTKEY = 0xF150;
public const int SC_HSCROLL = 0xF080;
public const int SC_ICON = SC_MINIMIZE;
public const int SC_KEYMENU = 0xF100;
public const int SC_MAXIMIZE = 0xF030;
public const int SC_MINIMIZE = 0xF020;
public const int SC_MOUSEMENU = 0xF090;
public const int SC_MOVE = 0xF010;
public const int SC_NEXTWINDOW = 0xF040;
public const int SC_PREVWINDOW = 0xF050;
public const int SC_RESTORE = 0xF120;
public const int SC_SCREENSAVE = 0xF140;
public const int SC_SIZE = 0xF000;
public const int SC_TASKLIST = 0xF130;
public const int SC_VSCROLL = 0xF070;
public const int SC_ZOOM = SC_MAXIMIZE;
public const int SHOW_FULLSCREEN = 3;
public const int SHOW_ICONWINDOW = 2;
public const int SHOW_OPENNOACTIVATE = 4;
public const int SHOW_OPENWINDOW = 1;
public const int SIZEFULLSCREEN = SIZE_MAXIMIZED;
public const int SIZEICONIC = SIZE_MINIMIZED;
public const int SIZENORMAL = SIZE_RESTORED;
public const int SIZEZOOMHIDE = SIZE_MAXHIDE;
public const int SIZEZOOMSHOW = SIZE_MAXSHOW;
public const int SIZE_MAXHIDE = 4;
public const int SIZE_MAXIMIZED = 2;
public const int SIZE_MAXSHOW = 3;
public const int SIZE_MINIMIZED = 1;
public const int SIZE_RESTORED = 0;
public const int SMTO_ABORTIFHUNG = 0x2;
public const int SMTO_BLOCK = 0x1;
public const int SMTO_NORMAL = 0x0;
public const int SM_CMETRICS = 44;
public const int SM_CMOUSEBUTTONS = 43;
public const int SM_CXBORDER = 5;
public const int SM_CXCURSOR = 13;
public const int SM_CXDLGFRAME = 7;
public const int SM_CXDOUBLECLK = 36;
public const int SM_CXFIXEDFRAME = SM_CXDLGFRAME;
public const int SM_CXFRAME = 32;
public const int SM_CXFULLSCREEN = 16;
public const int SM_CXHSCROLL = 21;
public const int SM_CXHTHUMB = 10;
public const int SM_CXICON = 11;
public const int SM_CXICONSPACING = 38;
public const int SM_CXMIN = 28;
public const int SM_CXMINTRACK = 34;
public const int SM_CXSCREEN = 0;
public const int SM_CXSIZE = 30;
public const int SM_CXSIZEFRAME = SM_CXFRAME;
public const int SM_CXVSCROLL = 2;
public const int SM_CYBORDER = 6;
public const int SM_CYCAPTION = 4;
public const int SM_CYCURSOR = 14;
public const int SM_CYDLGFRAME = 8;
public const int SM_CYDOUBLECLK = 37;
public const int SM_CYFIXEDFRAME = SM_CYDLGFRAME;
public const int SM_CYFRAME = 33;
public const int SM_CYFULLSCREEN = 17;
public const int SM_CYHSCROLL = 3;
public const int SM_CYICON = 12;
public const int SM_CYICONSPACING = 39;
public const int SM_CYKANJIWINDOW = 18;
public const int SM_CYMENU = 15;
public const int SM_CYMIN = 29;
public const int SM_CYMINTRACK = 35;
public const int SM_CYSCREEN = 1;
public const int SM_CYSIZE = 31;
public const int SM_CYSIZEFRAME = SM_CYFRAME;
public const int SM_CYVSCROLL = 20;
public const int SM_CYVTHUMB = 9;
public const int SM_DBCSENABLED = 42;
public const int SM_DEBUG = 22;
public const int SM_MENUDROPALIGNMENT = 40;
public const int SM_MOUSEPRESENT = 19;
public const int SM_PENWINDOWS = 41;
public const int SM_RESERVED1 = 24;
public const int SM_RESERVED2 = 25;
public const int SM_RESERVED3 = 26;
public const int SM_RESERVED4 = 27;
public const int SM_SWAPBUTTON = 23;
public const int SPIF_SENDWININICHANGE = 0x2;
public const int SPIF_UPDATEINIFILE = 0x1;
public const int SPI_GETACCESSTIMEOUT = 60;
public const int SPI_GETANIMATION = 72;
public const int SPI_GETBEEP = 1;
public const int SPI_GETBORDER = 5;
public const int SPI_GETDEFAULTINPUTLANG = 89;
public const int SPI_GETDRAGFULLWINDOWS = 38;
public const int SPI_GETFASTTASKSWITCH = 35;
public const int SPI_GETFILTERKEYS = 50;
public const int SPI_GETFONTSMOOTHING = 74;
public const int SPI_GETGRIDGRANULARITY = 18;
public const int SPI_GETHIGHCONTRAST = 66;
public const int SPI_GETICONMETRICS = 45;
public const int SPI_GETICONTITLELOGFONT = 31;
public const int SPI_GETICONTITLEWRAP = 25;
public const int SPI_GETKEYBOARDDELAY = 22;
public const int SPI_GETKEYBOARDPREF = 68;
public const int SPI_GETKEYBOARDSPEED = 10;
public const int SPI_GETLOWPOWERACTIVE = 83;
public const int SPI_GETLOWPOWERTIMEOUT = 79;
public const int SPI_GETMENUDROPALIGNMENT = 27;
public const int SPI_GETMINIMIZEDMETRICS = 43;
public const int SPI_GETMOUSE = 3;
public const int SPI_GETMOUSEKEYS = 54;
public const int SPI_GETMOUSETRAILS = 94;
public const int SPI_GETNONCLIENTMETRICS = 41;
public const int SPI_GETPOWEROFFACTIVE = 84;
public const int SPI_GETPOWEROFFTIMEOUT = 80;
public const int SPI_GETSCREENREADER = 70;
public const int SPI_GETSCREENSAVEACTIVE = 16;
public const int SPI_GETSCREENSAVETIMEOUT = 14;
public const int SPI_GETSERIALKEYS = 62;
public const int SPI_GETSHOWSOUNDS = 56;
public const int SPI_GETSOUNDSENTRY = 64;
public const int SPI_GETSTICKYKEYS = 58;
public const int SPI_GETTOGGLEKEYS = 52;
public const int SPI_GETWINDOWSEXTENSION = 92;
public const int SPI_GETWORKAREA = 48;
public const int SPI_ICONHORIZONTALSPACING = 13;
public const int SPI_ICONVERTICALSPACING = 24;
public const int SPI_LANGDRIVER = 12;
public const int SPI_SCREENSAVERRUNNING = 97;
public const int SPI_SETACCESSTIMEOUT = 61;
public const int SPI_SETANIMATION = 73;
public const int SPI_SETBEEP = 2;
public const int SPI_SETBORDER = 6;
public const int SPI_SETCURSORS = 87;
public const int SPI_SETDEFAULTINPUTLANG = 90;
public const int SPI_SETDESKPATTERN = 21;
public const int SPI_SETDESKWALLPAPER = 20;
public const int SPI_SETDOUBLECLICKTIME = 32;
public const int SPI_SETDOUBLECLKHEIGHT = 30;
public const int SPI_SETDOUBLECLKWIDTH = 29;
public const int SPI_SETDRAGFULLWINDOWS = 37;
public const int SPI_SETDRAGHEIGHT = 77;
public const int SPI_SETDRAGWIDTH = 76;
public const int SPI_SETFASTTASKSWITCH = 36;
public const int SPI_SETFILTERKEYS = 51;
public const int SPI_SETFONTSMOOTHING = 75;
public const int SPI_SETGRIDGRANULARITY = 19;
public const int SPI_SETHANDHELD = 78;
public const int SPI_SETHIGHCONTRAST = 67;
public const int SPI_SETICONMETRICS = 46;
public const int SPI_SETICONS = 88;
public const int SPI_SETICONTITLELOGFONT = 34;
public const int SPI_SETICONTITLEWRAP = 26;
public const int SPI_SETKEYBOARDDELAY = 23;
public const int SPI_SETKEYBOARDPREF = 69;
public const int SPI_SETKEYBOARDSPEED = 11;
public const int SPI_SETLANGTOGGLE = 91;
public const int SPI_SETLOWPOWERACTIVE = 85;
public const int SPI_SETLOWPOWERTIMEOUT = 81;
public const int SPI_SETMENUDROPALIGNMENT = 28;
public const int SPI_SETMINIMIZEDMETRICS = 44;
public const int SPI_SETMOUSE = 4;
public const int SPI_SETMOUSEBUTTONSWAP = 33;
public const int SPI_SETMOUSEKEYS = 55;
public const int SPI_SETMOUSETRAILS = 93;
public const int SPI_SETNONCLIENTMETRICS = 42;
public const int SPI_SETPENWINDOWS = 49;
public const int SPI_SETPOWEROFFACTIVE = 86;
public const int SPI_SETPOWEROFFTIMEOUT = 82;
public const int SPI_SETSCREENREADER = 71;
public const int SPI_SETSCREENSAVEACTIVE = 17;
public const int SPI_SETSCREENSAVETIMEOUT = 15;
public const int SPI_SETSERIALKEYS = 63;
public const int SPI_SETSHOWSOUNDS = 57;
public const int SPI_SETSOUNDSENTRY = 65;
public const int SPI_SETSTICKYKEYS = 59;
public const int SPI_SETTOGGLEKEYS = 53;
public const int SPI_SETWORKAREA = 47;
public const int SS_BLACKFRAME = 0x7;
public const int SS_BLACKRECT = 0x4;
public const int SS_CENTER = 0x1;
public const int SS_GRAYFRAME = 0x8;
public const int SS_GRAYRECT = 0x5;
public const int SS_ICON = 0x3;
public const int SS_LEFT = 0x0;
public const int SS_LEFTNOWORDWRAP = 0xC;
public const int SS_NOPREFIX = 0x80;
public const int SS_RIGHT = 0x2;
public const int SS_SIMPLE = 0xB;
public const int SS_USERITEM = 0xA;
public const int SS_WHITEFRAME = 0x9;
public const int SS_WHITERECT = 0x6;
public const int STM_GETICON = 0x171;
public const int STM_MSGMAX = 0x172;
public const int STM_SETICON = 0x170;
public const int ST_ADVISE = 0x2;
public const int ST_BEGINSWP = 0;
public const int ST_BLOCKED = 0x8;
public const int ST_BLOCKNEXT = 0x80;
public const int ST_CLIENT = 0x10;
public const int ST_CONNECTED = 0x1;
public const int ST_ENDSWP = 1;
public const int ST_INLIST = 0x40;
public const int ST_ISLOCAL = 0x4;
public const int ST_ISSELF = 0x100;
public const int ST_TERMINATED = 0x20;
public const int SWP_DRAWFRAME = SWP_FRAMECHANGED;
public const int SWP_FRAMECHANGED = 0x20;
public const int SWP_HIDEWINDOW = 0x80;
public const int SWP_NOACTIVATE = 0x10;
public const int SWP_NOCOPYBITS = 0x100;
public const int SWP_NOMOVE = 0x2;
public const int SWP_NOOWNERZORDER = 0x200;
public const int SWP_NOREDRAW = 0x8;
public const int SWP_NOREPOSITION = SWP_NOOWNERZORDER;
public const int SWP_NOSIZE = 0x1;
public const int SWP_NOZORDER = 0x4;
public const int SWP_SHOWWINDOW = 0x40;
public const int SW_ERASE = 0x4;
public const int SW_HIDE = 0;
public const int SW_INVALIDATE = 0x2;
public const int SW_MAX = 10;
public const int SW_MAXIMIZE = 3;
public const int SW_MINIMIZE = 6;
public const int SW_NORMAL = 1;
public const int SW_OTHERUNZOOM = 4;
public const int SW_OTHERZOOM = 2;
public const int SW_PARENTCLOSING = 1;
public const int SW_PARENTOPENING = 3;
public const int SW_RESTORE = 9;
public const int SW_SCROLLCHILDREN = 0x1;
public const int SW_SHOW = 5;
public const int SW_SHOWDEFAULT = 10;
public const int SW_SHOWMAXIMIZED = 3;
public const int SW_SHOWMINIMIZED = 2;
public const int SW_SHOWMINNOACTIVE = 7;
public const int SW_SHOWNA = 8;
public const int SW_SHOWNOACTIVATE = 4;
public const int SW_SHOWNORMAL = 1;
public const int TIMEOUT_ASYNC = 0xFFFF;
public const int TPM_CENTERALIGN = 0x4;
public const int TPM_LEFTALIGN = 0x0;
public const int TPM_LEFTBUTTON = 0x0;
public const int TPM_RIGHTALIGN = 0x8;
public const int TPM_RIGHTBUTTON = 0x2;
public const int VK_ADD = 0x6B;
public const int VK_ATTN = 0xF6;
public const int VK_BACK = 0x8;
public const int VK_CANCEL = 0x3;
public const int VK_CAPITAL = 0x14;
public const int VK_CLEAR = 0xC;
public const int VK_CONTROL = 0x11;
public const int VK_CRSEL = 0xF7;
public const int VK_DECIMAL = 0x6E;
public const int VK_DELETE = 0x2E;
public const int VK_DIVIDE = 0x6F;
public const int VK_DOWN = 0x28;
public const int VK_END = 0x23;
public const int VK_EREOF = 0xF9;
public const int VK_ESCAPE = 0x1B;
public const int VK_EXECUTE = 0x2B;
public const int VK_EXSEL = 0xF8;
public const int VK_F1 = 0x70;
public const int VK_F10 = 0x79;
public const int VK_F11 = 0x7A;
public const int VK_F12 = 0x7B;
public const int VK_F13 = 0x7C;
public const int VK_F14 = 0x7D;
public const int VK_F15 = 0x7E;
public const int VK_F16 = 0x7F;
public const int VK_F17 = 0x80;
public const int VK_F18 = 0x81;
public const int VK_F19 = 0x82;
public const int VK_F2 = 0x71;
public const int VK_F20 = 0x83;
public const int VK_F21 = 0x84;
public const int VK_F22 = 0x85;
public const int VK_F23 = 0x86;
public const int VK_F24 = 0x87;
public const int VK_F3 = 0x72;
public const int VK_F4 = 0x73;
public const int VK_F5 = 0x74;
public const int VK_F6 = 0x75;
public const int VK_F7 = 0x76;
public const int VK_F8 = 0x77;
public const int VK_F9 = 0x78;
public const int VK_HELP = 0x2F;
public const int VK_HOME = 0x24;
public const int VK_INSERT = 0x2D;
public const int VK_LBUTTON = 0x1;
public const int VK_LCONTROL = 0xA2;
public const int VK_LEFT = 0x25;
public const int VK_LMENU = 0xA4;
public const int VK_LSHIFT = 0xA0;
public const int VK_MBUTTON = 0x4;
public const int VK_MENU = 0x12;
public const int VK_MULTIPLY = 0x6A;
public const int VK_NEXT = 0x22;
public const int VK_NONAME = 0xFC;
public const int VK_NUMLOCK = 0x90;
public const int VK_NUMPAD0 = 0x60;
public const int VK_NUMPAD1 = 0x61;
public const int VK_NUMPAD2 = 0x62;
public const int VK_NUMPAD3 = 0x63;
public const int VK_NUMPAD4 = 0x64;
public const int VK_NUMPAD5 = 0x65;
public const int VK_NUMPAD6 = 0x66;
public const int VK_NUMPAD7 = 0x67;
public const int VK_NUMPAD8 = 0x68;
public const int VK_NUMPAD9 = 0x69;
public const int VK_OEM_CLEAR = 0xFE;
public const int VK_PA1 = 0xFD;
public const int VK_PAUSE = 0x13;
public const int VK_PLAY = 0xFA;
public const int VK_PRINT = 0x2A;
public const int VK_PRIOR = 0x21;
public const int VK_RBUTTON = 0x2;
public const int VK_RCONTROL = 0xA3;
public const int VK_RETURN = 0xD;
public const int VK_RIGHT = 0x27;
public const int VK_RMENU = 0xA5;
public const int VK_RSHIFT = 0xA1;
public const int VK_SCROLL = 0x91;
public const int VK_SELECT = 0x29;
public const int VK_SEPARATOR = 0x6C;
public const int VK_SHIFT = 0x10;
public const int VK_SNAPSHOT = 0x2C;
public const int VK_SPACE = 0x20;
public const int VK_SUBTRACT = 0x6D;
public const int VK_TAB = 0x9;
public const int VK_UP = 0x26;
public const int VK_ZOOM = 0xFB;
public const int WA_ACTIVE = 1;
public const int WA_CLICKACTIVE = 2;
public const int WA_INACTIVE = 0;
public const int WB_ISDELIMITER = 2;
public const int WB_LEFT = 0;
public const int WB_RIGHT = 1;
public const int WC_DIALOG = 8002;
public const int WH_CALLWNDPROC = 4;
public const int WH_CBT = 5;
public const int WH_DEBUG = 9;
public const int WH_FOREGROUNDIDLE = 11;
public const int WH_GETMESSAGE = 3;
public const int WH_HARDWARE = 8;
public const int WH_JOURNALPLAYBACK = 1;
public const int WH_JOURNALRECORD = 0;
public const int WH_KEYBOARD = 2;
public const int WH_MAX = 11;
public const int WH_MIN = (-1);
public const int WH_MOUSE = 7;
public const int WH_MSGFILTER = (-1);
public const int WH_SHELL = 10;
public const int WH_SYSMSGFILTER = 6;
public const int WINSTA_ACCESSCLIPBOARD = 0x4;
public const int WINSTA_ACCESSPUBLICATOMS = 0x20;
public const int WINSTA_CREATEDESKTOP = 0x8;
public const int WINSTA_ENUMDESKTOPS = 0x1;
public const int WINSTA_ENUMERATE = 0x100;
public const int WINSTA_EXITWINDOWS = 0x40;
public const int WINSTA_READATTRIBUTES = 0x2;
public const int WINSTA_READSCREEN = 0x200;
public const int WINSTA_WRITEATTRIBUTES = 0x10;
public const int WM_ACTIVATE = 0x6;
public const int WM_ACTIVATEAPP = 0x1C;
public const int WM_ASKCBFORMATNAME = 0x30C;
public const int WM_CANCELJOURNAL = 0x4B;
public const int WM_CANCELMODE = 0x1F;
public const int WM_CHANGECBCHAIN = 0x30D;
public const int WM_CHAR = 0x102;
public const int WM_CHARTOITEM = 0x2F;
public const int WM_CHILDACTIVATE = 0x22;
public const int WM_CLEAR = 0x303;
public const int WM_CLOSE = 0x10;
public const int WM_COMMAND = 0x111;
public const int WM_COMMNOTIFY = 0x44;
public const int WM_COMPACTING = 0x41;
public const int WM_COMPAREITEM = 0x39;
public const int WM_COPY = 0x301;
public const int WM_COPYDATA = 0x4A;
public const int WM_CREATE = 0x1;
public const int WM_CTLCOLORBTN = 0x135;
public const int WM_CTLCOLORDLG = 0x136;
public const int WM_CTLCOLOREDIT = 0x133;
public const int WM_CTLCOLORLISTBOX = 0x134;
public const int WM_CTLCOLORMSGBOX = 0x132;
public const int WM_CTLCOLORSCROLLBAR = 0x137;
public const int WM_CTLCOLORSTATIC = 0x138;
public const int WM_CUT = 0x300;
public const int WM_DDE_ACK = (WM_DDE_FIRST + 4);
public const int WM_DDE_ADVISE = (WM_DDE_FIRST + 2);
public const int WM_DDE_DATA = (WM_DDE_FIRST + 5);
public const int WM_DDE_EXECUTE = (WM_DDE_FIRST + 8);
public const int WM_DDE_FIRST = 0x3E0;
public const int WM_DDE_INITIATE = (WM_DDE_FIRST);
public const int WM_DDE_LAST = (WM_DDE_FIRST + 8);
public const int WM_DDE_POKE = (WM_DDE_FIRST + 7);
public const int WM_DDE_REQUEST = (WM_DDE_FIRST + 6);
public const int WM_DDE_TERMINATE = (WM_DDE_FIRST + 1);
public const int WM_DDE_UNADVISE = (WM_DDE_FIRST + 3);
public const int WM_DEADCHAR = 0x103;
public const int WM_DELETEITEM = 0x2D;
public const int WM_DESTROY = 0x2;
public const int WM_DESTROYCLIPBOARD = 0x307;
public const int WM_DEVMODECHANGE = 0x1B;
public const int WM_DRAWCLIPBOARD = 0x308;
public const int WM_DRAWITEM = 0x2B;
public const int WM_DROPFILES = 0x233;
public const int WM_ENABLE = 0xA;
public const int WM_ENDSESSION = 0x16;
public const int WM_ENTERIDLE = 0x121;
public const int WM_ENTERMENULOOP = 0x211;
public const int WM_ERASEBKGND = 0x14;
public const int WM_EXITMENULOOP = 0x212;
public const int WM_FONTCHANGE = 0x1D;
public const int WM_GETDLGCODE = 0x87;
public const int WM_GETFONT = 0x31;
public const int WM_GETHOTKEY = 0x33;
public const int WM_GETMINMAXINFO = 0x24;
public const int WM_GETTEXT = 0xD;
public const int WM_GETTEXTLENGTH = 0xE;
public const int WM_HOTKEY = 0x312;
public const int WM_HSCROLL = 0x114;
public const int WM_HSCROLLCLIPBOARD = 0x30E;
public const int WM_ICONERASEBKGND = 0x27;
public const int WM_INITDIALOG = 0x110;
public const int WM_INITMENU = 0x116;
public const int WM_INITMENUPOPUP = 0x117;
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYFIRST = 0x100;
public const int WM_KEYLAST = 0x108;
public const int WM_KEYUP = 0x101;
public const int WM_KILLFOCUS = 0x8;
public const int WM_LBUTTONDBLCLK = 0x203;
public const int WM_LBUTTONDOWN = 0x201;
public const int WM_LBUTTONUP = 0x202;
public const int WM_MBUTTONDBLCLK = 0x209;
public const int WM_MBUTTONDOWN = 0x207;
public const int WM_MBUTTONUP = 0x208;
public const int WM_MDIACTIVATE = 0x222;
public const int WM_MDICASCADE = 0x227;
public const int WM_MDICREATE = 0x220;
public const int WM_MDIDESTROY = 0x221;
public const int WM_MDIGETACTIVE = 0x229;
public const int WM_MDIICONARRANGE = 0x228;
public const int WM_MDIMAXIMIZE = 0x225;
public const int WM_MDINEXT = 0x224;
public const int WM_MDIREFRESHMENU = 0x234;
public const int WM_MDIRESTORE = 0x223;
public const int WM_MDISETMENU = 0x230;
public const int WM_MDITILE = 0x226;
public const int WM_MEASUREITEM = 0x2C;
public const int WM_MENUCHAR = 0x120;
public const int WM_MENUSELECT = 0x11F;
public const int WM_MOUSEACTIVATE = 0x21;
public const int WM_MOUSEFIRST = 0x200;
public const int WM_MOUSELAST = 0x209;
public const int WM_MOUSEMOVE = 0x200;
public const int WM_MOVE = 0x3;
public const int WM_NCACTIVATE = 0x86;
public const int WM_NCCALCSIZE = 0x83;
public const int WM_NCCREATE = 0x81;
public const int WM_NCDESTROY = 0x82;
public const int WM_NCHITTEST = 0x84;
public const int WM_NCLBUTTONDBLCLK = 0xA3;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int WM_NCLBUTTONUP = 0xA2;
public const int WM_NCMBUTTONDBLCLK = 0xA9;
public const int WM_NCMBUTTONDOWN = 0xA7;
public const int WM_NCMBUTTONUP = 0xA8;
public const int WM_NCMOUSEMOVE = 0xA0;
public const int WM_NCPAINT = 0x85;
public const int WM_NCRBUTTONDBLCLK = 0xA6;
public const int WM_NCRBUTTONDOWN = 0xA4;
public const int WM_NCRBUTTONUP = 0xA5;
public const int WM_NEXTDLGCTL = 0x28;
public const int WM_NULL = 0x0;
public const int WM_OTHERWINDOWCREATED = 0x42;
public const int WM_OTHERWINDOWDESTROYED = 0x43;
public const int WM_PAINT = 0xF;
public const int WM_PAINTCLIPBOARD = 0x309;
public const int WM_PAINTICON = 0x26;
public const int WM_PALETTECHANGED = 0x311;
public const int WM_PALETTEISCHANGING = 0x310;
public const int WM_PARENTNOTIFY = 0x210;
public const int WM_PASTE = 0x302;
public const int WM_PENWINFIRST = 0x380;
public const int WM_PENWINLAST = 0x38F;
public const int WM_POWER = 0x48;
public const int WM_QUERYDRAGICON = 0x37;
public const int WM_QUERYENDSESSION = 0x11;
public const int WM_QUERYNEWPALETTE = 0x30F;
public const int WM_QUERYOPEN = 0x13;
public const int WM_QUEUESYNC = 0x23;
public const int WM_QUIT = 0x12;
public const int WM_RBUTTONDBLCLK = 0x206;
public const int WM_RBUTTONDOWN = 0x204;
public const int WM_RBUTTONUP = 0x205;
public const int WM_RENDERALLFORMATS = 0x306;
public const int WM_RENDERFORMAT = 0x305;
public const int WM_SETCURSOR = 0x20;
public const int WM_SETFOCUS = 0x7;
public const int WM_SETFONT = 0x30;
public const int WM_SETHOTKEY = 0x32;
public const int WM_SETREDRAW = 0xB;
public const int WM_SETTEXT = 0xC;
public const int WM_SHOWWINDOW = 0x18;
public const int WM_SIZE = 0x5;
public const int WM_SIZECLIPBOARD = 0x30B;
public const int WM_SPOOLERSTATUS = 0x2A;
public const int WM_SYSCHAR = 0x106;
public const int WM_SYSCOLORCHANGE = 0x15;
public const int WM_SYSCOMMAND = 0x112;
public const int WM_SYSDEADCHAR = 0x107;
public const int WM_SYSKEYDOWN = 0x104;
public const int WM_SYSKEYUP = 0x105;
public const int WM_TIMECHANGE = 0x1E;
public const int WM_TIMER = 0x113;
public const int WM_UNDO = 0x304;
public const int WM_USER = 0x400;
public const int WM_VKEYTOITEM = 0x2E;
public const int WM_VSCROLL = 0x115;
public const int WM_VSCROLLCLIPBOARD = 0x30A;
public const int WM_WINDOWPOSCHANGED = 0x47;
public const int WM_WINDOWPOSCHANGING = 0x46;
public const int WM_WININICHANGE = 0x1A;
public const int WPF_RESTORETOMAXIMIZED = 0x2;
public const int WPF_SETMINPOSITION = 0x1;
public const int WRITE = 1;
public const int WS_BORDER = 0x800000;
public const int WS_CAPTION = 0xC00000;
public const int WS_CHILD = 0x40000000;
public const int WS_CHILDWINDOW = (WS_CHILD);
public const int WS_CLIPCHILDREN = 0x2000000;
public const int WS_CLIPSIBLINGS = 0x4000000;
public const int WS_DISABLED = 0x8000000;
public const int WS_DLGFRAME = 0x400000;
public const int WS_EX_ACCEPTFILES = 0x10;
public const int WS_EX_DLGMODALFRAME = 0x1;
public const int WS_EX_NOPARENTNOTIFY = 0x4;
public const int WS_EX_TOPMOST = 0x8;
public const int WS_EX_TRANSPARENT = 0x20;
public const int WS_GROUP = 0x20000;
public const int WS_HSCROLL = 0x100000;
public const int WS_ICONIC = WS_MINIMIZE;
public const int WS_MAXIMIZE = 0x1000000;
public const int WS_MAXIMIZEBOX = 0x10000;
public const int WS_MINIMIZE = 0x20000000;
public const int WS_MINIMIZEBOX = 0x20000;
public const int WS_OVERLAPPED = 0x0;
public const int WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
public const int WS_POPUP = unchecked((int)0x80000000);
public const int WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU);
public const int WS_SIZEBOX = WS_THICKFRAME;
public const int WS_SYSMENU = 0x80000;
public const int WS_TABSTOP = 0x10000;
public const int WS_THICKFRAME = 0x40000;
public const int WS_TILED = WS_OVERLAPPED;
public const int WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW;
public const int WS_VISIBLE = 0x10000000;
public const int WS_VSCROLL = 0x200000;
public const int WVR_ALIGNBOTTOM = 0x40;
public const int WVR_ALIGNLEFT = 0x20;
public const int WVR_ALIGNRIGHT = 0x80;
public const int WVR_ALIGNTOP = 0x10;
public const int WVR_HREDRAW = 0x100;
public const int WVR_REDRAW = (WVR_HREDRAW | WVR_VREDRAW);
public const int WVR_VALIDRECTS = 0x400;
public const int WVR_VREDRAW = 0x200;
public const int XCLASS_BOOL = 0x1000;
public const int XCLASS_DATA = 0x2000;
public const int XCLASS_FLAGS = 0x4000;
public const int XCLASS_MASK = 0xFC00;
public const int XCLASS_NOTIFICATION = 0x8000;
public const int XST_ADVACKRCVD = 13;
public const int XST_ADVDATAACKRCVD = 16;
public const int XST_ADVDATASENT = 15;
public const int XST_ADVSENT = 11;
public const int XST_CONNECTED = 2;
public const int XST_DATARCVD = 6;
public const int XST_EXECACKRCVD = 10;
public const int XST_EXECSENT = 9;
public const int XST_INCOMPLETE = 1;
public const int XST_INIT1 = 3;
public const int XST_INIT2 = 4;
public const int XST_NULL = 0;
public const int XST_POKEACKRCVD = 8;
public const int XST_POKESENT = 7;
public const int XST_REQSENT = 5;
public const int XST_UNADVACKRCVD = 14;
public const int XST_UNADVSENT = 12;
public const int XTYPF_ACKREQ = 0x8;
public const int XTYPF_NOBLOCK = 0x2;
public const int XTYPF_NODATA = 0x4;
public const int XTYP_ADVDATA = (0x10 | XCLASS_FLAGS);
public const int XTYP_ADVREQ = (0x20 | XCLASS_DATA | XTYPF_NOBLOCK);
public const int XTYP_ADVSTART = (0x30 | XCLASS_BOOL);
public const int XTYP_ADVSTOP = (0x40 | XCLASS_NOTIFICATION);
public const int XTYP_CONNECT = (0x60 | XCLASS_BOOL | XTYPF_NOBLOCK);
public const int XTYP_CONNECT_CONFIRM = (0x70 | XCLASS_NOTIFICATION | XTYPF_NOBLOCK);
public const int XTYP_DISCONNECT = (0xC0 | XCLASS_NOTIFICATION | XTYPF_NOBLOCK);
public const int XTYP_ERROR = (0x0 | XCLASS_NOTIFICATION | XTYPF_NOBLOCK);
public const int XTYP_EXECUTE = (0x50 | XCLASS_FLAGS);
public const int XTYP_MASK = 0xF0;
public const int XTYP_MONITOR = (0xF0 | XCLASS_NOTIFICATION | XTYPF_NOBLOCK);
public const int XTYP_POKE = (0x90 | XCLASS_FLAGS);
public const int XTYP_REGISTER = (0xA0 | XCLASS_NOTIFICATION | XTYPF_NOBLOCK);
public const int XTYP_REQUEST = (0xB0 | XCLASS_DATA);
public const int XTYP_SHIFT = 4;
public const int XTYP_UNREGISTER = (0xD0 | XCLASS_NOTIFICATION | XTYPF_NOBLOCK);
public const int XTYP_WILDCONNECT = (0xE0 | XCLASS_DATA | XTYPF_NOBLOCK);
public const int XTYP_XACT_COMPLETE = (0x80 | XCLASS_NOTIFICATION);
public const string SZDDESYS_ITEM_FORMATS = "Formats";
public const string SZDDESYS_ITEM_HELP = "Help";
public const string SZDDESYS_ITEM_RTNMSG = "ReturnMessage";
public const string SZDDESYS_ITEM_STATUS = "Status";
public const string SZDDESYS_ITEM_SYSITEMS = "SysItems";
public const string SZDDESYS_ITEM_TOPICS = "Topics";
public const string SZDDESYS_TOPIC = "System";
public const string SZDDE_ITEM_ITEMLIST = "TopicItemList";
}
}


using System;
using System.Runtime.InteropServices;
namespace Win32
{
public struct RECT
{
public int Left;
public int
Top;
public int Right;
public int
Bottom;
}
public struct POINT
{
public int x;
public int
y;
}
public struct SIZE
{
public int
cx;
public int cy;
}
public struct FILETIME
{
public int dwLowDateTime;
public int
dwHighDateTime;
}
public struct SYSTEMTIME
{
public short wYear;
public short
wMonth;
public short wDayOfWeek;
public short
wDay;
public short wHour;
public short
wMinute;
public short wSecond;
public short
wMilliseconds;
}
}


using System;
using System.Runtime.InteropServices;
using HWND = System.IntPtr;
using HANDLE = System.IntPtr;
namespace Win32
{
public struct DRAGINFO
{
public int uSize;
public POINT
pt;
public int fNC;
public string
lpFileList;
public int grfKeyState;
}
public
struct APPBARDATA
{
public int
cbSize;
public HWND hwnd;
public int
uCallbackMessage;
public int uEdge;
public RECT
rc;
public int lParam;
}
public struct
SHFILEOPSTRUCT
{
public HWND
hwnd;
public int wFunc;
public string
pFrom;
public string pTo;
public short
fFlags;
public int fAnyOperationsAborted;
public
HANDLE hNameMappings;
public string lpszProgressTitle;
}
public struct SHNAMEMAPPING
{
public string pszOldPath;
public
string pszNewPath;
public int cchOldPath;
public
int cchNewPath;
}
public struct SHELLEXECUTEINFO
{
public int cbSize;
public int
fMask;
public HWND hwnd;
public string
lpVerb;
public string lpFile;
public string
lpParameters;
public string lpDirectory;
public
int nShow;
public HANDLE hInstApp;
public int
lpIDList;
public string lpClass;
public HANDLE
hkeyClass;
public int dwHotKey;
public HANDLE
hIcon;
public HANDLE hProcess;
}
public struct
NOTIFYICONDATA
{
public int
cbSize;
public HWND hwnd;
public int
uID;
public int uFlags;
public int
uCallbackMessage;
public HANDLE
hIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)] public
string szTip;
}
public struct SHFILEINFO
{
public HANDLE hIcon;
public int
iIcon;
public int dwAttributes;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=Kernel.MAX_PATH)]public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=80)] public string
szTypeName;
}
 public abstract class
Shell
{
[DllImport("shell32")] public static extern int
CommandLineToArgv(string lpCmdLine, short
pNumArgs);
[DllImport("shell32")] public static extern int
DoEnvironmentSubst(string szString, int
cbString);
[DllImport("shell32")] public static extern int
DragQueryFile(HANDLE hDROP, int UINT, string lpStr, int
ch);
[DllImport("shell32")] public static extern int
DragQueryPoint(HANDLE hDROP, ref POINT
lpPoint);
[DllImport("shell32")] public static extern int
DuplicateIcon(HANDLE hInst, HANDLE hIcon);
[DllImport("shell32")]
public static extern int ExtractAssociatedIcon(HANDLE hInst, string lpIconPath,
ref int lpiIcon);
[DllImport("shell32")] public static extern int
ExtractIcon(HANDLE hInst, string lpszExeFileName, int
nIconIndex);
[DllImport("shell32")] public static extern int
ExtractIconEx(string lpszFile, int nIconIndex, ref int phiconLarge, ref int
phiconSmall, int nIcons);
[DllImport("shell32")] public static
extern int FindExecutable(string lpFile, string lpDirectory, string
lpResult);
[DllImport("shell32")] public static extern int
SHAppBarMessage(int dwMessage, ref APPBARDATA
pData);
[DllImport("shell32")] public static extern int
SHFileOperation(ref SHFILEOPSTRUCT
lpFileOp);
[DllImport("shell32")] public static extern int
SHGetFileInfo(string pszPath, int dwFileAttributes, ref SHFILEINFO psfi, int
cbFileInfo, int uFlags);
[DllImport("shell32")] public static
extern int SHGetNewLinkInfo(string pszLinkto, string pszDir, string pszName, ref
int pfMustCopy, int uFlags);
[DllImport("shell32")] public static
extern int ShellAbout(HWND hwnd, string szApp, string szOtherStuff, HANDLE
hIcon);
[DllImport("shell32")] public static extern int
ShellExecute(HWND hwnd, string lpOperation, string lpFile, string lpParameters,
string lpDirectory, int nShowCmd);
[DllImport("shell32")] public
static extern int Shell_NotifyIcon(int dwMessage, ref NOTIFYICONDATA
lpData);
[DllImport("shell32")] public static extern void
DragAcceptFiles(HWND hwnd, int fAccept);
[DllImport("shell32")]
public static extern void DragFinish(HANDLE
hDrop);
[DllImport("shell32")] public static extern void
SHFreeNameMappings(HANDLE hNameMappings);
[DllImport("shell32")]
public static extern void WinExecError(HWND hwnd, int error, string
lpstrFileName, string lpstrTitle);
[DllImport("shell32")] public
static extern int SHBrowseForFolder(BROWSEINFO
lpbi);
[DllImport("shell32")] public static extern int
SHGetPathFromIDList(int pidList, string lpBuffer);
  public const int ABE_BOTTOM =
3;
public const int ABE_LEFT = 0;
public const int
ABE_RIGHT = 2;
public const int ABE_TOP =
1;
public const int ABM_ACTIVATE = 0x6;
public
const int ABM_GETAUTOHIDEBAR = 0x7;
public const int ABM_GETSTATE
= 0x4;
public const int ABM_GETTASKBARPOS =
0x5;
public const int ABM_NEW = 0x0;
public const
int ABM_QUERYPOS = 0x2;
public const int ABM_REMOVE =
0x1;
public const int ABM_SETAUTOHIDEBAR = 0x8;
public const int ABM_SETPOS = 0x3;
public const
int ABM_WINDOWPOSCHANGED = 0x9;
public const int
ABN_FULLSCREENAPP = 0x2;
public const int ABN_POSCHANGED =
0x1;
public const int ABN_STATECHANGE =
0x0;
public const int ABN_WINDOWARRANGE = 0x3;
public const int ABS_ALWAYSONTOP = 0x2;
public
const int ABS_AUTOHIDE = 0x1;
public const int EIRESID =
-1;
public const int FOF_ALLOWUNDO = 0x40;
public
const int FOF_CONFIRMMOUSE = 0x2;
public const int FOF_FILESONLY
= 0x80;
public const int FOF_MULTIDESTFILES =
0x1;
public const int FOF_NOCONFIRMATION = 0x10;
public const int FOF_NOCONFIRMMKDIR = 0x200;
public const int FOF_RENAMEONCOLLISION =
0x8;
public const int FOF_SILENT = 0x4;
public
const int FOF_SIMPLEPROGRESS = 0x100;
public const int
FOF_WANTMAPPINGHANDLE = 0x20;
public const int FO_COPY =
0x2;
public const int FO_DELETE = 0x3;
public
const int FO_MOVE = 0x1;
public const int FO_RENAME =
0x4;
public const int NIF_ICON = 0x2;
public const
int NIF_MESSAGE = 0x1;
public const int NIF_TIP =
0x4;
public const int NIM_ADD = 0x0;
public const
int NIM_DELETE = 0x2;
public const int NIM_MODIFY =
0x1;
public const int PO_DELETE = 0x13;
public
const int PO_PORTCHANGE = 0x20;
public const int PO_RENAME =
0x14;
public const int PO_REN_PORT = 0x34;
public const int SEE_MASK_CLASSKEY = 0x3;
public
const int SEE_MASK_CLASSNAME = 0x1;
public const int
SEE_MASK_CONNECTNETDRV = 0x80;
public const int
SEE_MASK_DOENVSUBST = 0x200;
public const int
SEE_MASK_FLAG_DDEWAIT = 0x100;
public const int
SEE_MASK_FLAG_NO_UI = 0x400;
public const int SEE_MASK_HOTKEY =
0x20;
public const int SEE_MASK_ICON =
0x10;
public const int SEE_MASK_IDLIST =
0x4;
public const int SEE_MASK_INVOKEIDLIST =
0xC;
public const int SEE_MASK_NOCLOSEPROCESS =
0x40;
public const int SE_ERR_ACCESSDENIED = 5;
public const int SE_ERR_ASSOCINCOMPLETE =
27;
public const int SE_ERR_DDEBUSY = 30;
public
const int SE_ERR_DDEFAIL = 29;
public const int SE_ERR_DDETIMEOUT
= 28;
public const int SE_ERR_DLLNOTFOUND =
32;
public const int SE_ERR_FNF = 2;
public const
int SE_ERR_NOASSOC = 31;
public const int SE_ERR_OOM = 8;
public const int SE_ERR_PNF = 3;
public const
int SE_ERR_SHARE = 26;
public const int SHGFI_ATTRIBUTES = 0x800;
public const int SHGFI_DISPLAYNAME = 0x200;
public const int SHGFI_EXETYPE = 0x2000;
public
const int SHGFI_ICON = 0x100;
public const int
SHGFI_ICONLOCATION = 0x1000;
public const int SHGFI_LARGEICON =
0x0;
public const int SHGFI_LINKOVERLAY = 0x8000;
public const int SHGFI_OPENICON = 0x2;
public
const int SHGFI_PIDL = 0x8;
public const int SHGFI_SELECTED =
0x10000;
public const int SHGFI_SHELLICONSIZE = 0x4;
public const int SHGFI_SMALLICON = 0x1;
public
const int SHGFI_SYSICONINDEX = 0x4000;
public const int
SHGFI_TYPENAME = 0x400;
public const int SHGFI_USEFILEATTRIBUTES
= 0x10;
public const int SHGNLI_PIDL = 0x1;
public const int SHGNLI_PREFIXNAME = 0x2;
}
}


using System;
using System.Runtime.InteropServices;
using System.Text;
using HANDLE = System.IntPtr;
using HWND = System.IntPtr;
namespace Win32
{
public struct NETRESOURCE
{
public int dwScope;
public int
dwType;
public int dwDisplayType;
public int
dwUsage;
public string lpLocalName;
public string
lpRemoteName;
public string lpComment;
public
string lpProvider;
}
public struct USER_INFO_3
{
public int Name;
public int
Password;
public int PasswordAge;
public int
Privilege;
public int HomeDir;
public int
Comment;
public int Flags;
public int
ScriptPath;
public int AuthFlags;
public int
FullName;
public int UserComment;
public int
Parms;
public int Workstations;
public int
LastLogon;
public int LastLogoff;
public int
AcctExpires;
public int MaxStorage;
public int
UnitsPerWeek;
public int LogonHours;
public int
BadPwCount;
public int NumLogons;
public int
LogonServer;
public int CountryCode;
public int
CodePage;
public int UserID;
public int
PrimaryGroupID;
public int Profile;
public int
HomeDirDrive;
public int
PasswordExpired;
}
public struct GROUP_INFO_2
{
public int Name;
public int
Comment;
public int GroupID;
public int
Attributes;
}
public struct LOCALGROUP_MEMBERS_INFO_0
{
public int pSID;
}
public struct
LOCALGROUP_MEMBERS_INFO_1
{
public int
pSID;
public g_netSID_NAME_USE eUsage;
public int
psName;
}
public struct WKSTA_INFO_102
{
public int wki102_platform_id;
public
int wki102_computername;
public int
wki102_langroup;
public int
wki102_ver_major;
public int
wki102_ver_minor;
public int
wki102_lanroot;
public int
wki102_logged_on_users;
}
public struct WKSTA_USER_INFO_1
{
public int wkui1_username;
public int
wkui1_logon_domain;
public int
wkui1_oth_domains;
public int
wkui1_logon_server;
}
public enum g_netSID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup =
2,
SidTypeDomain = 3,
SidTypeAlias =
4,
SidTypeWellKnownGroup =
5,
SidTypeDeletedAccount = 6,
SidTypeInvalid =
7,
SidTypeUnknown = 8,
}
public abstract class
Mpr
{
[DllImport("mpr")] public static extern int
WNetAddConnection(string lpszNetPath, string lpszPassword, string
lpszLocalName);
[DllImport("mpr")] public static extern int
WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string
lpUserName, int dwFlags);
[DllImport("mpr")] public static extern
int WNetCancelConnection(string lpszName, int
bForce);
[DllImport("mpr")] public static extern int
WNetCancelConnection2(string lpName, int dwFlags, int
fForce);
[DllImport("mpr")] public static extern int
WNetCloseEnum(HANDLE hEnum);
[DllImport("mpr")] public static
extern int WNetConnectionDialog(HWND hwnd, int
dwType);
[DllImport("mpr")] public static extern int
WNetDisconnectDialog(HWND hwnd, int dwType);
[DllImport("mpr")]
public static extern int WNetEnumResource(HANDLE hEnum, ref int lpcCount, ref
NETRESOURCE lpBuffer, ref int lpBufferSize);
[DllImport("mpr")]
public static extern int WNetGetConnection(string lpszLocalName, string
lpszRemoteName, int cbRemoteName);
[DllImport("mpr")] public
static extern int WNetGetLastError(int lpError, StringBuilder lpErrorBuf, int
nErrorBufSize, string lpNameBuf, int
nNameBufSize);
[DllImport("mpr")] public static extern int
WNetGetUser(string lpName, StringBuilder lpUserName, ref int
lpnLength);
[DllImport("mpr")] public static extern int
WNetOpenEnum(int dwScope, int dwType, int dwUsage, ref NETRESOURCE
lpNetResource, ref int lphEnum);
}
 public abstract class
NetApi
{
[DllImport("Netapi32")] public static extern
int NetApiBufferFree(int lpBuffer);
[DllImport("Netapi32")]
public static extern int NetRemoteTOD(IntPtr yServer, int
pBuffer);
[DllImport("Netapi32")] public static extern int
NetUserChangePassword(IntPtr Domain, IntPtr User, Byte OldPass, Byte
NewPass);
[DllImport("Netapi32")] public static extern int
NetUserGetGroups(IntPtr lpServer, Byte UserName, int Level, ref int lpBuffer,
int PrefMaxLen, ref int lpEntriesRead, ref int
lpTotalEntries);
[DllImport("Netapi32")] public static extern int
NetUserGetInfo(IntPtr lpServer, Byte UserName, int Level, ref int
lpBuffer);
[DllImport("Netapi32")] public static extern int
NetUserGetLocalGroups(IntPtr lpServer, Byte UserName, int Level, int Flags, ref
int lpBuffer, int MaxLen, ref int lpEntriesRead, ref int
lpTotalEntries);
[DllImport("Netapi32")] public static extern int
NetWkstaGetInfo(IntPtr lpServer, int Level, IntPtr
lpBuffer);
[DllImport("Netapi32")] public static extern int
NetWkstaUserGetInfo(IntPtr reserved, int Level, IntPtr
lpBuffer);
[DllImport("netapi32")] public static extern int
NetUserAdd(IntPtr lpServer, int Level, ref USER_INFO_3 lpUser, ref int
lpError);
[DllImport("netapi32")] public static extern int
NetLocalGroupDelMembers(int psServer, int psLocalGroup, int lLevel, ref
LOCALGROUP_MEMBERS_INFO_0 uMember, int
lMemberCount);
[DllImport("netapi32")] public static extern int
NetLocalGroupGetMembers(int psServer, int psLocalGroup, int lLevel, int pBuffer,
int lMaxLength, int plEntriesRead, int plTotalEntries, int phResume);
public const int CNLEN = 15;
public const int CONNECT_UPDATE_PROFILE = 0x1;
public const int FILTER_INTERDOMAIN_TRUST_ACCOUNT = 0x8;
public const int FILTER_NORMAL_ACCOUNT = 0x2;
public const int FILTER_PROXY_ACCOUNT = 0x4;
public const int FILTER_SERVER_TRUST_ACCOUNT = 0x20;
public const int FILTER_TEMP_DUPLICATE_ACCOUNT = 0x1;
public const int FILTER_WORKSTATION_TRUST_ACCOUNT = 0x10;
public const int GNLEN = UNLEN;
public const int LG_INCLUDE_INDIRECT = 0x1;
public const int LM20_PWLEN = 14;
public const int MAXCOMMENTSZ = 256;
public const int NERR_BASE = 2100;
public const int NERR_GroupExists = (NERR_BASE + 123);
public const int NERR_InvalidComputer = (NERR_BASE + 251);
public const int NERR_NotPrimary = (NERR_BASE + 126);
public const int NERR_PasswordTooShort = (NERR_BASE + 145);
public const int NERR_Success = 0;
public const int NERR_UserExists = (NERR_BASE + 124);
public const int PWLEN = 256;
public const int RESOURCEDISPLAYTYPE_DOMAIN = 0x1;
public const int RESOURCEDISPLAYTYPE_FILE = 0x4;
public const int RESOURCEDISPLAYTYPE_GENERIC = 0x0;
public const int RESOURCEDISPLAYTYPE_GROUP = 0x5;
public const int RESOURCEDISPLAYTYPE_SERVER = 0x2;
public const int RESOURCEDISPLAYTYPE_SHARE = 0x3;
public const int RESOURCETYPE_ANY = 0x0;
public const int RESOURCETYPE_DISK = 0x1;
public const int RESOURCETYPE_PRINT = 0x2;
public const int RESOURCETYPE_UNKNOWN = 0xFFFF;
public const int RESOURCEUSAGE_ALL = 0x0;
public const int RESOURCEUSAGE_CONNECTABLE = 0x1;
public const int RESOURCEUSAGE_CONTAINER = 0x2;
public const int RESOURCEUSAGE_RESERVED = unchecked((int)0x80000000);
public const int RESOURCE_CONNECTED = 0x1;
public const int RESOURCE_ENUM_ALL = 0xFFFF;
public const int RESOURCE_GLOBALNET = 0x2;
public const int RESOURCE_PUBLICNET = 0x2;
public const int RESOURCE_REMEMBERED = 0x3;
public const int TIMEQ_FOREVER = -1;
public const int UF_ACCOUNTDISABLE = 0x2;
public const int UF_HOMEDIR_REQUIRED = 0x8;
public const int UF_LOCKOUT = 0x10;
public const int UF_PASSWD_CANT_CHANGE = 0x40;
public const int UF_PASSWD_NOTREQD = 0x20;
public const int UF_SCRIPT = 0x1;
public const int UNITS_PER_DAY = 24;
public const int UNITS_PER_WEEK = UNITS_PER_DAY * 7;
public const int UNLEN = 256;
public const int USER_MAXSTORAGE_UNLIMITED = -1;
public const int USER_NO_LOGOFF = -1;
public const int USER_PRIV_ADMIN = 2;
public const int USER_PRIV_GUEST = 0;
public const int USER_PRIV_MASK = 3;
public const int USER_PRIV_USER = 1;
public const int WN_ACCESS_DENIED = ERROR.ERROR_ACCESS_DENIED;
public const int WN_ALREADY_CONNECTED = ERROR.ERROR_ALREADY_ASSIGNED;
public const int WN_BAD_LOCALNAME = ERROR.ERROR_BAD_DEVICE;
public const int WN_BAD_NETNAME = ERROR.ERROR_BAD_NET_NAME;
public const int WN_BAD_PASSWORD = ERROR.ERROR_INVALID_PASSWORD;
public const int WN_BAD_POINTER = ERROR.ERROR_INVALID_ADDRESS;
public const int WN_BAD_PROFILE = ERROR.ERROR_BAD_PROFILE;
public const int WN_BAD_PROVIDER = ERROR.ERROR_BAD_PROVIDER;
public const int WN_BAD_USER = ERROR.ERROR_BAD_USERNAME;
public const int WN_BAD_VALUE = ERROR.ERROR_INVALID_PARAMETER;
public const int WN_CANNOT_OPEN_PROFILE = ERROR.ERROR_CANNOT_OPEN_PROFILE;
public const int WN_CONNECTION_CLOSED = ERROR.ERROR_CONNECTION_UNAVAIL;
public const int WN_DEVICE_ERROR = ERROR.ERROR_GEN_FAILURE;
public const int WN_DEVICE_IN_USE = ERROR.ERROR_DEVICE_IN_USE;
public const int WN_EXTENDED_ERROR = ERROR.ERROR_EXTENDED_ERROR;
public const int WN_FUNCTION_BUSY = ERROR.ERROR_BUSY;
public const int WN_MORE_DATA = ERROR.ERROR_MORE_DATA;
public const int WN_NET_ERROR = ERROR.ERROR_UNEXP_NET_ERR;
public const int WN_NOT_CONNECTED = ERROR.ERROR_NOT_CONNECTED;
public const int WN_NOT_SUPPORTED = ERROR.ERROR_NOT_SUPPORTED;
public const int WN_NO_NETWORK = ERROR.ERROR_NO_NETWORK;
public const int WN_NO_NET_OR_BAD_PATH = ERROR.ERROR_NO_NET_OR_BAD_PATH;
public const int WN_OPEN_FILES = ERROR.ERROR_OPEN_FILES;
public const int WN_OUT_OF_MEMORY = ERROR.ERROR_NOT_ENOUGH_MEMORY;
public const int WN_SUCCESS = ERROR.NO_ERROR;
public const int WN_WINDOWS_ERROR = ERROR.ERROR_UNEXP_NET_ERR;
}
}


using System;
using System.Runtime.InteropServices;
using System.Text;
using HANDLE = System.IntPtr;
using HWND = System.IntPtr;
using HDC = System.IntPtr;
namespace Win32
{
public struct SMPTE
{
public byte hour;
public byte min;
public byte sec;
public byte frame;
public byte fps;
public byte dummy;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=2)] public byte pad;
}
public struct MIDI
{
public int songptrpos;
}
public struct MMTIME
{
public int wType;
public int u;
}
public struct MIDIEVENT
{
public int dwDeltaTime;
public int dwStreamID;
public int dwEvent;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)] public int dwParms;
}
public struct MIDISTRMBUFFVER
{
public int dwVersion;
public int dwMid;
public int dwOEMVersion;
}
public struct MIDIPROPTIMEDIV
{
public int cbStruct;
public int dwTimeDiv;
}
public struct MIDIPROPTEMPO
{
public int cbStruct;
public int dwTempo;
}
public struct MIXERCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)] public string szPname;
public int fdwSupport;
public int cDestinations;
}
public struct TARGET
{
public int dwType;
public int dwDeviceID;
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)]public string szPname;
}
public struct MIXERLINE
{
public int cbStruct;
public int dwDestination;
public int dwSource;
public int dwLineID;
public int fdwLine;
public int dwUser;
public int dwComponentType;
public int cChannels;
public int cConnections;
public int cControls;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MIXER_SHORT_NAME_CHARS)]
public string szShortName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MIXER_LONG_NAME_CHARS)]
public string szName;
public TARGET tTarget;
}
public struct MIXERCONTROL
{
public int cbStruct;
public int dwControlID;
public int dwControlType;
public int fdwControl;
public int cMultipleItems;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MIXER_SHORT_NAME_CHARS)] public string szShortName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MIXER_LONG_NAME_CHARS)] public string szName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)] public int[] Bounds;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)] public int[] Metrics;
}
public struct MIXERLINECONTROLS
{
public int cbStruct;
public int dwLineID;
public int dwControl;
public int cControls;
public int cbmxctrl;
public MIXERCONTROL pamxctrl;
}
public struct MIXERCONTROLDETAILS
{
public int cbStruct;
public int dwControlID;
public int cChannels;
public int item;
public int cbDetails;
public int paDetails;
}
public struct MIXERCONTROLDETAILS_LISTTEXT
{
public int dwParam1;
public int dwParam2;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MIXER_LONG_NAME_CHARS)] public string szName;
}
public struct MIXERCONTROLDETAILS_BOOLEAN
{
public int fValue;
}
public struct MIXERCONTROLDETAILS_SIGNED
{
public int lValue;
}
public struct MIXERCONTROLDETAILS_UNSIGNED
{
public int dwValue;
}
public struct JOYINFOEX
{
public int dwSize;
public int dwFlags;
public int dwXpos;
public int dwYpos;
public int dwZpos;
public int dwRpos;
public int dwUpos;
public int dwVpos;
public int dwButtons;
public int dwButtonNumber;
public int dwPOV;
public int dwReserved1;
public int dwReserved2;
}
public struct DRVCONFIGINFO
{
public int dwDCISize;
public string lpszDCISectionName;
public string lpszDCIAliasName;
public int dnDevNode;
}
public struct WAVEHDR
{
public string lpData;
public int dwBufferLength;
public int dwBytesRecorded;
public int dwUser;
public int dwFlags;
public int dwLoops;
public int lpNext;
public int Reserved;
}
public struct WAVEOUTCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)] public string szPname;
public int dwFormats;
public short wChannels;
public int dwSupport;
}
public struct WAVEINCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)]public string szPname;
public int dwFormats;
public short wChannels;
}
public struct WAVEFORMAT
{
public short wFormatTag;
public short nChannels;
public int nSamplesPerSec;
public int nAvgBytesPerSec;
public short nBlockAlign;
}
public struct PCMWAVEFORMAT
{
public WAVEFORMAT wf;
public short wBitsPerSample;
}
public struct MIDIOUTCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)]public string szPname;
public short wTechnology;
public short wVoices;
public short wNotes;
public short wChannelMask;
public int dwSupport;
}
public struct MIDIINCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
public string szPname;
}
public struct MIDIHDR
{
public string lpData;
public int dwBufferLength;
public int dwBytesRecorded;
public int dwUser;
public int dwFlags;
public int lpNext;
public int Reserved;
}
public struct AUXCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)]public string szPname;
public short wTechnology;
public int dwSupport;
}
public struct TIMECAPS
{
public int wPeriodMin;
public int wPeriodMax;
}
public struct JOYCAPS
{
public short wMid;
public short wPid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=WinMM.MAXPNAMELEN)] public string szPname;
public short wXmin;
public short wXmax;
public short wYmin;
public short wYmax;
public short wZmin;
public short wZmax;
public short wNumButtons;
public short wPeriodMin;
public short wPeriodMax;
}
public struct JOYINFO
{
public int wXpos;
public int wYpos;
public int wZpos;
public int wButtons;
}
public struct MMIOINFO
{
public int dwFlags;
public int fccIOProc;
public int pIOProc;
public int wErrorRet;
public HANDLE htask;
public int cchBuffer;
public string pchBuffer;
public string pchNext;
public string pchEndRead;
public string pchEndWrite;
public int lBufOffset;
public int lDiskOffset;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] public int adwInfo;
public int dwReserved1;
public int dwReserved2;
public HANDLE hmmio;
}
public struct MMCKINFO
{
public int ckid;
public int ckSize;
public int fccType;
public int dwDataOffset;
public int dwFlags;
}
public struct MCI_GENERIC_PARMS
{
public int dwCallback;
}
public struct MCI_OPEN_PARMS
{
public int dwCallback;
public int wDeviceID;
public string lpstrDeviceType;
public string lpstrElementName;
public string lpstrAlias;
}
public struct MCI_PLAY_PARMS
{
public int dwCallback;
public int dwFrom;
public int dwTo;
}
public struct MCI_SEEK_PARMS
{
public int dwCallback;
public int dwTo;
}
public struct MCI_STATUS_PARMS
{
public int dwCallback;
public int dwReturn;
public int dwItem;
public short dwTrack;
}
public struct MCI_INFO_PARMS
{
public int dwCallback;
public string lpstrReturn;
public int dwRetSize;
}
public struct MCI_GETDEVCAPS_PARMS
{
public int dwCallback;
public int dwReturn;
public int dwIten;
}
public struct MCI_SYSINFO_PARMS
{
public int dwCallback;
public string lpstrReturn;
public int dwRetSize;
public int dwNumber;
public int wDeviceType;
}
public struct MCI_SET_PARMS
{
public int dwCallback;
public int dwTimeFormat;
public int dwAudio;
}
public struct MCI_BREAK_PARMS
{
public int dwCallback;
public int nVirtKey;
public HWND hwndBreak;
}
public struct MCI_SOUND_PARMS
{
public int dwCallback;
public string lpstrSoundName;
}
public struct MCI_SAVE_PARMS
{
public int dwCallback;
public string lpFileName;
}
public struct MCI_LOAD_PARMS
{
public int dwCallback;
public string lpFileName;
}
public struct MCI_RECORD_PARMS
{
public int dwCallback;
public int dwFrom;
public int dwTo;
}
public struct MCI_VD_PLAY_PARMS
{
public int dwCallback;
public int dwFrom;
public int dwTo;
public int dwSpeed;
}
public struct MCI_VD_STEP_PARMS
{
public int dwCallback;
public int dwFrames;
}
public struct MCI_VD_ESCAPE_PARMS
{
public int dwCallback;
public string lpstrCommand;
}
public struct MCI_WAVE_OPEN_PARMS
{
public int dwCallback;
public int wDeviceID;
public string lpstrDeviceType;
public string lpstrElementName;
public string lpstrAlias;
public int dwBufferSeconds;
}
public struct MCI_WAVE_DELETE_PARMS
{
public int dwCallback;
public int dwFrom;
public int dwTo;
}
public struct MCI_WAVE_SET_PARMS
{
public int dwCallback;
public int dwTimeFormat;
public int dwAudio;
public int wInput;
public int wOutput;
public short wFormatTag;
public short wReserved2;
public short nChannels;
public short wReserved3;
public int nSamplesPerSec;
public int nAvgBytesPerSec;
public short nBlockAlign;
public short wReserved4;
public short wBitsPerSample;
public short wReserved5;
}
public struct MCI_SEQ_SET_PARMS
{
public int dwCallback;
public int dwTimeFormat;
public int dwAudio;
public int dwTempo;
public int dwPort;
public int dwSlave;
public int dwMaster;
public int dwOffset;
}
public struct MCI_ANIM_OPEN_PARMS
{
public int dwCallback;
public int wDeviceID;
public string lpstrDeviceType;
public string lpstrElementName;
public string lpstrAlias;
public int dwStyle;
public HWND hwndParent;
}
public struct MCI_ANIM_PLAY_PARMS
{
public int dwCallback;
public int dwFrom;
public int dwTo;
public int dwSpeed;
}
public struct MCI_ANIM_STEP_PARMS
{
public int dwCallback;
public int dwFrames;
}
public struct MCI_ANIM_WINDOW_PARMS
{
public int dwCallback;
public HWND hwnd;
public int nCmdShow;
public string lpstrText;
}
public struct MCI_ANIM_RECT_PARMS
{
public int dwCallback;
public RECT rc;
}
public struct MCI_ANIM_UPDATE_PARMS
{
public int dwCallback;
public RECT rc;
public HDC hdc;
}
public struct MCI_OVLY_OPEN_PARMS
{
public int dwCallback;
public int wDeviceID;
public string lpstrDeviceType;
public string lpstrElementName;
public string lpstrAlias;
public int dwStyle;
public HWND hwndParent;
}
public struct MCI_OVLY_WINDOW_PARMS
{
public int dwCallback;
public HWND hwnd;
public int nCmdShow;
public string lpstrText;
}
public struct MCI_OVLY_RECT_PARMS
{
public int dwCallback;
public RECT rc;
}
public struct MCI_OVLY_SAVE_PARMS
{
public int dwCallback;
public string lpFileName;
public RECT rc;
}
public struct MCI_OVLY_LOAD_PARMS
{
public int dwCallback;
public string lpFileName;
public RECT rc;
}
 public abstract class
LZ
{
[DllImport("lz32")] public static extern int
CopyLZFile(int n1, int n2);
[DllImport("lz32")] public static
extern int LZStart();
[DllImport("lz32")] public static extern
void LZDone();
[DllImport("lz32")] public static extern int
GetExpandedName(string lpszSource, StringBuilder
lpszBuffer);
[DllImport("lz32")] public static extern int
LZCopy(HANDLE hfSource, HANDLE hfDest);
[DllImport("lz32")]
public static extern int LZInit(HANDLE
hfSrc);
[DllImport("lz32")] public static extern int
LZOpenFile(string lpszFile, ref OFSTRUCT lpOf, int
style);
[DllImport("lz32")] public static extern int
LZRead(HANDLE hfFile, string lpvBuf, int
cbread);
[DllImport("lz32")] public static extern int
LZSeek(HANDLE hfFile, int lOffset, int
nOrigin);
[DllImport("lz32")] public static extern void
LZClose(HANDLE hfFile);
}
public abstract class
WinMM
{
[DllImport("winmm")] public static extern int
mciGetYieldProc(int mciId, ref int
pdwYieldData);
[DllImport("winmm")] public static extern int
mciSetYieldProc(int mciId, int fpYieldProc, int
dwYieldData);
[DllImport("winmm")] public static extern int
mmioInstallIOProcA(int fccIOProc, ref int pIOProc, int
dwFlags);
[DllImport("winmm")] public static extern short
midiOutGetNumDevs();
[DllImport("winmm")] public static extern
int CloseDriver(HANDLE hDriver, int lParam1, int
lParam2);
[DllImport("winmm")] public static extern int
DefDriverProc(int dwDriverIdentifier, HANDLE hdrvr, int uMsg, int lParam1, int
lParam2);
[DllImport("winmm")] public static extern int
DrvGetModuleHandle(HANDLE hDriver);
[DllImport("winmm")] public
static extern int GetDriverModuleHandle(HANDLE
hDriver);
[DllImport("winmm")] public static extern int
OpenDriver(string szDriverName, string szSectionName, int
lParam2);
[DllImport("winmm")] public static extern int
PlaySound(string lpszName, HANDLE hModule, int
dwFlags);
[DllImport("winmm")] public static extern int
SendDriverMessage(HANDLE hDriver, int message, int lParam1, int
lParam2);
[DllImport("winmm")] public static extern int
auxGetDevCaps(int uDeviceID, ref AUXCAPS lpCaps, int
uSize);
[DllImport("winmm")] public static extern int
auxGetNumDevs();
[DllImport("winmm")] public static extern int
auxGetVolume(int uDeviceID, ref int
lpdwVolume);
[DllImport("winmm")] public static extern int
auxOutMessage(int uDeviceID, int msg, int dw1, int
dw2);
[DllImport("winmm")] public static extern int
auxSetVolume(int uDeviceID, int dwVolume);
[DllImport("winmm")]
public static extern int joyGetDevCaps(int id, ref JOYCAPS lpCaps, int
uSize);
[DllImport("winmm")] public static extern int
joyGetNumDevs();
[DllImport("winmm")] public static extern int
joyGetPos(int uJoyID, ref JOYINFO pji);
[DllImport("winmm")]
public static extern int joyGetPosEx(int uJoyID, ref JOYINFOEX
pji);
[DllImport("winmm")] public static extern int
joyGetThreshold(int id, ref int
lpuThreshold);
[DllImport("winmm")] public static extern int
joyReleaseCapture(int id);
[DllImport("winmm")] public static
extern int joySetCapture(HWND hwnd, int uID, int uPeriod, int
bChanged);
[DllImport("winmm")] public static extern int
joySetThreshold(int id, int uThreshold);
[DllImport("winmm")]
public static extern int mciExecute(string
lpstrCommand);
[DllImport("winmm")] public static extern int
mciGetCreatorTask(int wDeviceID);
[DllImport("winmm")] public
static extern int mciGetDeviceID(string
lpstrName);
[DllImport("winmm")] public static extern int
mciGetDeviceIDFromElementID(int dwElementID, string
lpstrType);
[DllImport("winmm")] public static extern int
mciGetErrorString(int dwError, string lpstrBuffer, int
uLength);
[DllImport("winmm")] public static extern int
mciSendCommand(int wDeviceID, int uMessage, int dwParam1, IntPtr
dwParam2);
[DllImport("winmm")] public static extern int
mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int
uReturnLength, HWND hwndCallback);
[DllImport("winmm")] public
static extern int midiConnect(HANDLE hmi, HANDLE hmo, IntPtr
pReserved);
[DllImport("winmm")] public static extern int
midiDisconnect(HANDLE hmi, HANDLE hmo, IntPtr
pReserved);
[DllImport("winmm")] public static extern int
midiInAddBuffer(HANDLE hMidiIn, ref MIDIHDR lpMidiInHdr, int
uSize);
[DllImport("winmm")] public static extern int
midiInClose(HANDLE hMidiIn);
[DllImport("winmm")] public static
extern int midiInGetDevCaps(int uDeviceID, ref MIDIINCAPS lpCaps, int
uSize);
[DllImport("winmm")] public static extern int
midiInGetErrorText(int err, string lpText, int
uSize);
[DllImport("winmm")] public static extern int
midiInGetID(HANDLE hMidiIn, ref int
lpuDeviceID);
[DllImport("winmm")] public static extern int
midiInGetNumDevs();
[DllImport("winmm")] public static extern int
midiInMessage(HANDLE hMidiIn, int msg, int dw1, int
dw2);
[DllImport("winmm")] public static extern int
midiInOpen(int lphMidiIn, int uDeviceID, int dwCallback, int dwInstance, int
dwFlags);
[DllImport("winmm")] public static extern int
midiInPrepareHeader(HANDLE hMidiIn, ref MIDIHDR lpMidiInHdr, int
uSize);
[DllImport("winmm")] public static extern int
midiInReset(HANDLE hMidiIn);
[DllImport("winmm")] public static
extern int midiInStart(HANDLE hMidiIn);
[DllImport("winmm")]
public static extern int midiInStop(HANDLE
hMidiIn);
[DllImport("winmm")] public static extern int
midiInUnprepareHeader(HANDLE hMidiIn, ref MIDIHDR lpMidiInHdr, int
uSize);
[DllImport("winmm")] public static extern int
midiOutCacheDrumPatches(HANDLE hMidiOut, int uPatch, ref int lpKeyArray, int
uFlags);
[DllImport("winmm")] public static extern int
midiOutCachePatches(HANDLE hMidiOut, int uBank, ref int lpPatchArray, int
uFlags);
[DllImport("winmm")] public static extern int
midiOutClose(HANDLE hMidiOut);
[DllImport("winmm")] public static
extern int midiOutGetDevCaps(int uDeviceID, ref MIDIOUTCAPS lpCaps, int
uSize);
[DllImport("winmm")] public static extern int
midiOutGetErrorText(int err, StringBuilder lpText, int
uSize);
[DllImport("winmm")] public static extern int
midiOutGetID(HANDLE hMidiOut, ref int
lpuDeviceID);
[DllImport("winmm")] public static extern int
midiOutGetVolume(int uDeviceID, ref int
lpdwVolume);
[DllImport("winmm")] public static extern int
midiOutLongMsg(HANDLE hMidiOut, ref MIDIHDR lpMidiOutHdr, int
uSize);
[DllImport("winmm")] public static extern int
midiOutMessage(HANDLE hMidiOut, int msg, int dw1, int
dw2);
[DllImport("winmm")] public static extern int
midiOutOpen(int lphMidiOut, int uDeviceID, int dwCallback, int dwInstance, int
dwFlags);
[DllImport("winmm")] public static extern int
midiOutPrepareHeader(HANDLE hMidiOut, ref MIDIHDR lpMidiOutHdr, int
uSize);
[DllImport("winmm")] public static extern int
midiOutReset(HANDLE hMidiOut);
[DllImport("winmm")] public static
extern int midiOutSetVolume(int uDeviceID, int
dwVolume);
[DllImport("winmm")] public static extern int
midiOutShortMsg(HANDLE hMidiOut, int dwMsg);
[DllImport("winmm")]
public static extern int midiOutUnprepareHeader(HANDLE hMidiOut, ref MIDIHDR
lpMidiOutHdr, int uSize);
[DllImport("winmm")] public static
extern int midiStreamClose(HANDLE hms);
[DllImport("winmm")]
public static extern int midiStreamOpen(int phms, int puDeviceID, int cMidi, int
dwCallback, int dwInstance, int fdwOpen);
[DllImport("winmm")]
public static extern int midiStreamOut(HANDLE hms, ref MIDIHDR pmh, int
cbmh);
[DllImport("winmm")] public static extern int
midiStreamPause(HANDLE hms);
[DllImport("winmm")] public static
extern int midiStreamPosition(HANDLE hms, ref MMTIME lpmmt, int
cbmmt);
[DllImport("winmm")] public static extern int
midiStreamProperty(HANDLE hms, Byte lppropdata, int
dwProperty);
[DllImport("winmm")] public static extern int
midiStreamRestart(HANDLE hms);
[DllImport("winmm")] public static
extern int midiStreamStop(HANDLE hms);
[DllImport("winmm")]
public static extern int mixerClose(HANDLE
hmx);
[DllImport("winmm")] public static extern int
mixerGetControlDetails(HANDLE hmxobj, ref MIXERCONTROLDETAILS pmxcd, int
fdwDetails);
[DllImport("winmm")] public static extern int
mixerGetDevCaps(int uMxId, ref MIXERCAPS pmxcaps, int
cbmxcaps);
[DllImport("winmm")] public static extern int
mixerGetID(HANDLE hmxobj, ref int pumxID, int
fdwId);
[DllImport("winmm")] public static extern int
mixerGetLineControls(HANDLE hmxobj, ref MIXERLINECONTROLS pmxlc, int
fdwControls);
[DllImport("winmm")] public static extern int
mixerGetLineInfo(HANDLE hmxobj, ref MIXERLINE pmxl, int
fdwInfo);
[DllImport("winmm")] public static extern int
mixerGetNumDevs();
[DllImport("winmm")] public static extern int
mixerMessage(HANDLE hmx, int uMsg, int dwParam1, int
dwParam2);
[DllImport("winmm")] public static extern int
mixerOpen(int phmx, int uMxId, int dwCallback, int dwInstance, int
fdwOpen);
[DllImport("winmm")] public static extern int
mixerSetControlDetails(HANDLE hmxobj, ref MIXERCONTROLDETAILS pmxcd, int
fdwDetails);
[DllImport("winmm")] public static extern int
mmioAdvance(HANDLE hmmio, ref MMIOINFO lpmmioinfo, int
uFlags);
[DllImport("winmm")] public static extern int
mmioAscend(HANDLE hmmio, ref MMCKINFO lpck, int
uFlags);
[DllImport("winmm")] public static extern int
mmioClose(HANDLE hmmio, int uFlags);
[DllImport("winmm")] public
static extern int mmioCreateChunk(HANDLE hmmio, ref MMCKINFO lpck, int
uFlags);
[DllImport("winmm")] public static extern int
mmioDescend(HANDLE hmmio, ref MMCKINFO lpck, ref MMCKINFO lpckParent, int
uFlags);
[DllImport("winmm")] public static extern int
mmioFlush(HANDLE hmmio, int uFlags);
[DllImport("winmm")] public
static extern int mmioGetInfo(HANDLE hmmio, ref MMIOINFO lpmmioinfo, int
uFlags);
[DllImport("winmm")] public static extern int
mmioOpen(string szFileName, ref MMIOINFO lpmmioinfo, int
dwOpenFlags);
[DllImport("winmm")] public static extern int
mmioRead(HANDLE hmmio, string pch, int cch);
[DllImport("winmm")]
public static extern int mmioRename(string szFileName, string SzNewFileName, ref
MMIOINFO lpmmioinfo, int dwRenameFlags);
[DllImport("winmm")]
public static extern int mmioSeek(HANDLE hmmio, int lOffset, int
iOrigin);
[DllImport("winmm")] public static extern int
mmioSendMessage(HANDLE hmmio, int uMsg, int lParam1, int
lParam2);
[DllImport("winmm")] public static extern int
mmioSetBuffer(HANDLE hmmio, string pchBuffer, int cchBuffer, int
uFlags);
[DllImport("winmm")] public static extern int
mmioSetInfo(HANDLE hmmio, ref MMIOINFO lpmmioinfo, int
uFlags);
[DllImport("winmm")] public static extern int
mmioStringToFOURCC(string sz, int uFlags);
[DllImport("winmm")]
public static extern int mmioWrite(HANDLE hmmio, string pch, int
cch);
[DllImport("winmm")] public static extern int
mmsystemGetVersion();
[DllImport("winmm")] public static extern
int sndPlaySound(string lpszSoundName, int
uFlags);
[DllImport("winmm")] public static extern int
timeBeginPeriod(int uPeriod);
[DllImport("winmm")] public static
extern int timeEndPeriod(int uPeriod);
[DllImport("winmm")]
public static extern int timeGetDevCaps(ref TIMECAPS lpTimeCaps, int
uSize);
[DllImport("winmm")] public static extern int
timeGetSystemTime(ref MMTIME lpTime, int
uSize);
[DllImport("winmm")] public static extern int
timeGetTime();
[DllImport("winmm")] public static extern int
timeKillEvent(int uID);
[DllImport("winmm")] public static extern
int timeSetEvent(int uDelay, int uResolution, ref int lpFunction, int dwUser,
int uFlags);
[DllImport("winmm")] public static extern int
waveInAddBuffer(HANDLE hWaveIn, ref WAVEHDR lpWaveInHdr, int
uSize);
[DllImport("winmm")] public static extern int
waveInClose(HANDLE hWaveIn);
[DllImport("winmm")] public static
extern int waveInGetDevCaps(int uDeviceID, ref WAVEINCAPS lpCaps, int
uSize);
[DllImport("winmm")] public static extern int
waveInGetErrorText(int err, string lpText, int
uSize);
[DllImport("winmm")] public static extern int
waveInGetID(HANDLE hWaveIn, ref int
lpuDeviceID);
[DllImport("winmm")] public static extern int
waveInGetNumDevs();
[DllImport("winmm")] public static extern int
waveInGetPosition(HANDLE hWaveIn, ref MMTIME lpInfo, int
uSize);
[DllImport("winmm")] public static extern int
waveInMessage(HANDLE hWaveIn, int msg, int dw1, int
dw2);
[DllImport("winmm")] public static extern int
waveInOpen(int lphWaveIn, int uDeviceID, ref WAVEFORMAT lpFormat, int
dwCallback, int dwInstance, int dwFlags);
[DllImport("winmm")]
public static extern int waveInPrepareHeader(HANDLE hWaveIn, ref WAVEHDR
lpWaveInHdr, int uSize);
[DllImport("winmm")] public static
extern int waveInReset(HANDLE hWaveIn);
[DllImport("winmm")]
public static extern int waveInStart(HANDLE
hWaveIn);
[DllImport("winmm")] public static extern int
waveInStop(HANDLE hWaveIn);
[DllImport("winmm")] public static
extern int waveInUnprepareHeader(HANDLE hWaveIn, ref WAVEHDR lpWaveInHdr, int
uSize);
[DllImport("winmm")] public static extern int
waveOutBreakLoop(HANDLE hWaveOut);
[DllImport("winmm")] public
static extern int waveOutClose(HANDLE
hWaveOut);
[DllImport("winmm")] public static extern int
waveOutGetDevCaps(int uDeviceID, ref WAVEOUTCAPS lpCaps, int
uSize);
[DllImport("winmm")] public static extern int
waveOutGetErrorText(int err, string lpText, int
uSize);
[DllImport("winmm")] public static extern int
waveOutGetID(HANDLE hWaveOut, ref int
lpuDeviceID);
[DllImport("winmm")] public static extern int
waveOutGetNumDevs();
[DllImport("winmm")] public static extern
int waveOutGetPitch(HANDLE hWaveOut, ref int
lpdwPitch);
[DllImport("winmm")] public static extern int
waveOutGetPlaybackRate(HANDLE hWaveOut, ref int
lpdwRate);
[DllImport("winmm")] public static extern int
waveOutGetPosition(HANDLE hWaveOut, ref MMTIME lpInfo, int
uSize);
[DllImport("winmm")] public static extern int
waveOutGetVolume(int uDeviceID, ref int
lpdwVolume);
[DllImport("winmm")] public static extern int
waveOutMessage(HANDLE hWaveOut, int msg, int dw1, int
dw2);
[DllImport("winmm")] public static extern int
waveOutOpen(int lphWaveOut, int uDeviceID, ref WAVEFORMAT lpFormat, int
dwCallback, int dwInstance, int dwFlags);
[DllImport("winmm")]
public static extern int waveOutPause(HANDLE
hWaveOut);
[DllImport("winmm")] public static extern int
waveOutPrepareHeader(HANDLE hWaveOut, ref WAVEHDR lpWaveOutHdr, int
uSize);
[DllImport("winmm")] public static extern int
waveOutReset(HANDLE hWaveOut);
[DllImport("winmm")] public static
extern int waveOutRestart(HANDLE hWaveOut);
[DllImport("winmm")]
public static extern int waveOutSetPitch(HANDLE hWaveOut, int
dwPitch);
[DllImport("winmm")] public static extern int
waveOutSetPlaybackRate(HANDLE hWaveOut, int
dwRate);
[DllImport("winmm")] public static extern int
waveOutSetVolume(int uDeviceID, int
dwVolume);
[DllImport("winmm")] public static extern int
waveOutUnprepareHeader(HANDLE hWaveOut, ref WAVEHDR lpWaveOutHdr, int
uSize);
[DllImport("winmm")] public static extern int
waveOutWrite(HANDLE hWaveOut, ref WAVEHDR lpWaveOutHdr, int uSize);
public const int AUXCAPS_AUXIN = 2;
public const int AUXCAPS_CDAUDIO = 1;
public const int AUXCAPS_LRVOLUME = 0x2;
public const int AUXCAPS_VOLUME = 0x1;
public const int AUX_MAPPER = -1;
public const int C1_TRANSPARENT = 0x1;
public const int CALLBACK_FUNCTION = 0x30000;
public const int CALLBACK_NULL = 0x0;
public const int CALLBACK_TASK = 0x20000;
public const int CALLBACK_TYPEMASK = 0x70000;
public const int CALLBACK_WINDOW = 0x10000;
public const int CAPS1 = 94;
public const int DRVCNF_CANCEL = 0x0;
public const int DRVCNF_OK = 0x1;
public const int DRVCNF_RESTART = 0x2;
public const int DRV_CANCEL = DRVCNF_CANCEL;
public const int DRV_CLOSE = 0x4;
public const int DRV_CONFIGURE = 0x7;
public const int DRV_DISABLE = 0x5;
public const int DRV_ENABLE = 0x2;
public const int DRV_EXITSESSION = 0xB;
public const int DRV_FREE = 0x6;
public const int DRV_INSTALL = 0x9;
public const int DRV_LOAD = 0x1;
public const int DRV_MCI_FIRST = DRV_RESERVED;
public const int DRV_MCI_LAST = DRV_RESERVED + 0xFFF;
public const int DRV_OK = DRVCNF_OK;
public const int DRV_OPEN = 0x3;
public const int DRV_POWER = 0xF;
public const int DRV_QUERYCONFIGURE = 0x8;
public const int DRV_REMOVE = 0xA;
public const int DRV_RESERVED = 0x800;
public const int DRV_RESTART = DRVCNF_RESTART;
public const int DRV_USER = 0x4000;
public const int JOYERR_BASE = 160;
public const int JOYERR_NOCANDO = (JOYERR_BASE + 6);
public const int JOYERR_NOERROR = (0);
public const int JOYERR_PARMS = (JOYERR_BASE + 5);
public const int JOYERR_UNPLUGGED = (JOYERR_BASE + 7);
public const int JOYSTICKID1 = 0;
public const int JOYSTICKID2 = 1;
public const int JOY_BUTTON1 = 0x1;
public const int JOY_BUTTON10 = 0x200;
public const int JOY_BUTTON11 = 0x400;
public const int JOY_BUTTON12 = 0x800;
public const int JOY_BUTTON13 = 0x1000;
public const int JOY_BUTTON14 = 0x2000;
public const int JOY_BUTTON15 = 0x4000;
public const int JOY_BUTTON16 = 0x8000;
public const int JOY_BUTTON17 = 0x10000;
public const int JOY_BUTTON18 = 0x20000;
public const int JOY_BUTTON19 = 0x40000;
public const int JOY_BUTTON1CHG = 0x100;
public const int JOY_BUTTON2 = 0x2;
public const int JOY_BUTTON20 = 0x80000;
public const int JOY_BUTTON21 = 0x100000;
public const int JOY_BUTTON22 = 0x200000;
public const int JOY_BUTTON23 = 0x400000;
public const int JOY_BUTTON24 = 0x800000;
public const int JOY_BUTTON25 = 0x1000000;
public const int JOY_BUTTON26 = 0x2000000;
public const int JOY_BUTTON27 = 0x4000000;
public const int JOY_BUTTON28 = 0x8000000;
public const int JOY_BUTTON29 = 0x10000000;
public const int JOY_BUTTON2CHG = 0x200;
public const int JOY_BUTTON3 = 0x4;
public const int JOY_BUTTON30 = 0x20000000;
public const int JOY_BUTTON31 = 0x40000000;
public const int JOY_BUTTON32 = unchecked((int)0x80000000);
public const int JOY_BUTTON3CHG = 0x400;
public const int JOY_BUTTON4 = 0x8;
public const int JOY_BUTTON4CHG = 0x800;
public const int JOY_BUTTON5 = 0x10;
public const int JOY_BUTTON6 = 0x20;
public const int JOY_BUTTON7 = 0x40;
public const int JOY_BUTTON8 = 0x80;
public const int JOY_BUTTON9 = 0x100;
public const int JOY_CAL_READ3 = 0x40000;
public const int JOY_CAL_READ4 = 0x80000;
public const int JOY_CAL_READ5 = 0x400000;
public const int JOY_CAL_READ6 = 0x800000;
public const int JOY_CAL_READALWAYS = 0x10000;
public const int JOY_CAL_READRONLY = 0x2000000;
public const int JOY_CAL_READUONLY = 0x4000000;
public const int JOY_CAL_READVONLY = 0x8000000;
public const int JOY_CAL_READXONLY = 0x100000;
public const int JOY_CAL_READXYONLY = 0x20000;
public const int JOY_CAL_READYONLY = 0x200000;
public const int JOY_CAL_READZONLY = 0x1000000;
public const int JOY_POVBACKWARD = 18000;
public const int JOY_POVCENTERED = -1;
public const int JOY_POVFORWARD = 0;
public const int JOY_POVLEFT = 27000;
public const int JOY_POVRIGHT = 9000;
public const int JOY_RETURNALL = (JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | JOY_RETURNPOV | JOY_RETURNBUTTONS);
public const int JOY_RETURNBUTTONS = 0x80;
public const int JOY_RETURNCENTERED = 0x400;
public const int JOY_RETURNPOV = 0x40;
public const int JOY_RETURNPOVCTS = 0x200;
public const int JOY_RETURNR = 0x8;
public const int JOY_RETURNRAWDATA = 0x100;
public const int JOY_RETURNU = 0x10;
public const int JOY_RETURNV = 0x20;
public const int JOY_RETURNX = 0x1;
public const int JOY_RETURNY = 0x2;
public const int JOY_RETURNZ = 0x4;
public const int JOY_USEDEADZONE = 0x800;
public const int LZERROR_BADINHANDLE = (-1);
public const int LZERROR_BADOUTHANDLE = (-2);
public const int LZERROR_BADVALUE = (-7);
public const int LZERROR_GLOBLOCK = (-6);
public const int LZERROR_PUBLICLOC = (-5);
public const int LZERROR_READ = (-3);
public const int LZERROR_UNKNOWNALG = (-8);
public const int LZERROR_WRITE = (-4);
public const int MAXERRORLENGTH = 128;
public const int MAXPNAMELEN = 32;
public const int MCIERR_BAD_CONSTANT = (MCIERR_BASE + 34);
public const int MCIERR_BAD_INTEGER = (MCIERR_BASE + 14);
public const int MCIERR_BAD_TIME_FORMAT = (MCIERR_BASE + 37);
public const int MCIERR_BASE = 256;
public const int MCIERR_CANNOT_LOAD_DRIVER = (MCIERR_BASE + 10);
public const int MCIERR_CANNOT_USE_ALL = (MCIERR_BASE + 23);
public const int MCIERR_CREATEWINDOW = (MCIERR_BASE + 91);
public const int MCIERR_CUSTOM_DRIVER_BASE = (MCIERR_BASE + 256);
public const int MCIERR_DEVICE_LENGTH = (MCIERR_BASE + 54);
public const int MCIERR_DEVICE_LOCKED = (MCIERR_BASE + 32);
public const int MCIERR_DEVICE_NOT_INSTALLED = (MCIERR_BASE + 50);
public const int MCIERR_DEVICE_NOT_READY = (MCIERR_BASE + 20);
public const int MCIERR_DEVICE_OPEN = (MCIERR_BASE + 9);
public const int MCIERR_DEVICE_ORD_LENGTH = (MCIERR_BASE + 55);
public const int MCIERR_DEVICE_TYPE_REQUIRED = (MCIERR_BASE + 31);
public const int MCIERR_DRIVER = (MCIERR_BASE + 22);
public const int MCIERR_DRIVER_INTERNAL = (MCIERR_BASE + 16);
public const int MCIERR_DUPLICATE_ALIAS = (MCIERR_BASE + 33);
public const int MCIERR_DUPLICATE_FLAGS = (MCIERR_BASE + 39);
public const int MCIERR_EXTENSION_NOT_FOUND = (MCIERR_BASE + 25);
public const int MCIERR_EXTRA_CHARACTERS = (MCIERR_BASE + 49);
public const int MCIERR_FILENAME_REQUIRED = (MCIERR_BASE + 48);
public const int MCIERR_FILE_NOT_FOUND = (MCIERR_BASE + 19);
public const int MCIERR_FILE_NOT_SAVED = (MCIERR_BASE + 30);
public const int MCIERR_FILE_READ = (MCIERR_BASE + 92);
public const int MCIERR_FILE_WRITE = (MCIERR_BASE + 93);
public const int MCIERR_FLAGS_NOT_COMPATIBLE = (MCIERR_BASE + 28);
public const int MCIERR_GET_CD = (MCIERR_BASE + 51);
public const int MCIERR_HARDWARE = (MCIERR_BASE + 6);
public const int MCIERR_ILLEGAL_FOR_AUTO_OPEN = (MCIERR_BASE + 47);
public const int MCIERR_INTERNAL = (MCIERR_BASE + 21);
public const int MCIERR_INVALID_DEVICE_ID = (MCIERR_BASE + 1);
public const int MCIERR_INVALID_DEVICE_NAME = (MCIERR_BASE + 7);
public const int MCIERR_INVALID_FILE = (MCIERR_BASE + 40);
public const int MCIERR_MISSING_COMMAND_STRING = (MCIERR_BASE + 11);
public const int MCIERR_MISSING_DEVICE_NAME = (MCIERR_BASE + 36);
public const int MCIERR_MISSING_PARAMETER = (MCIERR_BASE + 17);
public const int MCIERR_MISSING_STRING_ARGUMENT = (MCIERR_BASE + 13);
public const int MCIERR_MULTIPLE = (MCIERR_BASE + 24);
public const int MCIERR_MUST_USE_SHAREABLE = (MCIERR_BASE + 35);
public const int MCIERR_NEW_REQUIRES_ALIAS = (MCIERR_BASE + 43);
public const int MCIERR_NONAPPLICABLE_FUNCTION = (MCIERR_BASE + 46);
public const int MCIERR_NOTIFY_ON_AUTO_OPEN = (MCIERR_BASE + 44);
public const int MCIERR_NO_CLOSING_QUOTE = (MCIERR_BASE + 38);
public const int MCIERR_NO_ELEMENT_ALLOWED = (MCIERR_BASE + 45);
public const int MCIERR_NO_INTEGER = (MCIERR_BASE + 56);
public const int MCIERR_NO_WINDOW = (MCIERR_BASE + 90);
public const int MCIERR_NULL_PARAMETER_BLOCK = (MCIERR_BASE + 41);
public const int MCIERR_OUTOFRANGE = (MCIERR_BASE + 26);
public const int MCIERR_OUT_OF_MEMORY = (MCIERR_BASE + 8);
public const int MCIERR_PARAM_OVERFLOW = (MCIERR_BASE + 12);
public const int MCIERR_PARSER_INTERNAL = (MCIERR_BASE + 15);
public const int MCIERR_SEQ_DIV_INCOMPATIBLE = (MCIERR_BASE + 80);
public const int MCIERR_SEQ_NOMIDIPRESENT = (MCIERR_BASE + 87);
public const int MCIERR_SEQ_PORTUNSPECIFIED = (MCIERR_BASE + 86);
public const int MCIERR_SEQ_PORT_INUSE = (MCIERR_BASE + 81);
public const int MCIERR_SEQ_PORT_MAPNODEVICE = (MCIERR_BASE + 83);
public const int MCIERR_SEQ_PORT_MISCERROR = (MCIERR_BASE + 84);
public const int MCIERR_SEQ_PORT_NONEXISTENT = (MCIERR_BASE + 82);
public const int MCIERR_SEQ_TIMER = (MCIERR_BASE + 85);
public const int MCIERR_SET_CD = (MCIERR_BASE + 52);
public const int MCIERR_SET_DRIVE = (MCIERR_BASE + 53);
public const int MCIERR_UNNAMED_RESOURCE = (MCIERR_BASE + 42);
public const int MCIERR_UNRECOGNIZED_COMMAND = (MCIERR_BASE + 5);
public const int MCIERR_UNRECOGNIZED_KEYWORD = (MCIERR_BASE + 3);
public const int MCIERR_UNSUPPORTED_FUNCTION = (MCIERR_BASE + 18);
public const int MCIERR_WAVE_INPUTSINUSE = (MCIERR_BASE + 66);
public const int MCIERR_WAVE_INPUTSUNSUITABLE = (MCIERR_BASE + 72);
public const int MCIERR_WAVE_INPUTUNSPECIFIED = (MCIERR_BASE + 69);
public const int MCIERR_WAVE_OUTPUTSINUSE = (MCIERR_BASE + 64);
public const int MCIERR_WAVE_OUTPUTSUNSUITABLE = (MCIERR_BASE + 70);
public const int MCIERR_WAVE_OUTPUTUNSPECIFIED = (MCIERR_BASE + 68);
public const int MCIERR_WAVE_SETINPUTINUSE = (MCIERR_BASE + 67);
public const int MCIERR_WAVE_SETINPUTUNSUITABLE = (MCIERR_BASE + 73);
public const int MCIERR_WAVE_SETOUTPUTINUSE = (MCIERR_BASE + 65);
public const int MCIERR_WAVE_SETOUTPUTUNSUITABLE = (MCIERR_BASE + 71);
public const int MCI_ALL_DEVICE_ID = - 1;
public const int MCI_ANIM_GETDEVCAPS_CAN_REVERSE = 0x4001;
public const int MCI_ANIM_GETDEVCAPS_CAN_STRETCH = 0x4007;
public const int MCI_ANIM_GETDEVCAPS_FAST_RATE = 0x4002;
public const int MCI_ANIM_GETDEVCAPS_MAX_WINDOWS = 0x4008;
public const int MCI_ANIM_GETDEVCAPS_NORMAL_RATE = 0x4004;
public const int MCI_ANIM_GETDEVCAPS_PALETTES = 0x4006;
public const int MCI_ANIM_GETDEVCAPS_SLOW_RATE = 0x4003;
public const int MCI_ANIM_INFO_TEXT = 0x10000;
public const int MCI_ANIM_OPEN_NOSTATIC = 0x40000;
public const int MCI_ANIM_OPEN_PARENT = 0x20000;
public const int MCI_ANIM_OPEN_WS = 0x10000;
public const int MCI_ANIM_PLAY_FAST = 0x40000;
public const int MCI_ANIM_PLAY_REVERSE = 0x20000;
public const int MCI_ANIM_PLAY_SCAN = 0x100000;
public const int MCI_ANIM_PLAY_SLOW = 0x80000;
public const int MCI_ANIM_PLAY_SPEED = 0x10000;
public const int MCI_ANIM_PUT_DESTINATION = 0x40000;
public const int MCI_ANIM_PUT_SOURCE = 0x20000;
public const int MCI_ANIM_REALIZE_BKGD = 0x20000;
public const int MCI_ANIM_REALIZE_NORM = 0x10000;
public const int MCI_ANIM_RECT = 0x10000;
public const int MCI_ANIM_STATUS_FORWARD = 0x4002;
public const int MCI_ANIM_STATUS_HPAL = 0x4004;
public const int MCI_ANIM_STATUS_HWND = 0x4003;
public const int MCI_ANIM_STATUS_SPEED = 0x4001;
public const int MCI_ANIM_STATUS_STRETCH = 0x4005;
public const int MCI_ANIM_STEP_FRAMES = 0x20000;
public const int MCI_ANIM_STEP_REVERSE = 0x10000;
public const int MCI_ANIM_UPDATE_HDC = 0x20000;
public const int MCI_ANIM_WHERE_DESTINATION = 0x40000;
public const int MCI_ANIM_WHERE_SOURCE = 0x20000;
public const int MCI_ANIM_WINDOW_DEFAULT = 0x0;
public const int MCI_ANIM_WINDOW_DISABLE_STRETCH = 0x200000;
public const int MCI_ANIM_WINDOW_ENABLE_STRETCH = 0x100000;
public const int MCI_ANIM_WINDOW_HWND = 0x10000;
public const int MCI_ANIM_WINDOW_STATE = 0x40000;
public const int MCI_ANIM_WINDOW_TEXT = 0x80000;
public const int MCI_BREAK = 0x811;
public const int MCI_BREAK_HWND = 0x200;
public const int MCI_BREAK_KEY = 0x100;
public const int MCI_BREAK_OFF = 0x400;
public const int MCI_CD_OFFSET = 1088;
public const int MCI_CLOSE = 0x804;
public const int MCI_COPY = 0x852;
public const int MCI_CUE = 0x830;
public const int MCI_CUT = 0x851;
public const int MCI_DELETE = 0x856;
public const int MCI_DEVTYPE_ANIMATION = 519;
public const int MCI_DEVTYPE_CD_AUDIO = 516;
public const int MCI_DEVTYPE_DAT = 517;
public const int MCI_DEVTYPE_DIGITAL_VIDEO = 520;
public const int MCI_DEVTYPE_FIRST = MCI_DEVTYPE_VCR;
public const int MCI_DEVTYPE_FIRST_USER = 0x1000;
public const int MCI_DEVTYPE_LAST = MCI_DEVTYPE_SEQUENCER;
public const int MCI_DEVTYPE_OTHER = 521;
public const int MCI_DEVTYPE_OVERLAY = 515;
public const int MCI_DEVTYPE_SCANNER = 518;
public const int MCI_DEVTYPE_SEQUENCER = 523;
public const int MCI_DEVTYPE_VCR = 513;
public const int MCI_DEVTYPE_VIDEODISC = 514;
public const int MCI_DEVTYPE_WAVEFORM_AUDIO = 522;
public const int MCI_ESCAPE = 0x805;
public const int MCI_FIRST = 0x800;
public const int MCI_FORMAT_BYTES = 8;
public const int MCI_FORMAT_FRAMES = 3;
public const int MCI_FORMAT_HMS = 1;
public const int MCI_FORMAT_MILLISECONDS = 0;
public const int MCI_FORMAT_MSF = 2;
public const int MCI_FORMAT_SAMPLES = 9;
public const int MCI_FORMAT_SMPTE_24 = 4;
public const int MCI_FORMAT_SMPTE_25 = 5;
public const int MCI_FORMAT_SMPTE_30 = 6;
public const int MCI_FORMAT_SMPTE_30DROP = 7;
public const int MCI_FORMAT_TMSF = 10;
public const int MCI_FREEZE = 0x844;
public const int MCI_FROM = 0x4;
public const int MCI_GETDEVCAPS = 0x80B;
public const int MCI_GETDEVCAPS_CAN_EJECT = 0x7;
public const int MCI_GETDEVCAPS_CAN_PLAY = 0x8;
public const int MCI_GETDEVCAPS_CAN_RECORD = 0x1;
public const int MCI_GETDEVCAPS_CAN_SAVE = 0x9;
public const int MCI_GETDEVCAPS_COMPOUND_DEVICE = 0x6;
public const int MCI_GETDEVCAPS_DEVICE_TYPE = 0x4;
public const int MCI_GETDEVCAPS_HAS_AUDIO = 0x2;
public const int MCI_GETDEVCAPS_HAS_VIDEO = 0x3;
public const int MCI_GETDEVCAPS_ITEM = 0x100;
public const int MCI_GETDEVCAPS_USES_FILES = 0x5;
public const int MCI_INFO = 0x80A;
public const int MCI_INFO_FILE = 0x200;
public const int MCI_INFO_PRODUCT = 0x100;
public const int MCI_LAST = 0xFFF;
public const int MCI_LOAD = 0x850;
public const int MCI_LOAD_FILE = 0x100;
public const int MCI_MODE_NOT_READY = (MCI_STRING_OFFSET + 12);
public const int MCI_MODE_OPEN = (MCI_STRING_OFFSET + 18);
public const int MCI_MODE_PAUSE = (MCI_STRING_OFFSET + 17);
public const int MCI_MODE_PLAY = (MCI_STRING_OFFSET + 14);
public const int MCI_MODE_RECORD = (MCI_STRING_OFFSET + 15);
public const int MCI_MODE_SEEK = (MCI_STRING_OFFSET + 16);
public const int MCI_MODE_STOP = (MCI_STRING_OFFSET + 13);
public const int MCI_NOTIFY = 0x1;
public const int MCI_NOTIFY_ABORTED = 0x4;
public const int MCI_NOTIFY_FAILURE = 0x8;
public const int MCI_NOTIFY_SUCCESSFUL = 0x1;
public const int MCI_NOTIFY_SUPERSEDED = 0x2;
public const int MCI_OPEN = 0x803;
public const int MCI_OPEN_ALIAS = 0x400;
public const int MCI_OPEN_ELEMENT = 0x200;
public const int MCI_OPEN_ELEMENT_ID = 0x800;
public const int MCI_OPEN_SHAREABLE = 0x100;
public const int MCI_OPEN_TYPE = 0x2000;
public const int MCI_OPEN_TYPE_ID = 0x1000;
public const int MCI_OVLY_GETDEVCAPS_CAN_FREEZE = 0x4002;
public const int MCI_OVLY_GETDEVCAPS_CAN_STRETCH = 0x4001;
public const int MCI_OVLY_GETDEVCAPS_MAX_WINDOWS = 0x4003;
public const int MCI_OVLY_INFO_TEXT = 0x10000;
public const int MCI_OVLY_OPEN_PARENT = 0x20000;
public const int MCI_OVLY_OPEN_WS = 0x10000;
public const int MCI_OVLY_PUT_DESTINATION = 0x40000;
public const int MCI_OVLY_PUT_FRAME = 0x80000;
public const int MCI_OVLY_PUT_SOURCE = 0x20000;
public const int MCI_OVLY_PUT_VIDEO = 0x100000;
public const int MCI_OVLY_RECT = 0x10000;
public const int MCI_OVLY_STATUS_HWND = 0x4001;
public const int MCI_OVLY_STATUS_STRETCH = 0x4002;
public const int MCI_OVLY_WHERE_DESTINATION = 0x40000;
public const int MCI_OVLY_WHERE_FRAME = 0x80000;
public const int MCI_OVLY_WHERE_SOURCE = 0x20000;
public const int MCI_OVLY_WHERE_VIDEO = 0x100000;
public const int MCI_OVLY_WINDOW_DEFAULT = 0x0;
public const int MCI_OVLY_WINDOW_DISABLE_STRETCH = 0x200000;
public const int MCI_OVLY_WINDOW_ENABLE_STRETCH = 0x100000;
public const int MCI_OVLY_WINDOW_HWND = 0x10000;
public const int MCI_OVLY_WINDOW_STATE = 0x40000;
public const int MCI_OVLY_WINDOW_TEXT = 0x80000;
public const int MCI_PASTE = 0x853;
public const int MCI_PAUSE = 0x809;
public const int MCI_PLAY = 0x806;
public const int MCI_PUT = 0x842;
public const int MCI_REALIZE = 0x840;
public const int MCI_RECORD = 0x80F;
public const int MCI_RECORD_INSERT = 0x100;
public const int MCI_RECORD_OVERWRITE = 0x200;
public const int MCI_RESUME = 0x855;
public const int MCI_SAVE = 0x813;
public const int MCI_SAVE_FILE = 0x100;
public const int MCI_SEEK = 0x807;
public const int MCI_SEEK_TO_END = 0x200;
public const int MCI_SEEK_TO_START = 0x100;
public const int MCI_SEQ_DIV_PPQN = (0 + MCI_SEQ_OFFSET);
public const int MCI_SEQ_DIV_SMPTE_24 = (1 + MCI_SEQ_OFFSET);
public const int MCI_SEQ_DIV_SMPTE_25 = (2 + MCI_SEQ_OFFSET);
public const int MCI_SEQ_DIV_SMPTE_30 = (4 + MCI_SEQ_OFFSET);
public const int MCI_SEQ_DIV_SMPTE_30DROP = (3 + MCI_SEQ_OFFSET);
public const int MCI_SEQ_FILE = 0x4002;
public const int MCI_SEQ_FORMAT_SONGPTR = 0x4001;
public const int MCI_SEQ_MAPPER = 65535;
public const int MCI_SEQ_MIDI = 0x4003;
public const int MCI_SEQ_NONE = 65533;
public const int MCI_SEQ_OFFSET = 1216;
public const int MCI_SEQ_SET_MASTER = 0x80000;
public const int MCI_SEQ_SET_OFFSET = 0x1000000;
public const int MCI_SEQ_SET_PORT = 0x20000;
public const int MCI_SEQ_SET_SLAVE = 0x40000;
public const int MCI_SEQ_SET_TEMPO = 0x10000;
public const int MCI_SEQ_SMPTE = 0x4004;
public const int MCI_SEQ_STATUS_DIVTYPE = 0x400A;
public const int MCI_SEQ_STATUS_MASTER = 0x4008;
public const int MCI_SEQ_STATUS_OFFSET = 0x4009;
public const int MCI_SEQ_STATUS_PORT = 0x4003;
public const int MCI_SEQ_STATUS_SLAVE = 0x4007;
public const int MCI_SEQ_STATUS_TEMPO = 0x4002;
public const int MCI_SET = 0x80D;
public const int MCI_SET_AUDIO = 0x800;
public const int MCI_SET_AUDIO_ALL = 0x4001;
public const int MCI_SET_AUDIO_LEFT = 0x4002;
public const int MCI_SET_AUDIO_RIGHT = 0x4003;
public const int MCI_SET_DOOR_CLOSED = 0x200;
public const int MCI_SET_DOOR_OPEN = 0x100;
public const int MCI_SET_OFF = 0x4000;
public const int MCI_SET_ON = 0x2000;
public const int MCI_SET_TIME_FORMAT = 0x400;
public const int MCI_SET_VIDEO = 0x1000;
public const int MCI_SOUND = 0x812;
public const int MCI_SOUND_NAME = 0x100;
public const int MCI_SPIN = 0x80C;
public const int MCI_STATUS = 0x814;
public const int MCI_STATUS_CURRENT_TRACK = 0x8;
public const int MCI_STATUS_ITEM = 0x100;
public const int MCI_STATUS_LENGTH = 0x1;
public const int MCI_STATUS_MEDIA_PRESENT = 0x5;
public const int MCI_STATUS_MODE = 0x4;
public const int MCI_STATUS_NUMBER_OF_TRACKS = 0x3;
public const int MCI_STATUS_POSITION = 0x2;
public const int MCI_STATUS_READY = 0x7;
public const int MCI_STATUS_START = 0x200;
public const int MCI_STATUS_TIME_FORMAT = 0x6;
public const int MCI_STEP = 0x80E;
public const int MCI_STOP = 0x808;
public const int MCI_STRING_OFFSET = 512;
public const int MCI_SYSINFO = 0x810;
public const int MCI_SYSINFO_INSTALLNAME = 0x800;
public const int MCI_SYSINFO_NAME = 0x400;
public const int MCI_SYSINFO_OPEN = 0x200;
public const int MCI_SYSINFO_QUANTITY = 0x100;
public const int MCI_TO = 0x8;
public const int MCI_TRACK = 0x10;
public const int MCI_UNFREEZE = 0x845;
public const int MCI_UPDATE = 0x854;
public const int MCI_USER_MESSAGES = (0x400 + MCI_FIRST);
public const int MCI_VD_ESCAPE_STRING = 0x100;
public const int MCI_VD_FORMAT_TRACK = 0x4001;
public const int MCI_VD_GETDEVCAPS_CAN_REVERSE = 0x4002;
public const int MCI_VD_GETDEVCAPS_CAV = 0x20000;
public const int MCI_VD_GETDEVCAPS_CLV = 0x10000;
public const int MCI_VD_GETDEVCAPS_FAST_RATE = 0x4003;
public const int MCI_VD_GETDEVCAPS_NORMAL_RATE = 0x4005;
public const int MCI_VD_GETDEVCAPS_SLOW_RATE = 0x4004;
public const int MCI_VD_MEDIA_CAV = (MCI_VD_OFFSET + 3);
public const int MCI_VD_MEDIA_CLV = (MCI_VD_OFFSET + 2);
public const int MCI_VD_MEDIA_OTHER = (MCI_VD_OFFSET + 4);
public const int MCI_VD_MODE_PARK = (MCI_VD_OFFSET + 1);
public const int MCI_VD_OFFSET = 1024;
public const int MCI_VD_PLAY_FAST = 0x20000;
public const int MCI_VD_PLAY_REVERSE = 0x10000;
public const int MCI_VD_PLAY_SCAN = 0x80000;
public const int MCI_VD_PLAY_SLOW = 0x100000;
public const int MCI_VD_PLAY_SPEED = 0x40000;
public const int MCI_VD_SEEK_REVERSE = 0x10000;
public const int MCI_VD_SPIN_DOWN = 0x20000;
public const int MCI_VD_SPIN_UP = 0x10000;
public const int MCI_VD_STATUS_DISC_SIZE = 0x4006;
public const int MCI_VD_STATUS_FORWARD = 0x4003;
public const int MCI_VD_STATUS_MEDIA_TYPE = 0x4004;
public const int MCI_VD_STATUS_SIDE = 0x4005;
public const int MCI_VD_STATUS_SPEED = 0x4002;
public const int MCI_VD_STEP_FRAMES = 0x10000;
public const int MCI_VD_STEP_REVERSE = 0x20000;
public const int MCI_WAIT = 0x2;
public const int MCI_WAVE_GETDEVCAPS_INPUTS = 0x4001;
public const int MCI_WAVE_GETDEVCAPS_OUTPUTS = 0x4002;
public const int MCI_WAVE_INPUT = 0x400000;
public const int MCI_WAVE_MAPPER = (MCI_WAVE_OFFSET + 1);
public const int MCI_WAVE_OFFSET = 1152;
public const int MCI_WAVE_OPEN_BUFFER = 0x10000;
public const int MCI_WAVE_OUTPUT = 0x800000;
public const int MCI_WAVE_PCM = (MCI_WAVE_OFFSET + 0);
public const int MCI_WAVE_SET_ANYINPUT = 0x4000000;
public const int MCI_WAVE_SET_ANYOUTPUT = 0x8000000;
public const int MCI_WAVE_SET_AVGBYTESPERSEC = 0x80000;
public const int MCI_WAVE_SET_BITSPERSAMPLE = 0x200000;
public const int MCI_WAVE_SET_BLOCKALIGN = 0x100000;
public const int MCI_WAVE_SET_CHANNELS = 0x20000;
public const int MCI_WAVE_SET_FORMATTAG = 0x10000;
public const int MCI_WAVE_SET_SAMPLESPERSEC = 0x40000;
public const int MCI_WAVE_STATUS_AVGBYTESPERSEC = 0x4004;
public const int MCI_WAVE_STATUS_BITSPERSAMPLE = 0x4006;
public const int MCI_WAVE_STATUS_BLOCKALIGN = 0x4005;
public const int MCI_WAVE_STATUS_CHANNELS = 0x4002;
public const int MCI_WAVE_STATUS_FORMATTAG = 0x4001;
public const int MCI_WAVE_STATUS_LEVEL = 0x4007;
public const int MCI_WAVE_STATUS_SAMPLESPERSEC = 0x4003;
public const int MCI_WHERE = 0x843;
public const int MCI_WINDOW = 0x841;
public const int MEVT_F_CALLBACK = 0x40000000;
public const int MEVT_F_LONG = unchecked((int)0x80000000);
public const int MEVT_F_SHORT = 0x0;
public const int MHDR_DONE = 0x1;
public const int MHDR_INQUEUE = 0x4;
public const int MHDR_PREPARED = 0x2;
public const int MHDR_VALID = 0x7;
public const int MIDICAPS_CACHE = 0x4;
public const int MIDICAPS_LRVOLUME = 0x2;
public const int MIDICAPS_STREAM = 0x8;
public const int MIDICAPS_VOLUME = 0x1;
public const int MIDIERR_BASE = 64;
public const int MIDIERR_INVALIDSETUP = (MIDIERR_BASE + 5);
public const int MIDIERR_LASTERROR = (MIDIERR_BASE + 5);
public const int MIDIERR_NODEVICE = (MIDIERR_BASE + 4);
public const int MIDIERR_NOMAP = (MIDIERR_BASE + 2);
public const int MIDIERR_NOTREADY = (MIDIERR_BASE + 3);
public const int MIDIERR_STILLPLAYING = (MIDIERR_BASE + 1);
public const int MIDIERR_UNPREPARED = (MIDIERR_BASE + 0);
public const int MIDIMAPPER = (-1);
public const int MIDIPROP_GET = 0x40000000;
public const int MIDIPROP_SET = unchecked((int)0x80000000);
public const int MIDIPROP_TEMPO = 0x2;
public const int MIDIPROP_TIMEDIV = 0x1;
public const int MIDISTRM_ERROR = -2;
public const int MIDI_CACHE_ALL = 1;
public const int MIDI_CACHE_BESTFIT = 2;
public const int MIDI_CACHE_QUERY = 3;
public const int MIDI_CACHE_VALID = (MIDI_CACHE_ALL | MIDI_CACHE_BESTFIT | MIDI_CACHE_QUERY | MIDI_UNCACHE);
public const int MIDI_IO_STATUS = 0x20;
public const int MIDI_MAPPER = -1;
public const int MIDI_UNCACHE = 4;
public const int MIM_CLOSE = MM_MIM_CLOSE;
public const int MIM_DATA = MM_MIM_DATA;
public const int MIM_ERROR = MM_MIM_ERROR;
public const int MIM_LONGDATA = MM_MIM_LONGDATA;
public const int MIM_LONGERROR = MM_MIM_LONGERROR;
public const int MIM_MOREDATA = MM_MIM_MOREDATA;
public const int MIM_OPEN = MM_MIM_OPEN;
public const int MIXERCONTROL_CONTROLF_DISABLED = unchecked((int)0x80000000);
public const int MIXERCONTROL_CONTROLF_MULTIPLE = 0x2;
public const int MIXERCONTROL_CONTROLF_UNIFORM = 0x1;
public const int MIXERCONTROL_CONTROLTYPE_BASS = (MIXERCONTROL_CONTROLTYPE_FADER + 2);
public const int MIXERCONTROL_CONTROLTYPE_BOOLEAN = (MIXERCONTROL_CT_CLASS_SWITCH | MIXERCONTROL_CT_SC_SWITCH_BOOLEAN | MIXERCONTROL_CT_UNITS_BOOLEAN);
public const int MIXERCONTROL_CONTROLTYPE_BOOLEANMETER = (MIXERCONTROL_CT_CLASS_METER | MIXERCONTROL_CT_SC_METER_POLLED | MIXERCONTROL_CT_UNITS_BOOLEAN);
public const int MIXERCONTROL_CONTROLTYPE_BUTTON = (MIXERCONTROL_CT_CLASS_SWITCH | MIXERCONTROL_CT_SC_SWITCH_BUTTON | MIXERCONTROL_CT_UNITS_BOOLEAN);
public const int MIXERCONTROL_CONTROLTYPE_CUSTOM = (MIXERCONTROL_CT_CLASS_CUSTOM | MIXERCONTROL_CT_UNITS_CUSTOM);
public const int MIXERCONTROL_CONTROLTYPE_DECIBELS = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_DECIBELS);
public const int MIXERCONTROL_CONTROLTYPE_EQUALIZER = (MIXERCONTROL_CONTROLTYPE_FADER + 4);
public const int MIXERCONTROL_CONTROLTYPE_FADER = (MIXERCONTROL_CT_CLASS_FADER | MIXERCONTROL_CT_UNITS_UNSIGNED);
public const int MIXERCONTROL_CONTROLTYPE_LOUDNESS = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 4);
public const int MIXERCONTROL_CONTROLTYPE_MICROTIME = (MIXERCONTROL_CT_CLASS_TIME | MIXERCONTROL_CT_SC_TIME_MICROSECS | MIXERCONTROL_CT_UNITS_UNSIGNED);
public const int MIXERCONTROL_CONTROLTYPE_MILLITIME = (MIXERCONTROL_CT_CLASS_TIME | MIXERCONTROL_CT_SC_TIME_MILLISECS | MIXERCONTROL_CT_UNITS_UNSIGNED);
public const int MIXERCONTROL_CONTROLTYPE_MIXER = (MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT + 1);
public const int MIXERCONTROL_CONTROLTYPE_MONO = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 3);
public const int MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT = (MIXERCONTROL_CT_CLASS_LIST | MIXERCONTROL_CT_SC_LIST_MULTIPLE | MIXERCONTROL_CT_UNITS_BOOLEAN);
public const int MIXERCONTROL_CONTROLTYPE_MUTE = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 2);
public const int MIXERCONTROL_CONTROLTYPE_MUX = (MIXERCONTROL_CONTROLTYPE_SINGLESELECT + 1);
public const int MIXERCONTROL_CONTROLTYPE_ONOFF = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 1);
public const int MIXERCONTROL_CONTROLTYPE_PAN = (MIXERCONTROL_CONTROLTYPE_SLIDER + 1);
public const int MIXERCONTROL_CONTROLTYPE_PEAKMETER = (MIXERCONTROL_CONTROLTYPE_SIGNEDMETER + 1);
public const int MIXERCONTROL_CONTROLTYPE_PERCENT = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_PERCENT);
public const int MIXERCONTROL_CONTROLTYPE_QSOUNDPAN = (MIXERCONTROL_CONTROLTYPE_SLIDER + 2);
public const int MIXERCONTROL_CONTROLTYPE_SIGNED = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_SIGNED);
public const int MIXERCONTROL_CONTROLTYPE_SIGNEDMETER = (MIXERCONTROL_CT_CLASS_METER | MIXERCONTROL_CT_SC_METER_POLLED | MIXERCONTROL_CT_UNITS_SIGNED);
public const int MIXERCONTROL_CONTROLTYPE_SINGLESELECT = (MIXERCONTROL_CT_CLASS_LIST | MIXERCONTROL_CT_SC_LIST_SINGLE | MIXERCONTROL_CT_UNITS_BOOLEAN);
public const int MIXERCONTROL_CONTROLTYPE_SLIDER = (MIXERCONTROL_CT_CLASS_SLIDER | MIXERCONTROL_CT_UNITS_SIGNED);
public const int MIXERCONTROL_CONTROLTYPE_STEREOENH = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 5);
public const int MIXERCONTROL_CONTROLTYPE_TREBLE = (MIXERCONTROL_CONTROLTYPE_FADER + 3);
public const int MIXERCONTROL_CONTROLTYPE_UNSIGNED = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_UNSIGNED);
public const int MIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER = (MIXERCONTROL_CT_CLASS_METER | MIXERCONTROL_CT_SC_METER_POLLED | MIXERCONTROL_CT_UNITS_UNSIGNED);
public const int MIXERCONTROL_CONTROLTYPE_VOLUME = (MIXERCONTROL_CONTROLTYPE_FADER + 1);
public const int MIXERCONTROL_CT_CLASS_CUSTOM = 0x0;
public const int MIXERCONTROL_CT_CLASS_FADER = 0x50000000;
public const int MIXERCONTROL_CT_CLASS_LIST = 0x70000000;
public const int MIXERCONTROL_CT_CLASS_MASK = unchecked((int)0xF0000000);
public const int MIXERCONTROL_CT_CLASS_METER = 0x10000000;
public const int MIXERCONTROL_CT_CLASS_NUMBER = 0x30000000;
public const int MIXERCONTROL_CT_CLASS_SLIDER = 0x40000000;
public const int MIXERCONTROL_CT_CLASS_SWITCH = 0x20000000;
public const int MIXERCONTROL_CT_CLASS_TIME = 0x60000000;
public const int MIXERCONTROL_CT_SC_LIST_MULTIPLE = 0x1000000;
public const int MIXERCONTROL_CT_SC_LIST_SINGLE = 0x0;
public const int MIXERCONTROL_CT_SC_METER_POLLED = 0x0;
public const int MIXERCONTROL_CT_SC_SWITCH_BOOLEAN = 0x0;
public const int MIXERCONTROL_CT_SC_SWITCH_BUTTON = 0x1000000;
public const int MIXERCONTROL_CT_SC_TIME_MICROSECS = 0x0;
public const int MIXERCONTROL_CT_SC_TIME_MILLISECS = 0x1000000;
public const int MIXERCONTROL_CT_SUBCLASS_MASK = 0xF000000;
public const int MIXERCONTROL_CT_UNITS_BOOLEAN = 0x10000;
public const int MIXERCONTROL_CT_UNITS_CUSTOM = 0x0;
public const int MIXERCONTROL_CT_UNITS_DECIBELS = 0x40000;
public const int MIXERCONTROL_CT_UNITS_MASK = 0xFF0000;
public const int MIXERCONTROL_CT_UNITS_PERCENT = 0x50000;
public const int MIXERCONTROL_CT_UNITS_SIGNED = 0x20000;
public const int MIXERCONTROL_CT_UNITS_UNSIGNED = 0x30000;
public const int MIXERLINE_COMPONENTTYPE_DST_DIGITAL = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 1);
public const int MIXERLINE_COMPONENTTYPE_DST_FIRST = 0x0;
public const int MIXERLINE_COMPONENTTYPE_DST_HEADPHONES = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 5);
public const int MIXERLINE_COMPONENTTYPE_DST_LAST = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 8);
public const int MIXERLINE_COMPONENTTYPE_DST_LINE = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 2);
public const int MIXERLINE_COMPONENTTYPE_DST_MONITOR = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 3);
public const int MIXERLINE_COMPONENTTYPE_DST_SPEAKERS = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 4);
public const int MIXERLINE_COMPONENTTYPE_DST_TELEPHONE = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 6);
public const int MIXERLINE_COMPONENTTYPE_DST_UNDEFINED = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 0);
public const int MIXERLINE_COMPONENTTYPE_DST_VOICEIN = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 8);
public const int MIXERLINE_COMPONENTTYPE_DST_WAVEIN = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 7);
public const int MIXERLINE_COMPONENTTYPE_SRC_ANALOG = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 10);
public const int MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 9);
public const int MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 5);
public const int MIXERLINE_COMPONENTTYPE_SRC_DIGITAL = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 1);
public const int MIXERLINE_COMPONENTTYPE_SRC_FIRST = 0x1000;
public const int MIXERLINE_COMPONENTTYPE_SRC_LAST = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 10);
public const int MIXERLINE_COMPONENTTYPE_SRC_LINE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 2);
public const int MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 3);
public const int MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 7);
public const int MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 4);
public const int MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 6);
public const int MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 0);
public const int MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 8);
public const int MIXERLINE_LINEF_ACTIVE = 0x1;
public const int MIXERLINE_LINEF_DISCONNECTED = 0x8000;
public const int MIXERLINE_LINEF_SOURCE = unchecked((int)0x80000000);
public const int MIXERLINE_TARGETTYPE_AUX = 5;
public const int MIXERLINE_TARGETTYPE_MIDIIN = 4;
public const int MIXERLINE_TARGETTYPE_MIDIOUT = 3;
public const int MIXERLINE_TARGETTYPE_UNDEFINED = 0;
public const int MIXERLINE_TARGETTYPE_WAVEIN = 2;
public const int MIXERLINE_TARGETTYPE_WAVEOUT = 1;
public const int MIXERR_BASE = 1024;
public const int MIXERR_INVALCONTROL = (MIXERR_BASE + 1);
public const int MIXERR_INVALLINE = (MIXERR_BASE + 0);
public const int MIXERR_INVALVALUE = (MIXERR_BASE + 2);
public const int MIXERR_LASTERROR = (MIXERR_BASE + 2);
public const int MIXER_GETCONTROLDETAILSF_LISTTEXT = 0x1;
public const int MIXER_GETCONTROLDETAILSF_QUERYMASK = 0xF;
public const int MIXER_GETCONTROLDETAILSF_VALUE = 0x0;
public const int MIXER_GETLINECONTROLSF_ALL = 0x0;
public const int MIXER_GETLINECONTROLSF_ONEBYID = 0x1;
public const int MIXER_GETLINECONTROLSF_ONEBYTYPE = 0x2;
public const int MIXER_GETLINECONTROLSF_QUERYMASK = 0xF;
public const int MIXER_GETLINEINFOF_COMPONENTTYPE = 0x3;
public const int MIXER_GETLINEINFOF_DESTINATION = 0x0;
public const int MIXER_GETLINEINFOF_LINEID = 0x2;
public const int MIXER_GETLINEINFOF_QUERYMASK = 0xF;
public const int MIXER_GETLINEINFOF_SOURCE = 0x1;
public const int MIXER_GETLINEINFOF_TARGETTYPE = 0x4;
public const int MIXER_LONG_NAME_CHARS = 64;
public const int MIXER_OBJECTF_AUX = 0x50000000;
public const int MIXER_OBJECTF_HANDLE = unchecked((int)0x80000000);
public const int MIXER_OBJECTF_HMIDIIN = (MIXER_OBJECTF_HANDLE | MIXER_OBJECTF_MIDIIN);
public const int MIXER_OBJECTF_HMIDIOUT = (MIXER_OBJECTF_HANDLE | MIXER_OBJECTF_MIDIOUT);
public const int MIXER_OBJECTF_HMIXER = (MIXER_OBJECTF_HANDLE | MIXER_OBJECTF_MIXER);
public const int MIXER_OBJECTF_HWAVEIN = (MIXER_OBJECTF_HANDLE | MIXER_OBJECTF_WAVEIN);
public const int MIXER_OBJECTF_HWAVEOUT = (MIXER_OBJECTF_HANDLE | MIXER_OBJECTF_WAVEOUT);
public const int MIXER_OBJECTF_MIDIIN = 0x40000000;
public const int MIXER_OBJECTF_MIDIOUT = 0x30000000;
public const int MIXER_OBJECTF_MIXER = 0x0;
public const int MIXER_OBJECTF_WAVEIN = 0x20000000;
public const int MIXER_OBJECTF_WAVEOUT = 0x10000000;
public const int MIXER_SETCONTROLDETAILSF_CUSTOM = 0x1;
public const int MIXER_SETCONTROLDETAILSF_QUERYMASK = 0xF;
public const int MIXER_SETCONTROLDETAILSF_VALUE = 0x0;
public const int MIXER_SHORT_NAME_CHARS = 16;
public const int MMIOERR_BASE = 256;
public const int MMIOERR_CANNOTCLOSE = (MMIOERR_BASE + 4);
public const int MMIOERR_CANNOTEXPAND = (MMIOERR_BASE + 8);
public const int MMIOERR_CANNOTOPEN = (MMIOERR_BASE + 3);
public const int MMIOERR_CANNOTREAD = (MMIOERR_BASE + 5);
public const int MMIOERR_CANNOTSEEK = (MMIOERR_BASE + 7);
public const int MMIOERR_CANNOTWRITE = (MMIOERR_BASE + 6);
public const int MMIOERR_CHUNKNOTFOUND = (MMIOERR_BASE + 9);
public const int MMIOERR_FILENOTFOUND = (MMIOERR_BASE + 1);
public const int MMIOERR_OUTOFMEMORY = (MMIOERR_BASE + 2);
public const int MMIOERR_UNBUFFERED = (MMIOERR_BASE + 10);
public const int MMIOM_CLOSE = 4;
public const int MMIOM_OPEN = 3;
public const int MMIOM_READ = MMIO_READ;
public const int MMIOM_RENAME = 6;
public const int MMIOM_SEEK = 2;
public const int MMIOM_USER = 0x8000;
public const int MMIOM_WRITE = MMIO_WRITE;
public const int MMIOM_WRITEFLUSH = 5;
public const int MMIO_ALLOCBUF = 0x10000;
public const int MMIO_COMPAT = 0x0;
public const int MMIO_CREATE = 0x1000;
public const int MMIO_CREATELIST = 0x40;
public const int MMIO_CREATERIFF = 0x20;
public const int MMIO_DEFAULTBUFFER = 8192;
public const int MMIO_DELETE = 0x200;
public const int MMIO_DENYNONE = 0x40;
public const int MMIO_DENYREAD = 0x30;
public const int MMIO_DENYWRITE = 0x20;
public const int MMIO_DIRTY = 0x10000000;
public const int MMIO_EMPTYBUF = 0x10;
public const int MMIO_EXCLUSIVE = 0x10;
public const int MMIO_EXIST = 0x4000;
public const int MMIO_FHOPEN = 0x10;
public const int MMIO_FINDCHUNK = 0x10;
public const int MMIO_FINDLIST = 0x40;
public const int MMIO_FINDPROC = 0x40000;
public const int MMIO_FINDRIFF = 0x20;
public const int MMIO_GETTEMP = 0x20000;
public const int MMIO_INSTALLPROC = 0x10000;
public const int MMIO_OPEN_VALID = 0x3FFFF;
public const int MMIO_PARSE = 0x100;
public const int MMIO_PUBLICPROC = 0x10000000;
public const int MMIO_READ = 0x0;
public const int MMIO_READWRITE = 0x2;
public const int MMIO_REMOVEPROC = 0x20000;
public const int MMIO_RWMODE = 0x3;
public const int MMIO_SHAREMODE = 0x70;
public const int MMIO_TOUPPER = 0x10;
public const int MMIO_UNICODEPROC = 0x1000000;
public const int MMIO_VALIDPROC = 0x11070000;
public const int MMIO_WRITE = 0x1;
public const int MMSYSERR_ALLOCATED = (MMSYSERR_BASE + 4);
public const int MMSYSERR_BADDEVICEID = (MMSYSERR_BASE + 2);
public const int MMSYSERR_BADERRNUM = (MMSYSERR_BASE + 9);
public const int MMSYSERR_BASE = 0;
public const int MMSYSERR_ERROR = (MMSYSERR_BASE + 1);
public const int MMSYSERR_HANDLEBUSY = (MMSYSERR_BASE + 12);
public const int MMSYSERR_INVALFLAG = (MMSYSERR_BASE + 10);
public const int MMSYSERR_INVALHANDLE = (MMSYSERR_BASE + 5);
public const int MMSYSERR_INVALIDALIAS = (MMSYSERR_BASE + 13);
public const int MMSYSERR_INVALPARAM = (MMSYSERR_BASE + 11);
public const int MMSYSERR_LASTERROR = (MMSYSERR_BASE + 13);
public const int MMSYSERR_NODRIVER = (MMSYSERR_BASE + 6);
public const int MMSYSERR_NOERROR = 0;
public const int MMSYSERR_NOMEM = (MMSYSERR_BASE + 7);
public const int MMSYSERR_NOTENABLED = (MMSYSERR_BASE + 3);
public const int MMSYSERR_NOTSUPPORTED = (MMSYSERR_BASE + 8);
public const int MM_ADLIB = 9;
public const int MM_JOY1BUTTONDOWN = 0x3B5;
public const int MM_JOY1BUTTONUP = 0x3B7;
public const int MM_JOY1MOVE = 0x3A0;
public const int MM_JOY1ZMOVE = 0x3A2;
public const int MM_JOY2BUTTONDOWN = 0x3B6;
public const int MM_JOY2BUTTONUP = 0x3B8;
public const int MM_JOY2MOVE = 0x3A1;
public const int MM_JOY2ZMOVE = 0x3A3;
public const int MM_MCINOTIFY = 0x3B9;
public const int MM_MCISIGNAL = 0x3CB;
public const int MM_MCISYSTEM_STRING = 0x3CA;
public const int MM_MICROSOFT = 1;
public const int MM_MIDI_MAPPER = 1;
public const int MM_MIM_CLOSE = 0x3C2;
public const int MM_MIM_DATA = 0x3C3;
public const int MM_MIM_ERROR = 0x3C5;
public const int MM_MIM_LONGDATA = 0x3C4;
public const int MM_MIM_LONGERROR = 0x3C6;
public const int MM_MIM_MOREDATA = 0x3CC;
public const int MM_MIM_OPEN = 0x3C1;
public const int MM_MOM_CLOSE = 0x3C8;
public const int MM_MOM_DONE = 0x3C9;
public const int MM_MOM_OPEN = 0x3C7;
public const int MM_MOM_POSITIONCB = 0x3CA;
public const int MM_MPU401_MIDIIN = 11;
public const int MM_MPU401_MIDIOUT = 10;
public const int MM_PC_JOYSTICK = 12;
public const int MM_SNDBLST_MIDIIN = 4;
public const int MM_SNDBLST_MIDIOUT = 3;
public const int MM_SNDBLST_SYNTH = 5;
public const int MM_SNDBLST_WAVEIN = 7;
public const int MM_SNDBLST_WAVEOUT = 6;
public const int MM_WAVE_MAPPER = 2;
public const int MM_WIM_CLOSE = 0x3BF;
public const int MM_WIM_DATA = 0x3C0;
public const int MM_WIM_OPEN = 0x3BE;
public const int MM_WOM_CLOSE = 0x3BC;
public const int MM_WOM_DONE = 0x3BD;
public const int MM_WOM_OPEN = 0x3BB;
public const int MOD_FMSYNTH = 4;
public const int MOD_MAPPER = 5;
public const int MOD_MIDIPORT = 1;
public const int MOD_SQSYNTH = 3;
public const int MOD_SYNTH = 2;
public const int MOM_CLOSE = MM_MOM_CLOSE;
public const int MOM_DONE = MM_MOM_DONE;
public const int MOM_OPEN = MM_MOM_OPEN;
public const int MOM_POSITIONCB = MM_MOM_POSITIONCB;
public const int NEWTRANSPARENT = 3;
public const int QUERYROPSUPPORT = 40;
public const int SEEK_CUR = 1;
public const int SEEK_END = 2;
public const int SEEK_SET = 0;
public const int SELECTDIB = 41;
public const int SND_ALIAS = 0x10000;
public const int SND_ALIAS_ID = 0x110000;
public const int SND_ALIAS_START = 0;
public const int SND_APPLICATION = 0x80;
public const int SND_ASYNC = 0x1;
public const int SND_FILENAME = 0x20000;
public const int SND_LOOP = 0x8;
public const int SND_MEMORY = 0x4;
public const int SND_NODEFAULT = 0x2;
public const int SND_NOSTOP = 0x10;
public const int SND_NOWAIT = 0x2000;
public const int SND_PURGE = 0x40;
public const int SND_RESERVED = unchecked((int)0xFF000000);
public const int SND_RESOURCE = 0x40004;
public const int SND_SYNC = 0x0;
public const int SND_TYPE_MASK = 0x170007;
public const int SND_VALID = 0x1F;
public const int SND_VALIDFLAGS = 0x17201F;
public const int TIMERR_BASE = 96;
public const int TIMERR_NOCANDO = (TIMERR_BASE + 1);
public const int TIMERR_NOERROR = (0);
public const int TIMERR_STRUCT = (TIMERR_BASE + 33);
public const int TIME_BYTES = 0x4;
public const int TIME_MIDI = 0x10;
public const int TIME_MS = 0x1;
public const int TIME_ONESHOT = 0;
public const int TIME_PERIODIC = 1;
public const int TIME_SAMPLES = 0x2;
public const int TIME_SMPTE = 0x8;
public const int WAVECAPS_LRVOLUME = 0x8;
public const int WAVECAPS_PITCH = 0x1;
public const int WAVECAPS_PLAYBACKRATE = 0x2;
public const int WAVECAPS_SYNC = 0x10;
public const int WAVECAPS_VOLUME = 0x4;
public const int WAVERR_BADFORMAT = (WAVERR_BASE + 0);
public const int WAVERR_BASE = 32;
public const int WAVERR_LASTERROR = (WAVERR_BASE + 3);
public const int WAVERR_STILLPLAYING = (WAVERR_BASE + 1);
public const int WAVERR_SYNC = (WAVERR_BASE + 3);
public const int WAVERR_UNPREPARED = (WAVERR_BASE + 2);
public const int WAVE_ALLOWSYNC = 0x2;
public const int WAVE_FORMAT_1M08 = 0x1;
public const int WAVE_FORMAT_1M16 = 0x4;
public const int WAVE_FORMAT_1S08 = 0x2;
public const int WAVE_FORMAT_1S16 = 0x8;
public const int WAVE_FORMAT_2M08 = 0x10;
public const int WAVE_FORMAT_2M16 = 0x40;
public const int WAVE_FORMAT_2S08 = 0x20;
public const int WAVE_FORMAT_2S16 = 0x80;
public const int WAVE_FORMAT_4M08 = 0x100;
public const int WAVE_FORMAT_4M16 = 0x400;
public const int WAVE_FORMAT_4S08 = 0x200;
public const int WAVE_FORMAT_4S16 = 0x800;
public const int WAVE_FORMAT_DIRECT = 0x8;
public const int WAVE_FORMAT_DIRECT_QUERY = (WAVE_FORMAT_QUERY | WAVE_FORMAT_DIRECT);
public const int WAVE_FORMAT_PCM = 1;
public const int WAVE_FORMAT_QUERY = 0x1;
public const int WAVE_INVALIDFORMAT = 0x0;
public const int WAVE_MAPPED = 0x4;
public const int WAVE_MAPPER = -1;
public const int WAVE_VALID = 0x3;
public const int WHDR_BEGINLOOP = 0x4;
public const int WHDR_DONE = 0x1;
public const int WHDR_ENDLOOP = 0x8;
public const int WHDR_INQUEUE = 0x10;
public const int WHDR_PREPARED = 0x2;
public const int WHDR_VALID = 0x1F;
public const int WIM_CLOSE = MM_WIM_CLOSE;
public const int WIM_DATA = MM_WIM_DATA;
public const int WIM_OPEN = MM_WIM_OPEN;
public const int WOM_CLOSE = MM_WOM_CLOSE;
public const int WOM_DONE = MM_WOM_DONE;
public const int WOM_OPEN = MM_WOM_OPEN;
public const string CFSEPCHAR = "+";
}
}


using System;
using System.Runtime.InteropServices;
using HANDLE = System.IntPtr;
using HWND = System.IntPtr;
using HDC = System.IntPtr;
namespace Win32
{
public struct XFORM
{
public double eM11;
public double
eM12;
public double eM21;
public double
eM22;
public double eDx;
public double
eDy;
}
public struct BITMAP
{
public
int bmType;
public int bmWidth;
public int
bmHeight;
public int bmWidthBytes;
public short
bmPlanes;
public short bmBitsPixel;
public int
bmBits;
}
public struct RGBTRIPLE
{
public byte rgbtBlue;
public byte
rgbtGreen;
public byte rgbtRed;
}
public struct
RGBQUAD
{
public byte rgbBlue;
public
byte rgbGreen;
public byte rgbRed;
public byte
rgbReserved;
}
public struct BITMAPCOREHEADER
{
public int bcSize;
public short
bcWidth;
public short bcHeight;
public short
bcPlanes;
public short bcBitCount;
}
public
struct BITMAPINFOHEADER
{
public int
biSize;
public int biWidth;
public int
biHeight;
public short biPlanes;
public short
biBitCount;
public int biCompression;
public int
biSizeImage;
public int biXPelsPerMeter;
public
int biYPelsPerMeter;
public int biClrUsed;
public
int biClrImportant;
}
public struct BITMAPINFO
{
public BITMAPINFOHEADER
bmiHeader;
public RGBQUAD bmiColors;
}
public
struct BITMAPCOREINFO
{
public BITMAPCOREHEADER
bmciHeader;
public RGBTRIPLE
bmciColors;
}
public struct BITMAPFILEHEADER
{
public short bfType;
public int
bfSize;
public short bfReserved1;
public short
bfReserved2;
public int bfOffBits;
}
public
struct HANDLETABLE
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public int objectHandle;
}
public struct METARECORD
{
public int rdSize;
public short
rdFunction;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public short rdParm;
}
public struct METAFILEPICT
{
public int mm;
public int
xExt;
public int yExt;
public HANDLE
hMF;
}
public struct METAHEADER
{
public short mtType;
public short
mtHeaderSize;
public short mtVersion;
public int
mtSize;
public short mtNoObjects;
public int
mtMaxRecord;
public short
mtNoParameters;
}
public struct ENHMETARECORD
{
public int iType;
public int
nSize;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)] public
int dParm;
}
public struct ENHMETAHEADER
{
public int iType;
public int
nSize;
public RECT rclBounds;
public RECT
rclFrame;
public int dSignature;
public int
nVersion;
public int nBytes;
public int
nRecords;
public short nHandles;
public short
sReserved;
public int nDescription;
public int
offDescription;
public int nPalEntries;
public
SIZE szlDevice;
public SIZE
szlMillimeters;
}
public struct TEXTMETRIC
{
public int tmHeight;
public int
tmAscent;
public int tmDescent;
public int
tmInternalLeading;
public int
tmExternalLeading;
public int
tmAveCharWidth;
public int tmMaxCharWidth;
public
int tmWeight;
public int tmOverhang;
public int
tmDigitizedAspectX;
public int
tmDigitizedAspectY;
public byte
tmFirstChar;
public byte tmLastChar;
public byte
tmDefaultChar;
public byte tmBreakChar;
public
byte tmItalic;
public byte tmUnderlined;
public
byte tmStruckOut;
public byte
tmPitchAndFamily;
public byte
tmCharSet;
}
public struct NEWTEXTMETRIC
{
public int tmHeight;
public int
tmAscent;
public int tmDescent;
public int
tmInternalLeading;
public int
tmExternalLeading;
public int
tmAveCharWidth;
public int tmMaxCharWidth;
public
int tmWeight;
public int tmOverhang;
public int
tmDigitizedAspectX;
public int
tmDigitizedAspectY;
public byte
tmFirstChar;
public byte tmLastChar;
public byte
tmDefaultChar;
public byte tmBreakChar;
public
byte tmItalic;
public byte tmUnderlined;
public
byte tmStruckOut;
public byte
tmPitchAndFamily;
public byte tmCharSet;
public
int ntmFlags;
public int ntmSizeEM;
public int
ntmCellHeight;
public int ntmAveWidth;
}
public
struct PELARRAY
{
public int
paXCount;
public int paYCount;
public int
paXExt;
public int paYExt;
public short
paRGBs;
}
public struct LOGBRUSH
{
public int lbStyle;
public int
lbColor;
public int lbHatch;
}
public struct
LOGPEN
{
public int lopnStyle;
public
POINT lopnWidth;
public int lopnColor;
}
public
struct EXTLOGPEN
{
public int
elpPenStyle;
public int elpWidth;
public int
elpBrushStyle;
public int elpColor;
public int
elpHatch;
public int
elpNumEntries;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public int elpStyleEntry;
}
public struct PALETTEENTRY
{
public byte peRed;
public byte
peGreen;
public byte peBlue;
public byte
peFlags;
}
public struct LOGPALETTE
{
public short palVersion;
public short
palNumEntries;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=1)]
public PALETTEENTRY palPalEntry;
}
public struct LOGFONT
{
public int lfHeight;
public int
lfWidth;
public int lfEscapement;
public int
lfOrientation;
public int lfWeight;
public byte
lfItalic;
public byte lfUnderline;
public byte
lfStrikeOut;
public byte lfCharSet;
public byte
lfOutPrecision;
public byte
lfClipPrecision;
public byte lfQuality;
public
byte lfPitchAndFamily;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=GDI.LF_FACESIZE)] public byte[] lfFaceName;
}
public struct NONCLIENTMETRICS
{
public int cbSize;
public int
iBorderWidth;
public int iScrollWidth;
public int
iScrollHeight;
public int iCaptionWidth;
public
int iCaptionHeight;
public LOGFONT
lfCaptionFont;
public int iSMCaptionWidth;
public
int iSMCaptionHeight;
public LOGFONT
lfSMCaptionFont;
public int iMenuWidth;
public int
iMenuHeight;
public LOGFONT lfMenuFont;
public
LOGFONT lfStatusFont;
public LOGFONT
lfMessageFont;
}
public struct ENUMLOGFONT
{
public LOGFONT
elfLogFont;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=GDI.LF_FULLFACESIZE)] public byte[] elfFullName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=GDI.LF_FACESIZE)]
public byte[] elfStyle;
}
public struct PANOSE
{
public int ulculture;
public byte
bFamilyType;
public byte bSerifStyle;
public byte
bWeight;
public byte bProportion;
public byte
bContrast;
public byte bStrokeVariation;
public
byte bArmStyle;
public byte bLetterform;
public
byte bMidline;
public byte bXHeight;
}
public
struct EXTLOGFONT
{
public LOGFONT
elfLogFont;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=GDI.LF_FULLFACESIZE)] public byte[] elfFullName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=GDI.LF_FACESIZE)]
public byte[] elfStyle;
public int
elfVersion;
public int elfStyleSize;
public int
elfMatch;
public int
elfReserved;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=GDI.ELF_VENDOR_SIZE)] public byte[] elfVendorId;
public int elfCulture;
public PANOSE
elfPanose;
}
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
public string dmDeviceName;
public short
dmSpecVersion;
public short
dmDriverVersion;
public short dmSize;
public short
dmDriverExtra;
public int dmFields;
public short
dmOrientation;
public short dmPaperSize;
public
short dmPaperLength;
public short
dmPaperWidth;
public short dmScale;
public short
dmCopies;
public short dmDefaultSource;
public
short dmPrintQuality;
public short dmColor;
public
short dmDuplex;
public short dmYResolution;
public
short dmTTOption;
public short
dmCollate;
[MarshalAs(UnmanagedType.ByValTStr,
SizeConst=GDI.CCHFORMNAME)] public string dmFormName;
public
short dmUnusedPadding;
public int
dmBitsPerPel;
public int dmPelsWidth;
public int
dmPelsHeight;
public int dmDisplayFlags;
public
int dmDisplayFrequency;
}
public struct RGNDATAHEADER
{
public int dwSize;
public int
iType;
public int nCount;
public int
nRgnSize;
public RECT rcBound;
}
public struct
RGNDATA
{
public RGNDATAHEADER
rdh;
public byte Buffer;
}
public struct ABC
{
public int abcA;
public int
abcB;
public int abcC;
}
public struct ABCFLOAT
{
public double abcfA;
public double
abcfB;
public double abcfC;
}
public struct
OUTLINETEXTMETRIC
{
public int
otmSize;
public TEXTMETRIC otmTextMetrics;
public
byte otmFiller;
public PANOSE
otmPanoseNumber;
public int otmfsSelection;
public
int otmfsType;
public int
otmsCharSlopeRise;
public int
otmsCharSlopeRun;
public int
otmItalicAngle;
public int otmEMSquare;
public int
otmAscent;
public int otmDescent;
public int
otmLineGap;
public int otmsCapEmHeight;
public int
otmsXHeight;
public RECT otmrcFontBox;
public int
otmMacAscent;
public int otmMacDescent;
public int
otmMacLineGap;
public int otmusMinimumPPEM;
public
POINT otmptSubscriptSize;
public POINT
otmptSubscriptOffset;
public POINT
otmptSuperscriptSize;
public POINT
otmptSuperscriptOffset;
public int
otmsStrikeoutSize;
public int
otmsStrikeoutPosition;
public int
otmsUnderscorePosition;
public int
otmsUnderscoreSize;
public string
otmpFamilyName;
public string otmpFaceName;
public
string otmpStyleName;
public string
otmpFullName;
}
public struct POLYTEXT
{
public int x;
public int
y;
public int n;
public string
lpStr;
public int uiFlags;
public RECT
rcl;
public int pdx;
}
public struct FIXED
{
public short fract;
public short
Value;
}
public struct MAT2
{
public
FIXED eM11;
public FIXED eM12;
public FIXED
eM21;
public FIXED eM22;
}
public struct
GLYPHMETRICS
{
public int
gmBlackBoxX;
public int gmBlackBoxY;
public POINT
gmptGlyphOrigin;
public short gmCellIncX;
public
short gmCellIncY;
}
public struct POINTFX
{
public FIXED x;
public FIXED
y;
}
public struct TTPOLYCURVE
{
public short wType;
public short
cpfx;
public POINTFX apfx;
}
public struct
TTPOLYGONHEADER
{
public int cb;
public
int dwType;
public POINTFX pfxStart;
}
public
struct RASTERIZER_STATUS
{
public short
nSize;
public short wFlags;
public short
nLanguageID;
}
public struct COLORADJUSTMENT
{
public short caSize;
public short
caFlags;
public short caIlluminantIndex;
public
short caRedGamma;
public short
caGreenGamma;
public short caBlueGamma;
public
short caReferenceBlack;
public short
caReferenceWhite;
public short caContrast;
public
short caBrightness;
public short
caColorfulness;
public short
caRedGreenTint;
}
public struct DOCINFO
{
public int cbSize;
public string
lpszDocName;
public string lpszOutput;
}
public
struct KERNINGPAIR
{
public short
wFirst;
public short wSecond;
public int
iKernAmount;
}
public struct BITMAPV4HEADER
{
public int bV4Size;
public int
bV4Width;
public int bV4Height;
public short
bV4Planes;
public short bV4BitCount;
public int
bV4V4Compression;
public int bV4SizeImage;
public
int bV4XPelsPerMeter;
public int
bV4YPelsPerMeter;
public int bV4ClrUsed;
public
int bV4ClrImportant;
public int bV4RedMask;
public
int bV4GreenMask;
public int bV4BlueMask;
public
int bV4AlphaMask;
public int bV4CSType;
public int
bV4Endpoints;
public int bV4GammaRed;
public int
bV4GammaGreen;
public int
bV4GammaBlue;
}
public struct FONTSIGNATURE
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public int fsUsb;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=2)] public int fsCsb;
}
public struct CHARSETINFO
{
public int ciCharset;
public int
ciACP;
public FONTSIGNATURE fs;
}
public struct
LOCALESIGNATURE
{
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=4)] public int
lsUsb;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=2)] public
int lsCsbDefault;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=2)] public int lsCsbSupported;
}
public struct
NEWTEXTMETRICEX
{
public NEWTEXTMETRIC
ntmTm;
public FONTSIGNATURE
ntmFontSig;
}
public struct ENUMLOGFONTEX
{
public LOGFONT
elfLogFont;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=GDI.LF_FULLFACESIZE)] public byte[] elfFullName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=GDI.LF_FACESIZE)]
public byte[] elfStyle;
[MarshalAs(UnmanagedType.ByValArray,
SizeConst=GDI.LF_FACESIZE)] public byte[] elfScript;
}
public
struct GCP_RESULTS
{
public int
lStructSize;
public string lpOutString;
public int
lpOrder;
public int lpDX;
public int
lpCaretPos;
public string lpClass;
public string
lpGlyphs;
public int nGlyphs;
public int
nMaxFit;
}
public struct CIEXYZ
{
public int ciexyzX;
public int
ciexyzY;
public int ciexyzZ;
}
public struct
CIEXYZTRIPLE
{
public CIEXYZ
ciexyzRed;
public CIEXYZ ciexyzGreen;
public
CIEXYZ ciexyBlue;
}
public struct LOGCOLORSPACE
{
public int lcsSignature;
public int
lcsVersion;
public int lcsSize;
public int
lcsCSType;
public int lcsIntent;
public
CIEXYZTRIPLE lcsEndPoints;
public int
lcsGammaRed;
public int lcsGammaGreen;
public int
lcsGammaBlue;
[MarshalAs(UnmanagedType.ByValTStr,
SizeConst=Kernel.MAX_PATH)] public string lcsFileName;
}
public struct PIXELFORMATDESCRIPTOR
{
public short nSize;
public short
nVersion;
public int dwFlags;
public byte
iPixelType;
public byte cColorBits;
public byte
cRedBits;
public byte cRedShift;
public byte
cGreenBits;
public byte cGreenShift;
public byte
cBlueBits;
public byte cBlueShift;
public byte
cAlphaBits;
public byte cAlphaShift;
public byte
cAccumBits;
public byte cAccumRedBits;
public byte
cAccumGreenBits;
public byte
cAccumBlueBits;
public byte
cAccumAlphaBits;
public byte cDepthBits;
public
byte cStencilBits;
public byte cAuxBuffers;
public
byte iLayerType;
public byte bReserved;
public int
dwLayerMask;
public int dwVisibleMask;
public int
dwDamageMask;
}
 public abstract class
GDI
{
[DllImport("gdi32")] public static extern int
AbortDoc(HDC hdc);
[DllImport("gdi32")] public static extern int
AbortPath(HDC hdc);
[DllImport("gdi32")] public static extern int
AddFontResource(string lpFileName);
[DllImport("gdi32")] public
static extern int AngleArc(HDC hdc, int x, int y, int dwRadius, double
eStartAngle, double eSweepAngle);
[DllImport("gdi32")] public
static extern int AnimatePalette(HANDLE hPalette, int wStartIndex, int
wNumEntries, PALETTEENTRY[]
lpPaletteColors);
[DllImport("gdi32")] public static extern int
Arc(HDC hdc, int X1, int Y1, int X2, int Y2, int X3, int Y3, int X4, int
Y4);
[DllImport("gdi32")] public static extern int ArcTo(HDC hdc,
int X1, int Y1, int X2, int Y2, int X3, int Y3, int X4, int
Y4);
[DllImport("gdi32")] public static extern int BeginPath(HDC
hdc);
[DllImport("gdi32")] public static extern int BitBlt(HDC
hDestDC, int x, int y, int nWidth, int nHeight, HDC hSrcDC, int xSrc, int ySrc,
int dwRop);
[DllImport("gdi32")] public static extern int
CancelDC(HDC hdc);
[DllImport("gdi32")] public static extern int
CheckColorsInGamut(HDC hdc, IntPtr lpv, IntPtr lpv2, int
dw);
[DllImport("gdi32")] public static extern int
ChoosePixelFormat(HWND hdc, ref PIXELFORMATDESCRIPTOR
pPixelFormatDescriptor);
[DllImport("gdi32")] public static
extern int Chord(HDC hdc, int X1, int Y1, int X2, int Y2, int X3, int Y3, int
X4, int Y4);
[DllImport("gdi32")] public static extern int
CloseEnhMetaFile(HDC hdc);
[DllImport("gdi32")] public static
extern int CloseFigure(HDC hdc);
[DllImport("gdi32")] public
static extern int CloseMetaFile(HANDLE hMF);
[DllImport("gdi32")]
public static extern int ColorMatchToTarget(HDC hdc, HWND hdc2, int
dw);
[DllImport("gdi32")] public static extern int
CombineRgn(HANDLE hDestRgn, HANDLE hSrcRgn1, HANDLE hSrcRgn2, int
nCombineMode);
[DllImport("gdi32")] public static extern int
CombineTransform(ref XFORM lpxformResult, ref XFORM lpxform1, ref XFORM
lpxform2);
[DllImport("gdi32")] public static extern int
CopyEnhMetaFile(HANDLE hemfSrc, string
lpszFile);
[DllImport("gdi32")] public static extern int
CopyMetaFile(HANDLE hMF, string lpFileName);
[DllImport("gdi32")]
public static extern int CreateBitmap(int nWidth, int nHeight, int nPlanes, int
nBitCount, IntPtr lpBits);
[DllImport("gdi32")] public static
extern int CreateBitmapIndirect(ref BITMAP
lpBitmap);
[DllImport("gdi32")] public static extern int
CreateBrushIndirect(ref LOGBRUSH
lpLogBrush);
[DllImport("gdi32")] public static extern int
CreateColorSpace(ref LOGCOLORSPACE
lplogcolorspace);
[DllImport("gdi32")] public static extern int
CreateCompatibleBitmap(HDC hdc, int nWidth, int
nHeight);
[DllImport("gdi32")] public static extern int
CreateCompatibleDC(HDC hdc);
[DllImport("gdi32")] public static
extern int CreateDC(string lpDriverName, string lpDeviceName, string lpOutput,
ref DEVMODE lpInitData);
[DllImport("gdi32")] public static
extern int CreateDIBPatternBrush(HANDLE hPackedDIB, int
wUsage);
[DllImport("gdi32")] public static extern int
CreateDIBPatternBrushPt(IntPtr lpPackedDIB, int
iUsage);
[DllImport("gdi32")] public static extern int
CreateDIBSection(HWND hdc, ref BITMAPINFO pBitmapInfo, int un, ref IntPtr
lplpVoid, HANDLE handle, int dw);
[DllImport("gdi32")] public
static extern int CreateDIBitmap(HDC hdc, ref BITMAPINFOHEADER lpInfoHeader, int
dwUsage, IntPtr lpInitBits, ref BITMAPINFO lpInitInfo, int
wUsage);
[DllImport("gdi32")] public static extern int
CreateDiscardableBitmap(HDC hdc, int nWidth, int
nHeight);
[DllImport("gdi32")] public static extern int
CreateEllipticRgn(int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int
CreateEllipticRgnIndirect(ref RECT lpRect);
[DllImport("gdi32")]
public static extern int CreateEnhMetaFile(HWND hdcRef, string lpFileName, ref
RECT lpRect, string lpDescription);
[DllImport("gdi32")] public
static extern int CreateFont(HANDLE h, int W, int E, int O, int W2, int I, int
u, int S, int C, int OP, int CP, int Q, int PAF, string
F);
[DllImport("gdi32")] public static extern int
CreateFontIndirect(ref LOGFONT lpLogFont);
[DllImport("gdi32")]
public static extern int CreateHalftonePalette(HDC
hdc);
[DllImport("gdi32")] public static extern int
CreateHatchBrush(int nIndex, int crColor);
[DllImport("gdi32")]
public static extern int CreateIC(string lpDriverName, string lpDeviceName,
string lpOutput, ref DEVMODE lpInitData);
[DllImport("gdi32")]
public static extern int CreateMetaFile(string
lpString);
[DllImport("gdi32")] public static extern int
CreatePalette(ref LOGPALETTE lpLogPalette);
[DllImport("gdi32")]
public static extern int CreatePatternBrush(HANDLE
hBitmap);
[DllImport("gdi32")] public static extern int
CreatePen(int nPenStyle, int nWidth, int
crColor);
[DllImport("gdi32")] public static extern int
CreatePenIndirect(ref LOGPEN lpLogPen);
[DllImport("gdi32")]
public static extern int CreatePolyPolygonRgn(ref POINT lpPoint, ref int
lpPolyCounts, int nCount, int
nPolyFillMode);
[DllImport("gdi32")] public static extern int
CreatePolygonRgn(ref POINT lpPoint, int nCount, int
nPolyFillMode);
[DllImport("gdi32")] public static extern int
CreateRectRgn(int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int
CreateRectRgnIndirect(ref RECT lpRect);
[DllImport("gdi32")]
public static extern int CreateRoundRectRgn(int X1, int Y1, int X2, int Y2, int
X3, int Y3);
[DllImport("gdi32")] public static extern int
CreateScalableFontResource(int fHidden, string lpszResourceFile, string
lpszFontFile, string lpszCurrentPath);
[DllImport("gdi32")]
public static extern int CreateSolidBrush(int
crColor);
[DllImport("gdi32")] public static extern int
DPtoLP(HDC hdc, ref POINT lpPoint, int
nCount);
[DllImport("gdi32")] public static extern int
DeleteColorSpace(HANDLE hcolorspace);
[DllImport("gdi32")] public
static extern int DeleteDC(HDC hdc);
[DllImport("gdi32")] public
static extern int DeleteEnhMetaFile(HANDLE
hemf);
[DllImport("gdi32")] public static extern int
DeleteMetaFile(HANDLE hMF);
[DllImport("gdi32")] public static
extern int DeleteObject(HANDLE hObject);
[DllImport("gdi32")]
public static extern int DescribePixelFormat(HWND hdc, int n, int un, ref
PIXELFORMATDESCRIPTOR
lpPixelFormatDescriptor);
[DllImport("gdi32")] public static
extern int DrawEscape(HDC hdc, int nEscape, int cbInput, string
lpszInData);
[DllImport("gdi32")] public static extern int
Ellipse(HDC hdc, int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int EndDoc(HDC
hdc);
[DllImport("gdi32")] public static extern int EndPage(HDC
hdc);
[DllImport("gdi32")] public static extern int EndPath(HDC
hdc);
[DllImport("gdi32")] public static extern int
EnumEnhMetaFile(HDC hdc, HANDLE hemf, ref int lpEnhMetaFunc, IntPtr lpData, ref
RECT lpRect);
[DllImport("gdi32")] public static extern int
EnumFontFamilies(HDC hdc, string lpszFamily, ref int lpEnumFontFamProc, int
lParam);
[DllImport("gdi32")] public static extern int
EnumFontFamiliesEx(HDC hdc, ref LOGFONT lpLogFont, ref int lpEnumFontProc, int
lParam, int dw);
[DllImport("gdi32")] public static extern int
EnumFonts(HWND hdc, string lpsz, ref int lpFontEnumProc, int
lParam);
[DllImport("gdi32")] public static extern int
EnumICMProfiles(HDC hdc, int icmEnumProc, int
lParam);
[DllImport("gdi32")] public static extern int
EnumMetaFile(HWND hdc, HANDLE hMetafile, ref int lpMFEnumProc, int
lParam);
[DllImport("gdi32")] public static extern int
EnumObjects(HWND hdc, int n, ref int lpGOBJEnumProc, IntPtr
lpVoid);
[DllImport("gdi32")] public static extern int
EqualRgn(HANDLE hSrcRgn1, HANDLE hSrcRgn2);
[DllImport("gdi32")]
public static extern int Escape(HDC hdc, int nEscape, int nCount, string
lpInData, IntPtr lpOutData);
[DllImport("gdi32")] public static
extern int ExcludeClipRect(HDC hdc, int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int
ExtCreatePen(int dwPenStyle, int dwWidth, ref LOGBRUSH lplb, int dwStyleCount,
ref int lpStyle);
[DllImport("gdi32")] public static extern int
ExtCreateRegion(ref XFORM lpXform, int nCount, ref RGNDATA
lpRgnData);
[DllImport("gdi32")] public static extern int
ExtEscape(HDC hdc, int nEscape, int cbInput, string lpszInData, int cbOutput,
string lpszOutData);
[DllImport("gdi32")] public static extern
int ExtFloodFill(HDC hdc, int x, int y, int crColor, int
wFillType);
[DllImport("gdi32")] public static extern int
ExtSelectClipRgn(HDC hdc, HANDLE hRgn, int
fnMode);
[DllImport("gdi32")] public static extern int
ExtTextOut(HDC hdc, int x, int y, int wOptions, ref RECT lpRect, string
lpString, int nCount, ref int lpDx);
[DllImport("gdi32")] public
static extern int FillPath(HDC hdc);
[DllImport("gdi32")] public
static extern int FillRgn(HDC hdc, HANDLE hRgn, HANDLE
hBrush);
[DllImport("gdi32")] public static extern int
FixBrushOrgEx(HWND hdc, int n1, int n2, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
FlattenPath(HDC hdc);
[DllImport("gdi32")] public static extern
int FloodFill(HDC hdc, int x, int y, int
crColor);
[DllImport("gdi32")] public static extern int
FrameRgn(HDC hdc, HANDLE hRgn, HANDLE hBrush, int nWidth, int
nHeight);
[DllImport("gdi32")] public static extern int
GdiComment(HDC hdc, int cbSize, Byte
lpData);
[DllImport("gdi32")] public static extern int
GdiFlush();
[DllImport("gdi32")] public static extern int
GdiGetBatchLimit();
[DllImport("gdi32")] public static extern int
GdiSetBatchLimit(int dwLimit);
[DllImport("gdi32")] public static
extern int GetArcDirection(HDC hdc);
[DllImport("gdi32")] public
static extern int GetAspectRatioFilterEx(HDC hdc, ref SIZE
lpAspectRatio);
[DllImport("gdi32")] public static extern int
GetBitmapBits(HANDLE hBitmap, int dwCount, IntPtr
lpBits);
[DllImport("gdi32")] public static extern int
GetBitmapDimensionEx(HANDLE hBitmap, ref SIZE
lpDimension);
[DllImport("gdi32")] public static extern int
GetBkColor(HDC hdc);
[DllImport("gdi32")] public static extern
int GetBkMode(HDC hdc);
[DllImport("gdi32")] public static extern
int GetBoundsRect(HDC hdc, ref RECT lprcBounds, int
flags);
[DllImport("gdi32")] public static extern int
GetBrushOrgEx(HWND hdc, ref POINT lpPoint);
[DllImport("gdi32")]
public static extern int GetCharABCWidths(HDC hdc, int uFirstChar, int
uLastChar, ref ABC lpabc);
[DllImport("gdi32")] public static
extern int GetCharABCWidthsFloat(HDC hdc, int iFirstChar, int iLastChar, ref
ABCFLOAT lpABCF);
[DllImport("gdi32")] public static extern int
GetCharWidth(HDC hdc, int wFirstChar, int wLastChar, int[]
lpBuffer);
[DllImport("gdi32")] public static extern int
GetCharWidth32(HDC hdc, int iFirstChar, int iLastChar, int[]
lpBuffer);
[DllImport("gdi32")] public static extern int
GetCharWidthFloat(HDC hdc, int iFirstChar, int iLastChar, double[]
pxBuffer);
[DllImport("gdi32")] public static extern int
GetCharacterPlacement(HDC hdc, string lpsz, int n1, int n2, ref GCP_RESULTS
lpGcpResults, int dw);
[DllImport("gdi32")] public static extern
int GetClipBox(HDC hdc, ref RECT lpRect);
[DllImport("gdi32")]
public static extern int GetClipRgn(HDC hdc, HANDLE
hRgn);
[DllImport("gdi32")] public static extern int
GetColorAdjustment(HDC hdc, ref COLORADJUSTMENT
lpca);
[DllImport("gdi32")] public static extern int
GetColorSpace(HDC hdc);
[DllImport("gdi32")] public static extern
int GetCurrentObject(HDC hdc, int
uObjectType);
[DllImport("gdi32")] public static extern int
GetCurrentPositionEx(HDC hdc, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
GetDCOrgEx(HDC hdc, ref POINT lpPoint);
[DllImport("gdi32")]
public static extern int GetDIBColorTable(HWND hdc, int un1, int un2, ref
RGBQUAD pRGBQuad);
[DllImport("gdi32")] public static extern int
GetDIBits(int aHDC, HANDLE hBitmap, int nStartScan, int nNumScans, IntPtr
lpBits, ref BITMAPINFO lpBI, int wUsage);
[DllImport("gdi32")]
public static extern int GetDeviceCaps(HDC hdc, int
nIndex);
[DllImport("gdi32")] public static extern int
GetDeviceGammaRamp(HDC hdc, IntPtr lpv);
[DllImport("gdi32")]
public static extern int GetEnhMetaFile(string
lpszMetaFile);
[DllImport("gdi32")] public static extern int
GetEnhMetaFileBits(HANDLE hemf, int cbBuffer, Byte
lpbBuffer);
[DllImport("gdi32")] public static extern int
GetEnhMetaFileDescription(HANDLE hemf, int cchBuffer, string
lpszDescription);
[DllImport("gdi32")] public static extern int
GetEnhMetaFileHeader(HANDLE hemf, int cbBuffer, ref ENHMETAHEADER
lpemh);
[DllImport("gdi32")] public static extern int
GetEnhMetaFilePaletteEntries(HANDLE hemf, int cEntries, ref PALETTEENTRY
lppe);
[DllImport("gdi32")] public static extern int
GetFontData(HDC hdc, int dwTable, int dwOffset, IntPtr lpvBuffer, int
cbData);
[DllImport("gdi32")] public static extern int
GetFontLanguageInfo(HDC hdc);
[DllImport("gdi32")] public static
extern int GetGlyphOutline(HDC hdc, int uChar, int fuFormat, ref GLYPHMETRICS
lpgm, int cbBuffer, IntPtr lpBuffer, ref MAT2
lpmat2);
[DllImport("gdi32")] public static extern int
GetGraphicsMode(HDC hdc);
[DllImport("gdi32")] public static
extern int GetICMProfile(HDC hdc, int dw, string
lpStr);
[DllImport("gdi32")] public static extern int
GetKerningPairs(HDC hdc, int cPairs, ref KERNINGPAIR
lpkrnpair);
[DllImport("gdi32")] public static extern int
GetLogColorSpace(HANDLE hcolorspace, ref LOGCOLORSPACE lplogcolorspace, int
dw);
[DllImport("gdi32")] public static extern int GetMapMode(HDC
hdc);
[DllImport("gdi32")] public static extern int
GetMetaFile(string lpFileName);
[DllImport("gdi32")] public
static extern int GetMetaFileBitsEx(HANDLE hMF, int nSize, IntPtr
lpvData);
[DllImport("gdi32")] public static extern int
GetMetaRgn(HDC hdc, HANDLE hRgn);
[DllImport("gdi32")] public
static extern int GetMiterLimit(HDC hdc, double
peLimit);
[DllImport("gdi32")] public static extern int
GetNearestColor(HDC hdc, int crColor);
[DllImport("gdi32")]
public static extern int GetNearestPaletteIndex(HANDLE hPalette, int
crColor);
[DllImport("gdi32")] public static extern int
GetObject(HANDLE hObject, int nCount, IntPtr
lpObject);
[DllImport("gdi32")] public static extern int
GetObjectType(HANDLE hgdiobj);
[DllImport("gdi32")] public static
extern int GetOutlineTextMetrics(HDC hdc, int cbData, ref OUTLINETEXTMETRIC
lpotm);
[DllImport("gdi32")] public static extern int
GetPaletteEntries(HANDLE hPalette, int wStartIndex, int wNumEntries, ref
PALETTEENTRY lpPaletteEntries);
[DllImport("gdi32")] public
static extern int GetPath(HDC hdc, ref POINT lpPoint, Byte lpTypes, int
nSize);
[DllImport("gdi32")] public static extern int
GetPixel(HDC hdc, int x, int y);
[DllImport("gdi32")] public
static extern int GetPixelFormat(HWND hdc);
[DllImport("gdi32")]
public static extern int GetPolyFillMode(HDC
hdc);
[DllImport("gdi32")] public static extern int GetROP2(HDC
hdc);
[DllImport("gdi32")] public static extern int
GetRasterizerCaps(ref RASTERIZER_STATUS lpraststat, int
cb);
[DllImport("gdi32")] public static extern int
GetRegionData(HANDLE hRgn, int dwCount, ref RGNDATA
lpRgnData);
[DllImport("gdi32")] public static extern int
GetRgnBox(HANDLE hRgn, ref RECT lpRect);
[DllImport("gdi32")]
public static extern int GetStockObject(int
nIndex);
[DllImport("gdi32")] public static extern int
GetStretchBltMode(HDC hdc);
[DllImport("gdi32")] public static
extern int GetSystemPaletteEntries(HDC hdc, int wStartIndex, int wNumEntries,
ref PALETTEENTRY lpPaletteEntries);
[DllImport("gdi32")] public
static extern int GetSystemPaletteUse(HDC
hdc);
[DllImport("gdi32")] public static extern int
GetTextAlign(HDC hdc);
[DllImport("gdi32")] public static extern
int GetTextCharacterExtra(HDC hdc);
[DllImport("gdi32")] public
static extern int GetTextCharset(HDC hdc);
[DllImport("gdi32")]
public static extern int GetTextCharsetInfo(HDC hdc, ref FONTSIGNATURE lpSig,
int dwFlags);
[DllImport("gdi32")] public static extern int
GetTextColor(HDC hdc);
[DllImport("gdi32")] public static extern
int GetTextExtentExPoint(HDC hdc, string lpszStr, int cchString, int nMaxExtent,
ref int lpnFit, int alpDx, ref SIZE lpSize);
[DllImport("gdi32")]
public static extern int GetTextExtentPoint(HDC hdc, string lpszString, int
cbString, ref SIZE lpSize);
[DllImport("gdi32")] public static
extern int GetTextExtentPoint32(HDC hdc, string lpsz, int cbString, ref SIZE
lpSize);
[DllImport("gdi32")] public static extern int
GetTextFace(HDC hdc, int nCount, string
lpFacename);
[DllImport("gdi32")] public static extern int
GetTextMetrics(HDC hdc, ref TEXTMETRIC
lpMetrics);
[DllImport("gdi32")] public static extern int
GetViewportExtEx(HDC hdc, ref SIZE lpSize);
[DllImport("gdi32")]
public static extern int GetViewportOrgEx(HDC hdc, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
GetWinMetaFileBits(HANDLE hemf, int cbBuffer, Byte lpbBuffer, int fnMapMode,
HWND hdcRef);
[DllImport("gdi32")] public static extern int
GetWindowExtEx(HDC hdc, ref SIZE lpSize);
[DllImport("gdi32")]
public static extern int GetWindowOrgEx(HDC hdc, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
GetWorldTransform(HDC hdc, ref XFORM
lpXform);
[DllImport("gdi32")] public static extern int
IntersectClipRect(HDC hdc, int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int InvertRgn(HDC
hdc, HANDLE hRgn);
[DllImport("gdi32")] public static extern int
LPtoDP(HDC hdc, ref POINT lpPoint, int
nCount);
[DllImport("gdi32")] public static extern int
LineDDA(int n1, int n2, int n3, int n4, ref int lpLineDDAProc, int
lParam);
[DllImport("gdi32")] public static extern int LineTo(HDC
hdc, int x, int y);
[DllImport("gdi32")] public static extern int
MaskBlt(HWND hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, HWND
hdcSrc, int nXSrc, int nYSrc, HANDLE hbmMask, int xMask, int yMask, int
dwRop);
[DllImport("gdi32")] public static extern int
ModifyWorldTransform(HDC hdc, ref XFORM lpXform, int
iMode);
[DllImport("gdi32")] public static extern int
MoveToEx(HDC hdc, int x, int y, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
OffsetClipRgn(HDC hdc, int x, int y);
[DllImport("gdi32")] public
static extern int OffsetRgn(HANDLE hRgn, int x, int
y);
[DllImport("gdi32")] public static extern int
OffsetViewportOrgEx(HDC hdc, int nX, int nY, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
OffsetWindowOrgEx(HDC hdc, int nX, int nY, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
PaintRgn(HDC hdc, HANDLE hRgn);
[DllImport("gdi32")] public
static extern int PatBlt(HDC hdc, int x, int y, int nWidth, int nHeight, int
dwRop);
[DllImport("gdi32")] public static extern int
PathToRegion(HDC hdc);
[DllImport("gdi32")] public static extern
int Pie(HDC hdc, int X1, int Y1, int X2, int Y2, int X3, int Y3, int X4, int
Y4);
[DllImport("gdi32")] public static extern int
PlayEnhMetaFile(HDC hdc, HANDLE hemf, ref RECT
lpRect);
[DllImport("gdi32")] public static extern int
PlayEnhMetaFileRecord(HDC hdc, ref HANDLETABLE lpHandletable, ref ENHMETARECORD
lpEnhMetaRecord, int nHandles);
[DllImport("gdi32")] public
static extern int PlayMetaFile(HDC hdc, HANDLE
hMF);
[DllImport("gdi32")] public static extern int
PlayMetaFileRecord(HDC hdc, ref HANDLETABLE lpHandletable, ref METARECORD
lpMetaRecord, int nHandles);
[DllImport("gdi32")] public static
extern int PlgBlt(HWND hdcDest, ref POINT lpPoint, HWND hdcSrc, int nXSrc, int
nYSrc, int nWidth, int nHeight, HANDLE hbmMask, int xMask, int
yMask);
[DllImport("gdi32")] public static extern int
PolyBezier(HDC hdc, ref POINT lppt, int
cPoints);
[DllImport("gdi32")] public static extern int
PolyBezierTo(HDC hdc, ref POINT lppt, int
cCount);
[DllImport("gdi32")] public static extern int
PolyDraw(HDC hdc, ref POINT lppt, Byte lpbTypes, int
cCount);
[DllImport("gdi32")] public static extern int
PolyPolygon(HDC hdc, ref POINT lpPoint, ref int lpPolyCounts, int
nCount);
[DllImport("gdi32")] public static extern int
PolyPolyline(HDC hdc, ref POINT lppt, ref int lpdwPolyPoints, int
cCount);
[DllImport("gdi32")] public static extern int
PolyTextOut(HDC hdc, ref POLYTEXT pptxt, int
cStrings);
[DllImport("gdi32")] public static extern int
Polygon(HDC hdc, ref POINT lpPoint, int
nCount);
[DllImport("gdi32")] public static extern int
Polyline(HDC hdc, ref POINT lpPoint, int
nCount);
[DllImport("gdi32")] public static extern int
PolylineTo(HDC hdc, ref POINT lppt, int
cCount);
[DllImport("gdi32")] public static extern int
PtInRegion(HANDLE hRgn, int x, int y);
[DllImport("gdi32")]
public static extern int PtVisible(HDC hdc, int x, int
y);
[DllImport("gdi32")] public static extern int
RealizePalette(HDC hdc);
[DllImport("gdi32")] public static
extern int RectInRegion(HANDLE hRgn, ref RECT
lpRect);
[DllImport("gdi32")] public static extern int
RectVisible(HDC hdc, ref RECT lpRect);
[DllImport("gdi32")]
public static extern int Rectangle(HDC hdc, int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int
RemoveFontResource(string lpFileName);
[DllImport("gdi32")]
public static extern int ResetDC(HDC hdc, ref DEVMODE
lpInitData);
[DllImport("gdi32")] public static extern int
ResizePalette(HANDLE hPalette, int
nNumEntries);
[DllImport("gdi32")] public static extern int
RestoreDC(HDC hdc, int nSavedDC);
[DllImport("gdi32")] public
static extern int RoundRect(HDC hdc, int X1, int Y1, int X2, int Y2, int X3, int
Y3);
[DllImport("gdi32")] public static extern int SaveDC(HDC
hdc);
[DllImport("gdi32")] public static extern int
ScaleViewportExtEx(HDC hdc, int nXnum, int nXdenom, int nYnum, int nYdenom, ref
SIZE lpSize);
[DllImport("gdi32")] public static extern int
ScaleWindowExtEx(HDC hdc, int nXnum, int nXdenom, int nYnum, int nYdenom, ref
SIZE lpSize);
[DllImport("gdi32")] public static extern int
SelectClipPath(HDC hdc, int iMode);
[DllImport("gdi32")] public
static extern int SelectClipRgn(HDC hdc, HANDLE
hRgn);
[DllImport("gdi32")] public static extern int
SelectObject(HDC hdc, HANDLE hObject);
[DllImport("gdi32")]
public static extern int SelectPalette(HDC hdc, HANDLE hPalette, int
bForceBackground);
[DllImport("gdi32")] public static extern int
SetAbortProc(HWND hdc, ref int lpAbortProc);
[DllImport("gdi32")]
public static extern int SetArcDirection(HDC hdc, int
ArcDirection);
[DllImport("gdi32")] public static extern int
SetBitmapBits(HANDLE hBitmap, int dwCount, IntPtr
lpBits);
[DllImport("gdi32")] public static extern int
SetBitmapDimensionEx(HANDLE hbm, int nX, int nY, ref SIZE
lpSize);
[DllImport("gdi32")] public static extern int
SetBkColor(HDC hdc, int crColor);
[DllImport("gdi32")] public
static extern int SetBkMode(HDC hdc, int
nBkMode);
[DllImport("gdi32")] public static extern int
SetBoundsRect(HDC hdc, ref RECT lprcBounds, int
flags);
[DllImport("gdi32")] public static extern int
SetBrushOrgEx(HDC hdc, int nXOrg, int nYOrg, ref POINT
lppt);
[DllImport("gdi32")] public static extern int
SetColorAdjustment(HDC hdc, ref COLORADJUSTMENT
lpca);
[DllImport("gdi32")] public static extern int
SetColorSpace(HDC hdc, HANDLE hcolorspace);
[DllImport("gdi32")]
public static extern int SetDIBColorTable(HWND hdc, int un1, int un2, ref
RGBQUAD pcRGBQuad);
[DllImport("gdi32")] public static extern int
SetDIBits(HDC hdc, HANDLE hBitmap, int nStartScan, int nNumScans, IntPtr lpBits,
ref BITMAPINFO lpBI, int wUsage);
[DllImport("gdi32")] public
static extern int SetDIBitsToDevice(HDC hdc, int x, int y, int dx, int dy, int
SrcX, int SrcY, int Scan, int NumScans, IntPtr Bits, BITMAPINFO BitsInfo, int
wUsage);
[DllImport("gdi32")] public static extern int
SetDeviceGammaRamp(HDC hdc, IntPtr lpv);
[DllImport("gdi32")]
public static extern int SetEnhMetaFileBits(int cbBuffer, Byte
lpData);
[DllImport("gdi32")] public static extern int
SetGraphicsMode(HDC hdc, int iMode);
[DllImport("gdi32")] public
static extern int SetICMMode(HDC hdc, int
n);
[DllImport("gdi32")] public static extern int
SetICMProfile(HDC hdc, string lpStr);
[DllImport("gdi32")] public
static extern int SetMapMode(HDC hdc, int
nMapMode);
[DllImport("gdi32")] public static extern int
SetMapperFlags(HDC hdc, int dwFlag);
[DllImport("gdi32")] public
static extern int SetMetaFileBitsEx(int nSize, Byte
lpData);
[DllImport("gdi32")] public static extern int
SetMetaRgn(HDC hdc);
[DllImport("gdi32")] public static extern
int SetMiterLimit(HDC hdc, double eNewLimit, double
peOldLimit);
[DllImport("gdi32")] public static extern int
SetPaletteEntries(HANDLE hPalette, int wStartIndex, int wNumEntries, ref
PALETTEENTRY lpPaletteEntries);
[DllImport("gdi32")] public
static extern int SetPixel(HDC hdc, int x, int y, int
crColor);
[DllImport("gdi32")] public static extern int
SetPixelFormat(HWND hdc, int n, ref PIXELFORMATDESCRIPTOR
pcPixelFormatDescriptor);
[DllImport("gdi32")] public static
extern int SetPixelV(HDC hdc, int x, int y, int
crColor);
[DllImport("gdi32")] public static extern int
SetPolyFillMode(HDC hdc, int nPolyFillMode);
[DllImport("gdi32")]
public static extern int SetROP2(HDC hdc, int
nDrawMode);
[DllImport("gdi32")] public static extern int
SetRectRgn(HANDLE hRgn, int X1, int Y1, int X2, int
Y2);
[DllImport("gdi32")] public static extern int
SetStretchBltMode(HDC hdc, int
nStretchMode);
[DllImport("gdi32")] public static extern int
SetSystemPaletteUse(HDC hdc, int wUsage);
[DllImport("gdi32")]
public static extern int SetTextAlign(HDC hdc, int
wFlags);
[DllImport("gdi32")] public static extern int
SetTextCharacterExtra(HDC hdc, int
nCharExtra);
[DllImport("gdi32")] public static extern int
SetTextColor(HDC hdc, int crColor);
[DllImport("gdi32")] public
static extern int SetTextJustification(HDC hdc, int nBreakExtra, int
nBreakCount);
[DllImport("gdi32")] public static extern int
SetViewportExtEx(HDC hdc, int nX, int nY, ref SIZE
lpSize);
[DllImport("gdi32")] public static extern int
SetViewportOrgEx(HDC hdc, int nX, int nY, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
SetWinMetaFileBits(int cbBuffer, Byte lpbBuffer, HWND hdcRef, ref METAFILEPICT
lpmfp);
[DllImport("gdi32")] public static extern int
SetWindowExtEx(HDC hdc, int nX, int nY, ref SIZE
lpSize);
[DllImport("gdi32")] public static extern int
SetWindowOrgEx(HDC hdc, int nX, int nY, ref POINT
lpPoint);
[DllImport("gdi32")] public static extern int
SetWorldTransform(HDC hdc, ref XFORM
lpXform);
[DllImport("gdi32")] public static extern int
StartDoc(HDC hdc, ref DOCINFO lpdi);
[DllImport("gdi32")] public
static extern int StartPage(HDC hdc);
[DllImport("gdi32")] public
static extern int StretchBlt(HDC hdc, int x, int y, int nWidth, int nHeight,
HANDLE hSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, int
dwRop);
[DllImport("gdi32")] public static extern int
StretchDIBits(HDC hdc, int x, int y, int dx, int dy, int SrcX, int SrcY, int
wSrcWidth, int wSrcHeight, IntPtr lpBits, ref BITMAPINFO lpBitsInfo, int wUsage,
int dwRop);
[DllImport("gdi32")] public static extern int
StrokeAndFillPath(HDC hdc);
[DllImport("gdi32")] public static
extern int StrokePath(HDC hdc);
[DllImport("gdi32")] public
static extern int SwapBuffers(HWND hdc);
[DllImport("gdi32")]
public static extern int TextOut(HDC hdc, int x, int y, string lpString, int
nCount);
[DllImport("gdi32")] public static extern int
TranslateCharsetInfo(int lpSrc, ref CHARSETINFO lpcs, int
dwFlags);
[DllImport("gdi32")] public static extern int
UnrealizeObject(HANDLE hObject);
[DllImport("gdi32")] public
static extern int UpdateColors(HDC hdc);
[DllImport("gdi32")]
public static extern int WidenPath(HDC hdc);
public const int ABSOLUTE = 1;
public const int AD_CLOCKWISE = 2;
public const int AD_COUNTERCLOCKWISE = 1;
public const int ALTERNATE = 1;
public const int ANSI_CHARSET = 0;
public const int ANSI_FIXED_FONT = 11;
public const int ANSI_VAR_FONT = 12;
public const int ARABIC_CHARSET = 178;
public const int ASPECTX = 40;
public const int ASPECTXY = 44;
public const int ASPECTY = 42;
public const int ASPECT_FILTERING = 0x1;
public const int AbortDocC = 2;
public const int BALTIC_CHARSET = 186;
public const int BANDINFO = 24;
public const int BEGIN_PATH = 4096;
public const int BITSPIXEL = 12;
public const int BI_RGB = 0;
public const int BI_RLE4 = 2;
public const int BI_RLE8 = 1;
public const int BI_bitfields = 3;
public const int BKMODE_LAST = 2;
public const int BLACKNESS = 0x42;
public const int BLACKONWHITE = 1;
public const int BLACK_BRUSH = 4;
public const int BLACK_PEN = 7;
public const int BS_DIBPATTERN = 5;
public const int BS_DIBPATTERN8X8 = 8;
public const int BS_DIBPATTERNPT = 6;
public const int BS_HATCHED = 2;
public const int BS_HOLLOW = BS_NULL;
public const int BS_INDEXED = 4;
public const int BS_NULL = 1;
public const int BS_PATTERN = 3;
public const int BS_PATTERN8X8 = 7;
public const int BS_SOLID = 0;
public const int CA_LOG_FILTER = 0x2;
public const int CA_NEGATIVE = 0x1;
public const int CBM_CREATEDIB = 0x2;
public const int CBM_INIT = 0x4;
public const int CCHDEVICENAME = 32;
public const int CCHFORMNAME = 32;
public const int CC_CHORD = 4;
public const int CC_CIRCLES = 1;
public const int CC_ELLIPSES = 8;
public const int CC_INTERIORS = 128;
public const int CC_NONE = 0;
public const int CC_PIE = 2;
public const int CC_ROUNDRECT = 256;
public const int CC_STYLED = 32;
public const int CC_WIDE = 16;
public const int CC_WIDESTYLED = 64;
public const int CHINESEBIG5_CHARSET = 136;
public const int CLIPCAPS = 36;
public const int CLIP_CHARACTER_PRECIS = 1;
public const int CLIP_DEFAULT_PRECIS = 0;
public const int CLIP_EMBEDDED = 128;
public const int CLIP_LH_ANGLES = 16;
public const int CLIP_MASK = 0xF;
public const int CLIP_STROKE_PRECIS = 2;
public const int CLIP_TO_PATH = 4097;
public const int CLIP_TT_ALWAYS = 32;
public const int CLOSECHANNEL = 4112;
public const int CLR_INVALID = 0xFFFF;
public const int COLORONCOLOR = 3;
public const int COLORRES = 108;
public const int COLOR_ADJ_MAX = 100;
public const int COLOR_ADJ_MIN = -100;
public const int COMPLEXREGION = 3;
public const int CP_NONE = 0;
public const int CP_RECTANGLE = 1;
public const int CP_REGION = 2;
public const int CURVECAPS = 28;
public const int DCBA_FACEDOWNCENTER = 0x101;
public const int DCBA_FACEDOWNLEFT = 0x102;
public const int DCBA_FACEDOWNNONE = 0x100;
public const int DCBA_FACEDOWNRIGHT = 0x103;
public const int DCBA_FACEUPCENTER = 0x1;
public const int DCBA_FACEUPLEFT = 0x2;
public const int DCBA_FACEUPNONE = 0x0;
public const int DCBA_FACEUPRIGHT = 0x3;
public const int DCB_ACCUMULATE = 0x2;
public const int DCB_DIRTY = DCB_ACCUMULATE;
public const int DCB_DISABLE = 0x8;
public const int DCB_ENABLE = 0x4;
public const int DCB_RESET = 0x1;
public const int DCB_SET = (DCB_RESET | DCB_ACCUMULATE);
public const int DCTT_BITMAP = 0x1;
public const int DCTT_DOWNLOAD = 0x2;
public const int DCTT_DOWNLOAD_OUTLINE = 0x8;
public const int DCTT_SUBDEV = 0x4;
public const int DC_BINADJUST = 19;
public const int DC_BINNAMES = 12;
public const int DC_BINS = 6;
public const int DC_COLLATE = 22;
public const int DC_COPIES = 18;
public const int DC_DATATYPE_PRODUCED = 21;
public const int DC_DRIVER = 11;
public const int DC_DUPLEX = 7;
public const int DC_EMF_COMPLIANT = 20;
public const int DC_ENUMRESOLUTIONS = 13;
public const int DC_EXTRA = 9;
public const int DC_FIELDS = 1;
public const int DC_FILEDEPENDENCIES = 14;
public const int DC_MAXEXTENT = 5;
public const int DC_MINEXTENT = 4;
public const int DC_ORIENTATION = 17;
public const int DC_PAPERNAMES = 16;
public const int DC_PAPERS = 2;
public const int DC_PAPERSIZE = 3;
public const int DC_SIZE = 8;
public const int DC_TRUETYPE = 15;
public const int DC_VERSION = 10;
public const int DEFAULT_CHARSET = 1;
public const int DEFAULT_GUI_FONT = 17;
public const int DEFAULT_PALETTE = 15;
public const int DEFAULT_PITCH = 0;
public const int DEFAULT_QUALITY = 0;
public const int DEVICEDATA = 19;
public const int DEVICE_DEFAULT_FONT = 14;
public const int DEVICE_FONTTYPE = 0x2;
public const int DIB_PAL_COLORS = 1;
public const int DIB_PAL_INDICES = 2;
public const int DIB_PAL_LOGINDICES = 4;
public const int DIB_PAL_PHYSINDICES = 2;
public const int DIB_RGB_COLORS = 0;
public const int DKGRAY_BRUSH = 3;
public const int DMBIN_AUTO = 7;
public const int DMBIN_CASSETTE = 14;
public const int DMBIN_ENVELOPE = 5;
public const int DMBIN_ENVMANUAL = 6;
public const int DMBIN_FIRST = DMBIN_UPPER;
public const int DMBIN_LARGECAPACITY = 11;
public const int DMBIN_LARGEFMT = 10;
public const int DMBIN_LAST = DMBIN_CASSETTE;
public const int DMBIN_LOWER = 2;
public const int DMBIN_MANUAL = 4;
public const int DMBIN_MIDDLE = 3;
public const int DMBIN_ONLYONE = 1;
public const int DMBIN_SMALLFMT = 9;
public const int DMBIN_TRACTOR = 8;
public const int DMBIN_UPPER = 1;
public const int DMBIN_USER = 256;
public const int DMCOLLATE_FALSE = 0;
public const int DMCOLLATE_TRUE = 1;
public const int DMCOLOR_COLOR = 2;
public const int DMCOLOR_MONOCHROME = 1;
public const int DMDITHER_COARSE = 2;
public const int DMDITHER_FINE = 3;
public const int DMDITHER_GRAYSCALE = 5;
public const int DMDITHER_LINEART = 4;
public const int DMDITHER_NONE = 1;
public const int DMDITHER_USER = 256;
public const int DMDUP_HORIZONTAL = 3;
public const int DMDUP_SIMPLEX = 1;
public const int DMDUP_VERTICAL = 2;
public const int DMICMMETHOD_DEVICE = 4;
public const int DMICMMETHOD_DRIVER = 3;
public const int DMICMMETHOD_NONE = 1;
public const int DMICMMETHOD_SYSTEM = 2;
public const int DMICMMETHOD_USER = 256;
public const int DMICM_COLORMETRIC = 3;
public const int DMICM_CONTRAST = 2;
public const int DMICM_SATURATE = 1;
public const int DMICM_USER = 256;
public const int DMMEDIA_GLOSSY = 2;
public const int DMMEDIA_STANDARD = 1;
public const int DMMEDIA_TRANSPARENCY = 3;
public const int DMMEDIA_USER = 256;
public const int DMORIENT_LANDSCAPE = 2;
public const int DMORIENT_PORTRAIT = 1;
public const int DMPAPER_10X11 = 45;
public const int DMPAPER_10X14 = 16;
public const int DMPAPER_11X17 = 17;
public const int DMPAPER_15X11 = 46;
public const int DMPAPER_9X11 = 44;
public const int DMPAPER_A2 = 66;
public const int DMPAPER_A3 = 8;
public const int DMPAPER_A3_EXTRA = 63;
public const int DMPAPER_A3_EXTRA_TRANSVERSE = 68;
public const int DMPAPER_A3_TRANSVERSE = 67;
public const int DMPAPER_A4 = 9;
public const int DMPAPER_A4SMALL = 10;
public const int DMPAPER_A4_EXTRA = 53;
public const int DMPAPER_A4_PLUS = 60;
public const int DMPAPER_A4_TRANSVERSE = 55;
public const int DMPAPER_A5 = 11;
public const int DMPAPER_A5_EXTRA = 64;
public const int DMPAPER_A5_TRANSVERSE = 61;
public const int DMPAPER_A_PLUS = 57;
public const int DMPAPER_B4 = 12;
public const int DMPAPER_B5 = 13;
public const int DMPAPER_B5_EXTRA = 65;
public const int DMPAPER_B5_TRANSVERSE = 62;
public const int DMPAPER_B_PLUS = 58;
public const int DMPAPER_CSHEET = 24;
public const int DMPAPER_DSHEET = 25;
public const int DMPAPER_ENV_10 = 20;
public const int DMPAPER_ENV_11 = 21;
public const int DMPAPER_ENV_12 = 22;
public const int DMPAPER_ENV_14 = 23;
public const int DMPAPER_ENV_9 = 19;
public const int DMPAPER_ENV_B4 = 33;
public const int DMPAPER_ENV_B5 = 34;
public const int DMPAPER_ENV_B6 = 35;
public const int DMPAPER_ENV_C3 = 29;
public const int DMPAPER_ENV_C4 = 30;
public const int DMPAPER_ENV_C5 = 28;
public const int DMPAPER_ENV_C6 = 31;
public const int DMPAPER_ENV_C65 = 32;
public const int DMPAPER_ENV_DL = 27;
public const int DMPAPER_ENV_INVITE = 47;
public const int DMPAPER_ENV_ITALY = 36;
public const int DMPAPER_ENV_MONARCH = 37;
public const int DMPAPER_ENV_PERSONAL = 38;
public const int DMPAPER_ESHEET = 26;
public const int DMPAPER_EXECUTIVE = 7;
public const int DMPAPER_FANFOLD_LGL_GERMAN = 41;
public const int DMPAPER_FANFOLD_STD_GERMAN = 40;
public const int DMPAPER_FANFOLD_US = 39;
public const int DMPAPER_FIRST = DMPAPER_LETTER;
public const int DMPAPER_FOLIO = 14;
public const int DMPAPER_ISO_B4 = 42;
public const int DMPAPER_JAPANESE_POSTCARD = 43;
public const int DMPAPER_LAST = DMPAPER_FANFOLD_LGL_GERMAN;
public const int DMPAPER_LEDGER = 4;
public const int DMPAPER_LEGAL = 5;
public const int DMPAPER_LEGAL_EXTRA = 51;
public const int DMPAPER_LETTER = 1;
public const int DMPAPER_LETTERSMALL = 2;
public const int DMPAPER_LETTER_EXTRA = 50;
public const int DMPAPER_LETTER_EXTRA_TRANSVERSE = 56;
public const int DMPAPER_LETTER_PLUS = 59;
public const int DMPAPER_LETTER_TRANSVERSE = 54;
public const int DMPAPER_NOTE = 18;
public const int DMPAPER_QUARTO = 15;
public const int DMPAPER_RESERVED_48 = 48;
public const int DMPAPER_RESERVED_49 = 49;
public const int DMPAPER_STATEMENT = 6;
public const int DMPAPER_TABLOID = 3;
public const int DMPAPER_TABLOID_EXTRA = 52;
public const int DMPAPER_USER = 256;
public const int DMRES_DRAFT = (-1);
public const int DMRES_HIGH = (-4);
public const int DMRES_LOW = (-2);
public const int DMRES_MEDIUM = (-3);
public const int DMTT_BITMAP = 1;
public const int DMTT_DOWNLOAD = 2;
public const int DMTT_DOWNLOAD_OUTLINE = 4;
public const int DMTT_SUBDEV = 3;
public const int DM_COLLATE = 0x8000;
public const int DM_COLOR = 0x800;
public const int DM_COPIES = 0x100;
public const int DM_COPY = 2;
public const int DM_DEFAULTSOURCE = 0x200;
public const int DM_DITHERTYPE = 0x10000000;
public const int DM_DUPLEX = 0x1000;
public const int DM_FORMNAME = 0x10000;
public const int DM_GRAYSCALE = 0x1;
public const int DM_ICMINTENT = 0x4000000;
public const int DM_ICMMETHOD = 0x2000000;
public const int DM_INTERLACED = 0x2;
public const int DM_IN_BUFFER = DM_MODIFY;
public const int DM_IN_PROMPT = DM_PROMPT;
public const int DM_MEDIATYPE = 0x8000000;
public const int DM_MODIFY = 8;
public const int DM_ORIENTATION = 0x1;
public const int DM_OUT_BUFFER = DM_COPY;
public const int DM_OUT_DEFAULT = DM_UPDATE;
public const int DM_PAPERLENGTH = 0x4;
public const int DM_PAPERSIZE = 0x2;
public const int DM_PAPERWIDTH = 0x8;
public const int DM_PRINTQUALITY = 0x400;
public const int DM_PROMPT = 4;
public const int DM_RESERVED1 = 0x800000;
public const int DM_RESERVED2 = 0x1000000;
public const int DM_SCALE = 0x10;
public const int DM_SPECVERSION = 0x320;
public const int DM_TTOPTION = 0x4000;
public const int DM_UPDATE = 1;
public const int DM_YRESOLUTION = 0x2000;
public const int DOWNLOADFACE = 514;
public const int DOWNLOADHEADER = 4111;
public const int DRAFTMODE = 7;
public const int DRAFT_QUALITY = 1;
public const int DRAWPATTERNRECT = 25;
public const int DRIVERVERSION = 0;
public const int DSTINVERT = 0x550009;
public const int DT_CHARSTREAM = 4;
public const int DT_DISPFILE = 6;
public const int DT_METAFILE = 5;
public const int DT_PLOTTER = 0;
public const int DT_RASCAMERA = 3;
public const int DT_RASDISPLAY = 1;
public const int DT_RASPRINTER = 2;
public const int EASTEUROPE_CHARSET = 238;
public const int ELF_CULTURE_LATIN = 0;
public const int ELF_VENDOR_SIZE = 4;
public const int ELF_VERSION = 0;
public const int ENABLEDUPLEX = 28;
public const int ENABLEPAIRKERNING = 769;
public const int ENABLERELATIVEWIDTHS = 768;
public const int ENCAPSULATED_POSTSCRIPT = 4116;
public const int END_PATH = 4098;
public const int ENHMETA_SIGNATURE = 0x464D4520;
public const int ENHMETA_STOCK_OBJECT = unchecked((int)0x80000000);
public const int ENUMPAPERBINS = 31;
public const int ENUMPAPERMETRICS = 34;
public const int EPSPRINTING = 33;
public const int ERROR = 0;
public const int ETO_CLIPPED = 4;
public const int ETO_GRAYED = 1;
public const int ETO_OPAQUE = 2;
public const int EXT_DEVICE_CAPS = 4099;
public const int EndDocC = 11;
public const int ExtTextOutC = 512;
public const int FF_DECORATIVE = 80;
public const int FF_DONTCARE = 0;
public const int FF_MODERN = 48;
public const int FF_ROMAN = 16;
public const int FF_SCRIPT = 64;
public const int FF_SWISS = 32;
public const int FIXED_PITCH = 1;
public const int FLI_GLYPHS = 0x40000;
public const int FLI_MASK = 0x103B;
public const int FLOODFILLBORDER = 0;
public const int FLOODFILLSURFACE = 1;
public const int FLUSHOUTPUT = 6;
public const int FONTMAPPER_MAX = 10;
public const int FS_ARABIC = 0x40;
public const int FS_BALTIC = 0x80;
public const int FS_CHINESESIMP = 0x40000;
public const int FS_CHINESETRAD = 0x100000;
public const int FS_CYRILLIC = 0x4;
public const int FS_GREEK = 0x8;
public const int FS_HEBREW = 0x20;
public const int FS_JISJAPAN = 0x20000;
public const int FS_JOHAB = 0x200000;
public const int FS_LATIN1 = 0x1;
public const int FS_LATIN2 = 0x2;
public const int FS_SYMBOL = unchecked((int)0x80000000);
public const int FS_THAI = 0x10000;
public const int FS_TURKISH = 0x10;
public const int FS_WANSUNG = 0x80000;
public const int FW_BLACK = FW_HEAVY;
public const int FW_BOLD = 700;
public const int FW_DEMIBOLD = FW_SEMIBOLD;
public const int FW_DONTCARE = 0;
public const int FW_EXTRABOLD = 800;
public const int FW_EXTRALIGHT = 200;
public const int FW_HEAVY = 900;
public const int FW_LIGHT = 300;
public const int FW_MEDIUM = 500;
public const int FW_NORMAL = 400;
public const int FW_REGULAR = FW_NORMAL;
public const int FW_SEMIBOLD = 600;
public const int FW_THIN = 100;
public const int FW_ULTRABOLD = FW_EXTRABOLD;
public const int FW_ULTRALIGHT = FW_EXTRALIGHT;
public const int GCPCLASS_ARABIC = 2;
public const int GCPCLASS_HEBREW = 2;
public const int GCPCLASS_LATIN = 1;
public const int GCPCLASS_LATINNUMBER = 5;
public const int GCPCLASS_LATINNUMERICSEPARATOR = 7;
public const int GCPCLASS_LATINNUMERICTERMINATOR = 6;
public const int GCPCLASS_LOCALNUMBER = 4;
public const int GCPCLASS_NEUTRAL = 3;
public const int GCPCLASS_NUMERICSEPARATOR = 8;
public const int GCPCLASS_PREBOUNDLTR = 0x40;
public const int GCPCLASS_PREBOUNDRTL = 0x80;
public const int GCP_CLASSIN = 0x80000;
public const int GCP_DBCS = 0x1;
public const int GCP_DIACRITIC = 0x100;
public const int GCP_DISPLAYZWG = 0x400000;
public const int GCP_ERROR = 0x8000;
public const int GCP_GLYPHSHAPE = 0x10;
public const int GCP_JUSTIFY = 0x10000;
public const int GCP_JUSTIFYIN = 0x200000;
public const int GCP_KASHIDA = 0x400;
public const int GCP_LIGATE = 0x20;
public const int GCP_MAXEXTENT = 0x100000;
public const int GCP_NEUTRALOVERRIDE = 0x2000000;
public const int GCP_NODIACRITICS = 0x20000;
public const int GCP_NUMERICOVERRIDE = 0x1000000;
public const int GCP_NUMERICSLATIN = 0x4000000;
public const int GCP_NUMERICSLOCAL = 0x8000000;
public const int GCP_REORDER = 0x2;
public const int GCP_SYMSWAPOFF = 0x800000;
public const int GCP_USEKERNING = 0x8;
public const int GDI_ERROR = 0xFFFF;
public const int GETCOLORTABLE = 5;
public const int GETDEVICEUNITS = 42;
public const int GETEXTENDEDTEXTMETRICS = 256;
public const int GETEXTENTTABLE = 257;
public const int GETFACENAME = 513;
public const int GETPAIRKERNTABLE = 258;
public const int GETPENWIDTH = 16;
public const int GETPHYSPAGESIZE = 12;
public const int GETPRINTINGOFFSET = 13;
public const int GETSCALINGFACTOR = 14;
public const int GETSETPAPERBINS = 29;
public const int GETSETPAPERMETRICS = 35;
public const int GETSETPRINTORIENT = 30;
public const int GETSETSCREENPARAMS = 3072;
public const int GETTECHNOLGY = 20;
public const int GETTECHNOLOGY = 20;
public const int GETTRACKKERNTABLE = 259;
public const int GETVECTORBRUSHSIZE = 27;
public const int GETVECTORPENSIZE = 26;
public const int GGO_BITMAP = 1;
public const int GGO_GLYPH_INDEX = 0x80;
public const int GGO_GRAY2_BITMAP = 4;
public const int GGO_GRAY4_BITMAP = 5;
public const int GGO_GRAY8_BITMAP = 6;
public const int GGO_METRICS = 0;
public const int GGO_NATIVE = 2;
public const int GM_ADVANCED = 2;
public const int GM_COMPATIBLE = 1;
public const int GM_LAST = 2;
public const int GRAY_BRUSH = 2;
public const int GREEK_CHARSET = 161;
public const int HALFTONE = 4;
public const int HANGEUL_CHARSET = 129;
public const int HEBREW_CHARSET = 177;
public const int HGDI_ERROR = 0xFFFF;
public const int HOLLOW_BRUSH = NULL_BRUSH;
public const int HORZRES = 8;
public const int HORZSIZE = 4;
public const int HS_API_MAX = 25;
public const int HS_BDIAGONAL = 3;
public const int HS_BDIAGONAL1 = 7;
public const int HS_CROSS = 4;
public const int HS_DENSE1 = 9;
public const int HS_DENSE2 = 10;
public const int HS_DENSE3 = 11;
public const int HS_DENSE4 = 12;
public const int HS_DENSE5 = 13;
public const int HS_DENSE6 = 14;
public const int HS_DENSE7 = 15;
public const int HS_DENSE8 = 16;
public const int HS_DIAGCROSS = 5;
public const int HS_DITHEREDBKCLR = 24;
public const int HS_DITHEREDCLR = 20;
public const int HS_DITHEREDTEXTCLR = 22;
public const int HS_FDIAGONAL = 2;
public const int HS_FDIAGONAL1 = 6;
public const int HS_HALFTONE = 18;
public const int HS_HORIZONTAL = 0;
public const int HS_NOSHADE = 17;
public const int HS_SOLID = 8;
public const int HS_SOLIDBKCLR = 23;
public const int HS_SOLIDCLR = 19;
public const int HS_SOLIDTEXTCLR = 21;
public const int HS_VERTICAL = 1;
public const int ICM_OFF = 1;
public const int ICM_ON = 2;
public const int ICM_QUERY = 3;
public const int ILLUMINANT_A = 1;
public const int ILLUMINANT_B = 2;
public const int ILLUMINANT_C = 3;
public const int ILLUMINANT_D50 = 4;
public const int ILLUMINANT_D55 = 5;
public const int ILLUMINANT_D65 = 6;
public const int ILLUMINANT_D75 = 7;
public const int ILLUMINANT_DAYLIGHT = ILLUMINANT_C;
public const int ILLUMINANT_DEVICE_DEFAULT = 0;
public const int ILLUMINANT_F2 = 8;
public const int ILLUMINANT_FLUORESCENT = ILLUMINANT_F2;
public const int ILLUMINANT_MAX_INDEX = ILLUMINANT_F2;
public const int ILLUMINANT_NTSC = ILLUMINANT_C;
public const int ILLUMINANT_TUNGSTEN = ILLUMINANT_A;
public const int JOHAB_CHARSET = 130;
public const int LC_INTERIORS = 128;
public const int LC_MARKER = 4;
public const int LC_NONE = 0;
public const int LC_POLYLINE = 2;
public const int LC_POLYMARKER = 8;
public const int LC_STYLED = 32;
public const int LC_WIDE = 16;
public const int LC_WIDESTYLED = 64;
public const int LF_FACESIZE = 32;
public const int LF_FULLFACESIZE = 64;
public const int LINECAPS = 30;
public const int LOGPIXELSX = 88;
public const int LOGPIXELSY = 90;
public const int LTGRAY_BRUSH = 1;
public const int MAC_CHARSET = 77;
public const int MAXSTRETCHBLTMODE = 4;
public const int MERGECOPY = 0xC000CA;
public const int MERGEPAINT = 0xBB0226;
public const int META_ANIMATEPALETTE = 0x436;
public const int META_ARC = 0x817;
public const int META_BITBLT = 0x922;
public const int META_CHORD = 0x830;
public const int META_CREATEBRUSHINDIRECT = 0x2FC;
public const int META_CREATEFONTINDIRECT = 0x2FB;
public const int META_CREATEPALETTE = 0xF7;
public const int META_CREATEPATTERNBRUSH = 0x1F9;
public const int META_CREATEPENINDIRECT = 0x2FA;
public const int META_CREATEREGION = 0x6FF;
public const int META_DELETEOBJECT = 0x1F0;
public const int META_DIBBITBLT = 0x940;
public const int META_DIBCREATEPATTERNBRUSH = 0x142;
public const int META_DIBSTRETCHBLT = 0xB41;
public const int META_ELLIPSE = 0x418;
public const int META_ESCAPE = 0x626;
public const int META_EXCLUDECLIPRECT = 0x415;
public const int META_EXTFLOODFILL = 0x548;
public const int META_EXTTEXTOUT = 0xA32;
public const int META_FILLREGION = 0x228;
public const int META_FLOODFILL = 0x419;
public const int META_FRAMEREGION = 0x429;
public const int META_INTERSECTCLIPRECT = 0x416;
public const int META_INVERTREGION = 0x12A;
public const int META_LINETO = 0x213;
public const int META_MOVETO = 0x214;
public const int META_OFFSETCLIPRGN = 0x220;
public const int META_OFFSETVIEWPORTORG = 0x211;
public const int META_OFFSETWINDOWORG = 0x20F;
public const int META_PAINTREGION = 0x12B;
public const int META_PATBLT = 0x61D;
public const int META_PIE = 0x81A;
public const int META_POLYGON = 0x324;
public const int META_POLYLINE = 0x325;
public const int META_POLYPOLYGON = 0x538;
public const int META_REALIZEPALETTE = 0x35;
public const int META_RECTANGLE = 0x41B;
public const int META_RESIZEPALETTE = 0x139;
public const int META_RESTOREDC = 0x127;
public const int META_ROUNDRECT = 0x61C;
public const int META_SAVEDC = 0x1E;
public const int META_SCALEVIEWPORTEXT = 0x412;
public const int META_SCALEWINDOWEXT = 0x410;
public const int META_SELECTCLIPREGION = 0x12C;
public const int META_SELECTOBJECT = 0x12D;
public const int META_SELECTPALETTE = 0x234;
public const int META_SETBKCOLOR = 0x201;
public const int META_SETBKMODE = 0x102;
public const int META_SETDIBTODEV = 0xD33;
public const int META_SETMAPMODE = 0x103;
public const int META_SETMAPPERFLAGS = 0x231;
public const int META_SETPALENTRIES = 0x37;
public const int META_SETPIXEL = 0x41F;
public const int META_SETPOLYFILLMODE = 0x106;
public const int META_SETRELABS = 0x105;
public const int META_SETROP2 = 0x104;
public const int META_SETSTRETCHBLTMODE = 0x107;
public const int META_SETTEXTALIGN = 0x12E;
public const int META_SETTEXTCHAREXTRA = 0x108;
public const int META_SETTEXTCOLOR = 0x209;
public const int META_SETTEXTJUSTIFICATION = 0x20A;
public const int META_SETVIEWPORTEXT = 0x20E;
public const int META_SETVIEWPORTORG = 0x20D;
public const int META_SETWINDOWEXT = 0x20C;
public const int META_SETWINDOWORG = 0x20B;
public const int META_STRETCHBLT = 0xB23;
public const int META_STRETCHDIB = 0xF43;
public const int META_TEXTOUT = 0x521;
public const int MFCOMMENT = 15;
public const int MM_ANISOTROPIC = 8;
public const int MM_HIENGLISH = 5;
public const int MM_HIMETRIC = 3;
public const int MM_ISOTROPIC = 7;
public const int MM_LOENGLISH = 4;
public const int MM_LOMETRIC = 2;
public const int MM_MAX = MM_ANISOTROPIC;
public const int MM_MAX_FIXEDSCALE = MM_TWIPS;
public const int MM_MIN = MM_TEXT;
public const int MM_TEXT = 1;
public const int MM_TWIPS = 6;
public const int MONO_FONT = 8;
public const int MOUSETRAILS = 39;
public const int MWT_IDENTITY = 1;
public const int MWT_LEFTMULTIPLY = 2;
public const int MWT_MAX = MWT_RIGHTMULTIPLY;
public const int MWT_MIN = MWT_IDENTITY;
public const int MWT_RIGHTMULTIPLY = 3;
public const int NEWFRAME = 1;
public const int NEXTBAND = 3;
public const int NOTSRCCOPY = 0x330008;
public const int NOTSRCERASE = 0x1100A6;
public const int NTM_BOLD = 0x20;
public const int NTM_ITALIC = 0x1;
public const int NTM_REGULAR = 0x40;
public const int NULLREGION = 1;
public const int NULL_BRUSH = 5;
public const int NULL_PEN = 8;
public const int NUMBRUSHES = 16;
public const int NUMCOLORS = 24;
public const int NUMFONTS = 22;
public const int NUMMARKERS = 20;
public const int NUMPENS = 18;
public const int NUMRESERVED = 106;
public const int OBJ_BITMAP = 7;
public const int OBJ_BRUSH = 2;
public const int OBJ_DC = 3;
public const int OBJ_ENHMETADC = 12;
public const int OBJ_ENHMETAFILE = 13;
public const int OBJ_EXTPEN = 11;
public const int OBJ_FONT = 6;
public const int OBJ_MEMDC = 10;
public const int OBJ_METADC = 4;
public const int OBJ_METAFILE = 9;
public const int OBJ_PAL = 5;
public const int OBJ_PEN = 1;
public const int OBJ_REGION = 8;
public const int OEM_CHARSET = 255;
public const int OEM_FIXED_FONT = 10;
public const int OPAQUE = 2;
public const int OPENCHANNEL = 4110;
public const int OUT_CHARACTER_PRECIS = 2;
public const int OUT_DEFAULT_PRECIS = 0;
public const int OUT_DEVICE_PRECIS = 5;
public const int OUT_OUTLINE_PRECIS = 8;
public const int OUT_RASTER_PRECIS = 6;
public const int OUT_STRING_PRECIS = 1;
public const int OUT_STROKE_PRECIS = 3;
public const int OUT_TT_ONLY_PRECIS = 7;
public const int OUT_TT_PRECIS = 4;
public const int PANOSE_COUNT = 10;
public const int PAN_ANY = 0;
public const int PAN_ARMSTYLE_INDEX = 6;
public const int PAN_BENT_ARMS_DOUBLE_SERIF = 11;
public const int PAN_BENT_ARMS_HORZ = 7;
public const int PAN_BENT_ARMS_SINGLE_SERIF = 10;
public const int PAN_BENT_ARMS_VERT = 9;
public const int PAN_BENT_ARMS_WEDGE = 8;
public const int PAN_CONTRAST_HIGH = 8;
public const int PAN_CONTRAST_INDEX = 4;
public const int PAN_CONTRAST_LOW = 4;
public const int PAN_CONTRAST_MEDIUM = 6;
public const int PAN_CONTRAST_MEDIUM_HIGH = 7;
public const int PAN_CONTRAST_MEDIUM_LOW = 5;
public const int PAN_CONTRAST_NONE = 2;
public const int PAN_CONTRAST_VERY_HIGH = 9;
public const int PAN_CONTRAST_VERY_LOW = 3;
public const int PAN_CULTURE_LATIN = 0;
public const int PAN_FAMILYTYPE_INDEX = 0;
public const int PAN_FAMILY_DECORATIVE = 4;
public const int PAN_FAMILY_PICTORIAL = 5;
public const int PAN_FAMILY_SCRIPT = 3;
public const int PAN_FAMILY_TEXT_DISPLAY = 2;
public const int PAN_LETTERFORM_INDEX = 7;
public const int PAN_LETT_NORMAL_BOXED = 4;
public const int PAN_LETT_NORMAL_CONTACT = 2;
public const int PAN_LETT_NORMAL_FLATTENED = 5;
public const int PAN_LETT_NORMAL_OFF_CENTER = 7;
public const int PAN_LETT_NORMAL_ROUNDED = 6;
public const int PAN_LETT_NORMAL_SQUARE = 8;
public const int PAN_LETT_NORMAL_WEIGHTED = 3;
public const int PAN_LETT_OBLIQUE_BOXED = 11;
public const int PAN_LETT_OBLIQUE_CONTACT = 9;
public const int PAN_LETT_OBLIQUE_FLATTENED = 12;
public const int PAN_LETT_OBLIQUE_OFF_CENTER = 14;
public const int PAN_LETT_OBLIQUE_ROUNDED = 13;
public const int PAN_LETT_OBLIQUE_SQUARE = 15;
public const int PAN_LETT_OBLIQUE_WEIGHTED = 10;
public const int PAN_MIDLINE_CONSTANT_POINTED = 9;
public const int PAN_MIDLINE_CONSTANT_SERIFED = 10;
public const int PAN_MIDLINE_CONSTANT_TRIMMED = 8;
public const int PAN_MIDLINE_HIGH_POINTED = 6;
public const int PAN_MIDLINE_HIGH_SERIFED = 7;
public const int PAN_MIDLINE_HIGH_TRIMMED = 5;
public const int PAN_MIDLINE_INDEX = 8;
public const int PAN_MIDLINE_LOW_POINTED = 12;
public const int PAN_MIDLINE_LOW_SERIFED = 13;
public const int PAN_MIDLINE_LOW_TRIMMED = 11;
public const int PAN_MIDLINE_STANDARD_POINTED = 3;
public const int PAN_MIDLINE_STANDARD_SERIFED = 4;
public const int PAN_MIDLINE_STANDARD_TRIMMED = 2;
public const int PAN_NO_FIT = 1;
public const int PAN_PROPORTION_INDEX = 3;
public const int PAN_PROP_CONDENSED = 6;
public const int PAN_PROP_EVEN_WIDTH = 4;
public const int PAN_PROP_EXPANDED = 5;
public const int PAN_PROP_MODERN = 3;
public const int PAN_PROP_MONOSPACED = 9;
public const int PAN_PROP_OLD_STYLE = 2;
public const int PAN_PROP_VERY_CONDENSED = 8;
public const int PAN_PROP_VERY_EXPANDED = 7;
public const int PAN_SERIFSTYLE_INDEX = 1;
public const int PAN_SERIF_BONE = 8;
public const int PAN_SERIF_COVE = 2;
public const int PAN_SERIF_EXAGGERATED = 9;
public const int PAN_SERIF_FLARED = 14;
public const int PAN_SERIF_NORMAL_SANS = 11;
public const int PAN_SERIF_OBTUSE_COVE = 3;
public const int PAN_SERIF_OBTUSE_SANS = 12;
public const int PAN_SERIF_OBTUSE_SQUARE_COVE = 5;
public const int PAN_SERIF_PERP_SANS = 13;
public const int PAN_SERIF_ROUNDED = 15;
public const int PAN_SERIF_SQUARE = 6;
public const int PAN_SERIF_SQUARE_COVE = 4;
public const int PAN_SERIF_THIN = 7;
public const int PAN_SERIF_TRIANGLE = 10;
public const int PAN_STRAIGHT_ARMS_DOUBLE_SERIF = 6;
public const int PAN_STRAIGHT_ARMS_HORZ = 2;
public const int PAN_STRAIGHT_ARMS_SINGLE_SERIF = 5;
public const int PAN_STRAIGHT_ARMS_VERT = 4;
public const int PAN_STRAIGHT_ARMS_WEDGE = 3;
public const int PAN_STROKEVARIATION_INDEX = 5;
public const int PAN_STROKE_GRADUAL_DIAG = 2;
public const int PAN_STROKE_GRADUAL_HORZ = 5;
public const int PAN_STROKE_GRADUAL_TRAN = 3;
public const int PAN_STROKE_GRADUAL_VERT = 4;
public const int PAN_STROKE_INSTANT_VERT = 8;
public const int PAN_STROKE_RAPID_HORZ = 7;
public const int PAN_STROKE_RAPID_VERT = 6;
public const int PAN_WEIGHT_BLACK = 10;
public const int PAN_WEIGHT_BOLD = 8;
public const int PAN_WEIGHT_BOOK = 5;
public const int PAN_WEIGHT_DEMI = 7;
public const int PAN_WEIGHT_HEAVY = 9;
public const int PAN_WEIGHT_INDEX = 2;
public const int PAN_WEIGHT_LIGHT = 3;
public const int PAN_WEIGHT_MEDIUM = 6;
public const int PAN_WEIGHT_NORD = 11;
public const int PAN_WEIGHT_THIN = 4;
public const int PAN_WEIGHT_VERY_LIGHT = 2;
public const int PAN_XHEIGHT_CONSTANT_LARGE = 4;
public const int PAN_XHEIGHT_CONSTANT_SMALL = 2;
public const int PAN_XHEIGHT_CONSTANT_STD = 3;
public const int PAN_XHEIGHT_DUCKING_LARGE = 7;
public const int PAN_XHEIGHT_DUCKING_SMALL = 5;
public const int PAN_XHEIGHT_DUCKING_STD = 6;
public const int PAN_XHEIGHT_INDEX = 9;
public const int PASSTHROUGH = 19;
public const int PATCOPY = 0xF00021;
public const int PATINVERT = 0x5A0049;
public const int PATPAINT = 0xFB0A09;
public const int PC_EXPLICIT = 0x2;
public const int PC_INTERIORS = 128;
public const int PC_NOCOLLAPSE = 0x4;
public const int PC_NONE = 0;
public const int PC_POLYGON = 1;
public const int PC_RECTANGLE = 2;
public const int PC_RESERVED = 0x1;
public const int PC_SCANLINE = 8;
public const int PC_STYLED = 32;
public const int PC_TRAPEZOID = 4;
public const int PC_WIDE = 16;
public const int PC_WIDESTYLED = 64;
public const int PC_WINDPOLYGON = 4;
public const int PDEVICESIZE = 26;
public const int PHYSICALHEIGHT = 111;
public const int PHYSICALOFFSETX = 112;
public const int PHYSICALOFFSETY = 113;
public const int PHYSICALWIDTH = 110;
public const int PLANES = 14;
public const int POLYFILL_LAST = 2;
public const int POLYGONALCAPS = 32;
public const int POSTSCRIPT_DATA = 37;
public const int POSTSCRIPT_IGNORE = 38;
public const int POSTSCRIPT_PASSTHROUGH = 4115;
public const int PROOF_QUALITY = 2;
public const int PR_JOBSTATUS = 0x0;
public const int PS_ALTERNATE = 8;
public const int PS_COSMETIC = 0x0;
public const int PS_DASH = 1;
public const int PS_DASHDOT = 3;
public const int PS_DASHDOTDOT = 4;
public const int PS_DOT = 2;
public const int PS_ENDCAP_FLAT = 0x200;
public const int PS_ENDCAP_MASK = 0xF00;
public const int PS_ENDCAP_ROUND = 0x0;
public const int PS_ENDCAP_SQUARE = 0x100;
public const int PS_GEOMETRIC = 0x10000;
public const int PS_INSIDEFRAME = 6;
public const int PS_JOIN_BEVEL = 0x1000;
public const int PS_JOIN_MASK = 0xF000;
public const int PS_JOIN_MITER = 0x2000;
public const int PS_JOIN_ROUND = 0x0;
public const int PS_NULL = 5;
public const int PS_SOLID = 0;
public const int PS_STYLE_MASK = 0xF;
public const int PS_TYPE_MASK = 0xF0000;
public const int PS_USERSTYLE = 7;
public const int PT_BEZIERTO = 0x4;
public const int PT_CLOSEFIGURE = 0x1;
public const int PT_LINETO = 0x2;
public const int PT_MOVETO = 0x6;
public const int QUERYESCSUPPORT = 8;
public const int R2_BLACK = 1;
public const int R2_COPYPEN = 13;
public const int R2_LAST = 16;
public const int R2_MASKNOTPEN = 3;
public const int R2_MASKPEN = 9;
public const int R2_MASKPENNOT = 5;
public const int R2_MERGENOTPEN = 12;
public const int R2_MERGEPEN = 15;
public const int R2_MERGEPENNOT = 14;
public const int R2_NOP = 11;
public const int R2_NOT = 6;
public const int R2_NOTCOPYPEN = 4;
public const int R2_NOTMASKPEN = 8;
public const int R2_NOTMERGEPEN = 2;
public const int R2_NOTXORPEN = 10;
public const int R2_WHITE = 16;
public const int R2_XORPEN = 7;
public const int RASTERCAPS = 38;
public const int RASTER_FONTTYPE = 0x1;
public const int RC_BANDING = 2;
public const int RC_BIGFONT = 0x400;
public const int RC_BITBLT = 1;
public const int RC_BITMAP64 = 8;
public const int RC_DEVBITS = 0x8000;
public const int RC_DIBTODEV = 0x200;
public const int RC_DI_BITMAP = 0x80;
public const int RC_FLOODFILL = 0x1000;
public const int RC_GDI20_OUTPUT = 0x10;
public const int RC_GDI20_STATE = 0x20;
public const int RC_NONE = 0;
public const int RC_OP_DX_OUTPUT = 0x4000;
public const int RC_PALETTE = 0x100;
public const int RC_SAVEBITMAP = 0x40;
public const int RC_SCALING = 4;
public const int RC_STRETCHBLT = 0x800;
public const int RC_STRETCHDIB = 0x2000;
public const int RDH_RECTANGLES = 1;
public const int REFERENCE_BLACK_MAX = 4000;
public const int REFERENCE_BLACK_MIN = 0;
public const int REFERENCE_WHITE_MAX = 10000;
public const int REFERENCE_WHITE_MIN = 6000;
public const int RELATIVE = 2;
public const int RESTORE_CTM = 4100;
public const int RGB_GAMMA_MAX = 65000;
public const int RGB_GAMMA_MIN = 2500;
public const int RGN_AND = 1;
public const int RGN_COPY = 5;
public const int RGN_DIFF = 4;
public const int RGN_MAX = RGN_COPY;
public const int RGN_MIN = RGN_AND;
public const int RGN_OR = 2;
public const int RGN_XOR = 3;
public const int RUSSIAN_CHARSET = 204;
public const int SAVE_CTM = 4101;
public const int SCALINGFACTORX = 114;
public const int SCALINGFACTORY = 115;
public const int SELECTPAPERSOURCE = 18;
public const int SETABORTPROC = 9;
public const int SETALLJUSTVALUES = 771;
public const int SETCHARSET = 772;
public const int SETCOLORTABLE = 4;
public const int SETCOPYCOUNT = 17;
public const int SETDIBSCALING = 32;
public const int SETKERNTRACK = 770;
public const int SETLINECAP = 21;
public const int SETLINEJOIN = 22;
public const int SET_ARC_DIRECTION = 4102;
public const int SET_BACKGROUND_COLOR = 4103;
public const int SET_BOUNDS = 4109;
public const int SET_CLIP_BOX = 4108;
public const int SET_MIRROR_MODE = 4110;
public const int SET_POLY_MODE = 4104;
public const int SET_SCREEN_ANGLE = 4105;
public const int SET_SPREAD = 4106;
public const int SHIFTJIS_CHARSET = 128;
public const int SIMPLEREGION = 2;
public const int SIZEPALETTE = 104;
public const int SP_APPABORT = (-2);
public const int SP_ERROR = (-1);
public const int SP_NOTREPORTED = 0x4000;
public const int SP_OUTOFDISK = (-4);
public const int SP_OUTOFMEMORY = (-5);
public const int SP_USERABORT = (-3);
public const int SRCAND = 0x8800C6;
public const int SRCCOPY = 0xCC0020;
public const int SRCERASE = 0x440328;
public const int SRCINVERT = 0x660046;
public const int SRCPAINT = 0xEE0086;
public const int STOCK_LAST = 16;
public const int STRETCH_ANDSCANS = 1;
public const int STRETCH_DELETESCANS = 3;
public const int STRETCH_HALFTONE = 4;
public const int STRETCH_ORSCANS = 2;
public const int SYMBOL_CHARSET = 2;
public const int SYSPAL_ERROR = 0;
public const int SYSPAL_NOSTATIC = 2;
public const int SYSPAL_STATIC = 1;
public const int SYSTEM_FIXED_FONT = 16;
public const int SYSTEM_FONT = 13;
public const int SetMiterLimitC = 23;
public const int StartDocC = 10;
public const int StretchBltC = 2048;
public const int TA_BASELINE = 24;
public const int TA_BOTTOM = 8;
public const int TA_CENTER = 6;
public const int TA_LEFT = 0;
public const int TA_MASK = (TA_BASELINE + TA_CENTER + TA_UPDATECP);
public const int TA_NOUPDATECP = 0;
public const int TA_RIGHT = 2;
public const int TA_TOP = 0;
public const int TA_UPDATECP = 1;
public const int TCI_SRCCHARSET = 1;
public const int TCI_SRCCODEPAGE = 2;
public const int TCI_SRCFONTSIG = 3;
public const int TC_CP_STROKE = 0x4;
public const int TC_CR_90 = 0x8;
public const int TC_CR_ANY = 0x10;
public const int TC_EA_DOUBLE = 0x200;
public const int TC_IA_ABLE = 0x400;
public const int TC_OP_CHARACTER = 0x1;
public const int TC_OP_STROKE = 0x2;
public const int TC_RA_ABLE = 0x2000;
public const int TC_RESERVED = 0x8000;
public const int TC_SA_CONTIN = 0x100;
public const int TC_SA_DOUBLE = 0x40;
public const int TC_SA_INTEGER = 0x80;
public const int TC_SCROLLBLT = 0x10000;
public const int TC_SF_X_YINDEP = 0x20;
public const int TC_SO_ABLE = 0x1000;
public const int TC_UA_ABLE = 0x800;
public const int TC_VA_ABLE = 0x4000;
public const int TECHNOLOGY = 2;
public const int TEXTCAPS = 34;
public const int THAI_CHARSET = 222;
public const int TMPF_DEVICE = 0x8;
public const int TMPF_FIXED_PITCH = 0x1;
public const int TMPF_TRUETYPE = 0x4;
public const int TMPF_VECTOR = 0x2;
public const int TRANSFORM_CTM = 4107;
public const int TRANSPARENT = 1;
public const int TRUETYPE_FONTTYPE = 0x4;
public const int TT_AVAILABLE = 0x1;
public const int TT_ENABLED = 0x2;
public const int TT_POLYGON_TYPE = 24;
public const int TT_PRIM_LINE = 1;
public const int TT_PRIM_QSPLINE = 2;
public const int TURKISH_CHARSET = 162;
public const int VARIABLE_PITCH = 2;
public const int VERTRES = 10;
public const int VERTSIZE = 6;
public const int VTA_BASELINE = TA_BASELINE;
public const int VTA_BOTTOM = TA_RIGHT;
public const int VTA_CENTER = TA_CENTER;
public const int VTA_LEFT = TA_BOTTOM;
public const int VTA_RIGHT = TA_TOP;
public const int VTA_TOP = TA_LEFT;
public const int WHITENESS = 0xFF0062;
public const int WHITEONBLACK = 2;
public const int WHITE_BRUSH = 0;
public const int WHITE_PEN = 6;
public const int WINDING = 2;
}
}


using System;
namespace Win32
{
public abstract class ERROR
{
public const int CACHE_E_FIRST = unchecked((int) 0x80040170);
public const int CACHE_E_LAST = unchecked((int) 0x8004017F);
public const int CACHE_E_NOCACHE_UPDATED = unchecked((int) 0x80040170);
public const int CACHE_S_FIRST = 0x40170;
public const int CACHE_S_FORMATETC_NOTSUPPORTED = 0x40170;
public const int CACHE_S_LAST = 0x4017F;
public const int CACHE_S_SAMECACHE = 0x40171;
public const int CACHE_S_SOMECACHES_NOTUPDATED = 0x40172;
public const int CLASSFACTORY_E_FIRST = unchecked((int) 0x80040110);
public const int CLASSFACTORY_E_LAST = unchecked((int) 0x8004011F);
public const int CLASSFACTORY_S_FIRST = 0x40110;
public const int CLASSFACTORY_S_LAST = 0x4011F;
public const int CLASS_E_CLASSNOTAVAILABLE = unchecked((int) 0x80040111);
public const int CLASS_E_NOAGGREGATION = unchecked((int) 0x80040110);
public const int CLIENTSITE_E_FIRST = unchecked((int) 0x80040190);
public const int CLIENTSITE_E_LAST = unchecked((int) 0x8004019F);
public const int CLIENTSITE_S_FIRST = 0x40190;
public const int CLIENTSITE_S_LAST = 0x4019F;
public const int CLIPBRD_E_BAD_DATA = unchecked((int) 0x800401D3);
public const int CLIPBRD_E_CANT_CLOSE = unchecked((int) 0x800401D4);
public const int CLIPBRD_E_CANT_EMPTY = unchecked((int) 0x800401D1);
public const int CLIPBRD_E_CANT_OPEN = unchecked((int) 0x800401D0);
public const int CLIPBRD_E_CANT_SET = unchecked((int) 0x800401D2);
public const int CLIPBRD_E_FIRST = unchecked((int) 0x800401D0);
public const int CLIPBRD_E_LAST = unchecked((int) 0x800401DF);
public const int CLIPBRD_S_FIRST = 0x401D0;
public const int CLIPBRD_S_LAST = 0x401DF;
public const int CONVERT10_E_FIRST = unchecked((int) 0x800401C0);
public const int CONVERT10_E_LAST = unchecked((int) 0x800401CF);
public const int CONVERT10_E_OLESTREAM_BITMAP_TO_DIB = unchecked((int) 0x800401C3);
public const int CONVERT10_E_OLESTREAM_FMT = unchecked((int) 0x800401C2);
public const int CONVERT10_E_OLESTREAM_GET = unchecked((int) 0x800401C0);
public const int CONVERT10_E_OLESTREAM_PUT = unchecked((int) 0x800401C1);
public const int CONVERT10_E_STG_DIB_TO_BITMAP = unchecked((int) 0x800401C6);
public const int CONVERT10_E_STG_FMT = unchecked((int) 0x800401C4);
public const int CONVERT10_E_STG_NO_STD_STREAM = unchecked((int) 0x800401C5);
public const int CONVERT10_S_FIRST = 0x401C0;
public const int CONVERT10_S_LAST = 0x401CF;
public const int CONVERT10_S_NO_PRESENTATION = 0x401C0;
public const int CO_E_ALREADYINITIALIZED = unchecked((int) 0x800401F1);
public const int CO_E_APPDIDNTREG = unchecked((int) 0x800401FE);
public const int CO_E_APPNOTFOUND = unchecked((int) 0x800401F5);
public const int CO_E_APPSINGLEUSE = unchecked((int) 0x800401F6);
public const int CO_E_BAD_PATH = unchecked((int) 0x80080004);
public const int CO_E_CANTDETERMINECLASS = unchecked((int) 0x800401F2);
public const int CO_E_CLASSSTRING = unchecked((int) 0x800401F3);
public const int CO_E_CLASS_CREATE_FAILED = unchecked((int) 0x80080001);
public const int CO_E_DLLNOTFOUND = unchecked((int) 0x800401F8);
public const int CO_E_ERRORINAPP = unchecked((int) 0x800401F7);
public const int CO_E_ERRORINDLL = unchecked((int) 0x800401F9);
public const int CO_E_FIRST = unchecked((int) 0x800401F0);
public const int CO_E_IIDSTRING = unchecked((int) 0x800401F4);
public const int CO_E_INIT_CLASS_CACHE = unchecked((int) 0x80004009);
public const int CO_E_INIT_MEMORY_ALLOCATOR = unchecked((int) 0x80004008);
public const int CO_E_INIT_ONLY_SINGLE_THREADED = unchecked((int) 0x80004012);
public const int CO_E_INIT_RPC_CHANNEL = unchecked((int) 0x8000400A);
public const int CO_E_INIT_SCM_EXEC_FAILURE = unchecked((int) 0x80004011);
public const int CO_E_INIT_SCM_FILE_MAPPING_EXISTS = unchecked((int) 0x8000400F);
public const int CO_E_INIT_SCM_MAP_VIEW_OF_FILE = unchecked((int) 0x80004010);
public const int CO_E_INIT_SCM_MUTEX_EXISTS = unchecked((int) 0x8000400E);
public const int CO_E_INIT_SHARED_ALLOCATOR = unchecked((int) 0x80004007);
public const int CO_E_INIT_TLS = unchecked((int) 0x80004006);
public const int CO_E_INIT_TLS_CHANNEL_CONTROL = unchecked((int) 0x8000400C);
public const int CO_E_INIT_TLS_SET_CHANNEL_CONTROL = unchecked((int) 0x8000400B);
public const int CO_E_INIT_UNACCEPTED_USER_ALLOCATOR = unchecked((int) 0x8000400D);
public const int CO_E_LAST = unchecked((int) 0x800401FF);
public const int CO_E_NOTINITIALIZED = unchecked((int) 0x800401F0);
public const int CO_E_OBJISREG = unchecked((int) 0x800401FC);
public const int CO_E_OBJNOTCONNECTED = unchecked((int) 0x800401FD);
public const int CO_E_OBJNOTREG = unchecked((int) 0x800401FB);
public const int CO_E_OBJSRV_RPC_FAILURE = unchecked((int) 0x80080006);
public const int CO_E_RELEASED = unchecked((int) 0x800401FF);
public const int CO_E_SCM_ERROR = unchecked((int) 0x80080002);
public const int CO_E_SCM_RPC_FAILURE = unchecked((int) 0x80080003);
public const int CO_E_SERVER_EXEC_FAILURE = unchecked((int) 0x80080005);
public const int CO_E_SERVER_STOPPING = unchecked((int) 0x80080008);
public const int CO_E_WRONGOSFORAPP = unchecked((int) 0x800401FA);
public const int CO_S_FIRST = 0x401F0;
public const int CO_S_LAST = 0x401FF;
public const int DATA_E_FIRST = unchecked((int) 0x80040130);
public const int DATA_E_LAST = unchecked((int) 0x8004013F);
public const int DATA_S_FIRST = 0x40130;
public const int DATA_S_LAST = 0x4013F;
public const int DATA_S_SAMEFORMATETC = 0x40130;
public const int DISP_E_ARRAYISLOCKED = unchecked((int) 0x8002000D);
public const int DISP_E_BADCALLEE = unchecked((int) 0x80020010);
public const int DISP_E_BADINDEX = unchecked((int) 0x8002000B);
public const int DISP_E_BADPARAMCOUNT = unchecked((int) 0x8002000E);
public const int DISP_E_BADVARTYPE = unchecked((int) 0x80020008);
public const int DISP_E_EXCEPTION = unchecked((int) 0x80020009);
public const int DISP_E_MEMBERNOTFOUND = unchecked((int) 0x80020003);
public const int DISP_E_NONAMEDARGS = unchecked((int) 0x80020007);
public const int DISP_E_NOTACOLLECTION = unchecked((int) 0x80020011);
public const int DISP_E_OVERFLOW = unchecked((int) 0x8002000A);
public const int DISP_E_PARAMNOTFOUND = unchecked((int) 0x80020004);
public const int DISP_E_PARAMNOTOPTIONAL = unchecked((int) 0x8002000F);
public const int DISP_E_TYPEMISMATCH = unchecked((int) 0x80020005);
public const int DISP_E_UNKNOWNINTERFACE = unchecked((int) 0x80020001);
public const int DISP_E_UNKNOWNLCID = unchecked((int) 0x8002000C);
public const int DISP_E_UNKNOWNNAME = unchecked((int) 0x80020006);
public const int DRAGDROP_E_ALREADYREGISTERED = unchecked((int) 0x80040101);
public const int DRAGDROP_E_FIRST = unchecked((int) 0x80040100);
public const int DRAGDROP_E_INVALIDHWND = unchecked((int) 0x80040102);
public const int DRAGDROP_E_LAST = unchecked((int) 0x8004010F);
public const int DRAGDROP_E_NOTREGISTERED = unchecked((int) 0x80040100);
public const int DRAGDROP_S_CANCEL = 0x40101;
public const int DRAGDROP_S_DROP = 0x40100;
public const int DRAGDROP_S_FIRST = 0x40100;
public const int DRAGDROP_S_LAST = 0x4010F;
public const int DRAGDROP_S_USEDEFAULTCURSORS = 0x40102;
public const int DV_E_CLIPFORMAT = unchecked((int) 0x8004006A);
public const int DV_E_DVASPECT = unchecked((int) 0x8004006B);
public const int DV_E_DVTARGETDEVICE = unchecked((int) 0x80040065);
public const int DV_E_DVTARGETDEVICE_SIZE = unchecked((int) 0x8004006C);
public const int DV_E_FORMATETC = unchecked((int) 0x80040064);
public const int DV_E_LINDEX = unchecked((int) 0x80040068);
public const int DV_E_NOIVIEWOBJECT = unchecked((int) 0x8004006D);
public const int DV_E_STATDATA = unchecked((int) 0x80040067);
public const int DV_E_STGMEDIUM = unchecked((int) 0x80040066);
public const int DV_E_TYMED = unchecked((int) 0x80040069);
public const int ENUM_E_FIRST = unchecked((int) 0x800401B0);
public const int ENUM_E_LAST = unchecked((int) 0x800401BF);
public const int ENUM_S_FIRST = 0x401B0;
public const int ENUM_S_LAST = 0x401BF;
public const int EPT_S_CANT_CREATE = 1899;
public const int EPT_S_CANT_PERFORM_OP = 1752;
public const int EPT_S_INVALID_ENTRY = 1751;
public const int EPT_S_NOT_REGISTERED = 1753;
public const int ERROR_ACCESS_DENIED = 5;
public const int ERROR_ACCOUNT_DISABLED = 1331;
public const int ERROR_ACCOUNT_EXPIRED = 1793;
public const int ERROR_ACCOUNT_RESTRICTION = 1327;
public const int ERROR_ADAP_HDW_ERR = 57;
public const int ERROR_ALIAS_EXISTS = 1379;
public const int ERROR_ALLOTTED_SPACE_EXCEEDED = 1344;
public const int ERROR_ALREADY_ASSIGNED = 85;
public const int ERROR_ALREADY_EXISTS = 183;
public const int ERROR_ALREADY_RUNNING_LKG = 1074;
public const int ERROR_ALREADY_WAITING = 1904;
public const int ERROR_ARENA_TRASHED = 7;
public const int ERROR_ARITHMETIC_OVERFLOW = 534;
public const int ERROR_ATOMIC_LOCKS_NOT_SUPPORTED = 174;
public const int ERROR_AUTODATASEG_EXCEEDS_64k = 199;
public const int ERROR_BADDB = 1009;
public const int ERROR_BADKEY = 1010;
public const int ERROR_BAD_ARGUMENTS = 160;
public const int ERROR_BAD_COMMAND = 22;
public const int ERROR_BAD_DESCRIPTOR_FORMAT = 1361;
public const int ERROR_BAD_DEVICE = 1200;
public const int ERROR_BAD_DEV_TYPE = 66;
public const int ERROR_BAD_DRIVER = 2001;
public const int ERROR_BAD_DRIVER_LEVEL = 119;
public const int ERROR_BAD_ENVIRONMENT = 10;
public const int ERROR_BAD_EXE_FORMAT = 193;
public const int ERROR_BAD_FORMAT = 11;
public const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;
public const int ERROR_BAD_INHERITANCE_ACL = 1340;
public const int ERROR_BAD_LENGTH = 24;
public const int ERROR_BAD_LOGON_SESSION_STATE = 1365;
public const int ERROR_BAD_NETPATH = 53;
public const int ERROR_BAD_NET_NAME = 67;
public const int ERROR_BAD_NET_RESP = 58;
public const int ERROR_BAD_PATHNAME = 161;
public const int ERROR_BAD_PIPE = 230;
public const int ERROR_BAD_PROFILE = 1206;
public const int ERROR_BAD_PROVIDER = 1204;
public const int ERROR_BAD_REM_ADAP = 60;
public const int ERROR_BAD_THREADID_ADDR = 159;
public const int ERROR_BAD_TOKEN_TYPE = 1349;
public const int ERROR_BAD_UNIT = 20;
public const int ERROR_BAD_USERNAME = 2202;
public const int ERROR_BAD_VALIDATION_CLASS = 1348;
public const int ERROR_BEGINNING_OF_MEDIA = 1102;
public const int ERROR_BOOT_ALREADY_ACCEPTED = 1076;
public const int ERROR_BROKEN_PIPE = 109;
public const int ERROR_BUFFER_OVERFLOW = 111;
public const int ERROR_BUSY = 170;
public const int ERROR_BUSY_DRIVE = 142;
public const int ERROR_BUS_RESET = 1111;
public const int ERROR_CALL_NOT_IMPLEMENTED = 120;
public const int ERROR_CANCEL_VIOLATION = 173;
public const int ERROR_CANNOT_COPY = 266;
public const int ERROR_CANNOT_FIND_WND_CLASS = 1407;
public const int ERROR_CANNOT_IMPERSONATE = 1368;
public const int ERROR_CANNOT_MAKE = 82;
public const int ERROR_CANNOT_OPEN_PROFILE = 1205;
public const int ERROR_CANTOPEN = 1011;
public const int ERROR_CANTREAD = 1012;
public const int ERROR_CANTWRITE = 1013;
public const int ERROR_CANT_ACCESS_DOMAIN_INFO = 1351;
public const int ERROR_CANT_DISABLE_MANDATORY = 1310;
public const int ERROR_CANT_OPEN_ANONYMOUS = 1347;
public const int ERROR_CAN_NOT_COMPLETE = 1003;
public const int ERROR_CAN_NOT_DEL_LOCAL_WINS = 4001;
public const int ERROR_CHILD_MUST_BE_VOLATILE = 1021;
public const int ERROR_CHILD_NOT_COMPLETE = 129;
public const int ERROR_CHILD_WINDOW_MENU = 1436;
public const int ERROR_CIRCULAR_DEPENDENCY = 1059;
public const int ERROR_CLASS_ALREADY_EXISTS = 1410;
public const int ERROR_CLASS_DOES_NOT_EXIST = 1411;
public const int ERROR_CLASS_HAS_WINDOWS = 1412;
public const int ERROR_CLIPBOARD_NOT_OPEN = 1418;
public const int ERROR_CLIPPING_NOT_SUPPORTED = 2005;
public const int ERROR_CONNECTION_UNAVAIL = 1201;
public const int ERROR_CONTROL_ID_NOT_FOUND = 1421;
public const int ERROR_COUNTER_TIMEOUT = 1121;
public const int ERROR_CRC = 23;
public const int ERROR_CURRENT_DIRECTORY = 16;
public const int ERROR_DATABASE_DOES_NOT_EXIST = 1065;
public const int ERROR_DC_NOT_FOUND = 1425;
public const int ERROR_DEPENDENT_SERVICES_RUNNING = 1051;
public const int ERROR_DESTROY_OBJECT_OF_OTHER_THREAD = 1435;
public const int ERROR_DEVICE_ALREADY_REMEMBERED = 1202;
public const int ERROR_DEVICE_IN_USE = 2404;
public const int ERROR_DEVICE_NOT_PARTITIONED = 1107;
public const int ERROR_DEV_NOT_EXIST = 55;
public const int ERROR_DIRECTORY = 267;
public const int ERROR_DIRECT_ACCESS_HANDLE = 130;
public const int ERROR_DIR_NOT_EMPTY = 145;
public const int ERROR_DIR_NOT_ROOT = 144;
public const int ERROR_DISCARDED = 157;
public const int ERROR_DISK_CHANGE = 107;
public const int ERROR_DISK_CORRUPT = 1393;
public const int ERROR_DISK_FULL = 112;
public const int ERROR_DISK_OPERATION_FAILED = 1127;
public const int ERROR_DISK_RECALIBRATE_FAILED = 1126;
public const int ERROR_DISK_RESET_FAILED = 1128;
public const int ERROR_DLL_INIT_FAILED = 1114;
public const int ERROR_DOMAIN_EXISTS = 1356;
public const int ERROR_DOMAIN_LIMIT_EXCEEDED = 1357;
public const int ERROR_DOMAIN_TRUST_INCONSISTENT = 1810;
public const int ERROR_DRIVE_LOCKED = 108;
public const int ERROR_DUPLICATE_SERVICE_NAME = 1078;
public const int ERROR_DUP_DOMAINNAME = 1221;
public const int ERROR_DUP_NAME = 52;
public const int ERROR_DYNLINK_FROM_INVALID_RING = 196;
public const int ERROR_EAS_DIDNT_FIT = 275;
public const int ERROR_EAS_NOT_SUPPORTED = 282;
public const int ERROR_EA_ACCESS_DENIED = 994;
public const int ERROR_EA_FILE_CORRUPT = 276;
public const int ERROR_EA_LIST_INCONSISTENT = 255;
public const int ERROR_EA_TABLE_FULL = 277;
public const int ERROR_END_OF_MEDIA = 1100;
public const int ERROR_ENVVAR_NOT_FOUND = 203;
public const int ERROR_EOM_OVERFLOW = 1129;
public const int ERROR_EVENTLOG_CANT_START = 1501;
public const int ERROR_EVENTLOG_FILE_CHANGED = 1503;
public const int ERROR_EVENTLOG_FILE_CORRUPT = 1500;
public const int ERROR_EXCEPTION_IN_SERVICE = 1064;
public const int ERROR_EXCL_SEM_ALREADY_OWNED = 101;
public const int ERROR_EXE_MARKED_INVALID = 192;
public const int ERROR_EXTENDED_ERROR = 1208;
public const int ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063;
public const int ERROR_FAIL_I24 = 83;
public const int ERROR_FILEMARK_DETECTED = 1101;
public const int ERROR_FILENAME_EXCED_RANGE = 206;
public const int ERROR_FILE_CORRUPT = 1392;
public const int ERROR_FILE_EXISTS = 80;
public const int ERROR_FILE_INVALID = 1006;
public const int ERROR_FILE_NOT_FOUND = 2;
public const int ERROR_FLOPPY_BAD_REGISTERS = 1125;
public const int ERROR_FLOPPY_ID_MARK_NOT_FOUND = 1122;
public const int ERROR_FLOPPY_UNKNOWN_ERROR = 1124;
public const int ERROR_FLOPPY_WRONG_CYLINDER = 1123;
public const int ERROR_FULLSCREEN_MODE = 1007;
public const int ERROR_FULL_BACKUP = 4004;
public const int ERROR_GENERIC_NOT_MAPPED = 1360;
public const int ERROR_GEN_FAILURE = 31;
public const int ERROR_GROUP_EXISTS = 1318;
public const int ERROR_HANDLE_DISK_FULL = 39;
public const int ERROR_HANDLE_EOF = 38;
public const int ERROR_HOOK_NEEDS_HMOD = 1428;
public const int ERROR_HOOK_NOT_INSTALLED = 1431;
public const int ERROR_HOTKEY_ALREADY_REGISTERED = 1409;
public const int ERROR_HOTKEY_NOT_REGISTERED = 1419;
public const int ERROR_HWNDS_HAVE_DIFF_PARENT = 1441;
public const int ERROR_ILL_FORMED_PASSWORD = 1324;
public const int ERROR_INC_BACKUP = 4003;
public const int ERROR_INFLOOP_IN_RELOC_CHAIN = 202;
public const int ERROR_INSUFFICIENT_BUFFER = 122;
public const int ERROR_INTERNAL_DB_CORRUPTION = 1358;
public const int ERROR_INTERNAL_DB_ERROR = 1383;
public const int ERROR_INTERNAL_ERROR = 1359;
public const int ERROR_INVALID_ACCEL_HANDLE = 1403;
public const int ERROR_INVALID_ACCESS = 12;
public const int ERROR_INVALID_ACCOUNT_NAME = 1315;
public const int ERROR_INVALID_ACL = 1336;
public const int ERROR_INVALID_ADDRESS = 487;
public const int ERROR_INVALID_AT_INTERRUPT_TIME = 104;
public const int ERROR_INVALID_BLOCK = 9;
public const int ERROR_INVALID_BLOCK_LENGTH = 1106;
public const int ERROR_INVALID_CATEGORY = 117;
public const int ERROR_INVALID_COMBOBOX_MESSAGE = 1422;
public const int ERROR_INVALID_COMPUTERNAME = 1210;
public const int ERROR_INVALID_CURSOR_HANDLE = 1402;
public const int ERROR_INVALID_DATA = 13;
public const int ERROR_INVALID_DATATYPE = 1804;
public const int ERROR_INVALID_DOMAINNAME = 1212;
public const int ERROR_INVALID_DOMAIN_ROLE = 1354;
public const int ERROR_INVALID_DOMAIN_STATE = 1353;
public const int ERROR_INVALID_DRIVE = 15;
public const int ERROR_INVALID_DWP_HANDLE = 1405;
public const int ERROR_INVALID_EA_HANDLE = 278;
public const int ERROR_INVALID_EA_NAME = 254;
public const int ERROR_INVALID_EDIT_HEIGHT = 1424;
public const int ERROR_INVALID_ENVIRONMENT = 1805;
public const int ERROR_INVALID_EVENTNAME = 1211;
public const int ERROR_INVALID_EVENT_COUNT = 151;
public const int ERROR_INVALID_EXE_SIGNATURE = 191;
public const int ERROR_INVALID_FILTER_PROC = 1427;
public const int ERROR_INVALID_FLAGS = 1004;
public const int ERROR_INVALID_FLAG_NUMBER = 186;
public const int ERROR_INVALID_FORM_NAME = 1902;
public const int ERROR_INVALID_FORM_SIZE = 1903;
public const int ERROR_INVALID_FUNCTION = 1;
public const int ERROR_INVALID_GROUPNAME = 1209;
public const int ERROR_INVALID_GROUP_ATTRIBUTES = 1345;
public const int ERROR_INVALID_GW_COMMAND = 1443;
public const int ERROR_INVALID_HANDLE = 6;
public const int ERROR_INVALID_HOOK_FILTER = 1426;
public const int ERROR_INVALID_HOOK_HANDLE = 1404;
public const int ERROR_INVALID_ICON_HANDLE = 1414;
public const int ERROR_INVALID_ID_AUTHORITY = 1343;
public const int ERROR_INVALID_INDEX = 1413;
public const int ERROR_INVALID_LB_MESSAGE = 1432;
public const int ERROR_INVALID_LEVEL = 124;
public const int ERROR_INVALID_LIST_FORMAT = 153;
public const int ERROR_INVALID_LOGON_HOURS = 1328;
public const int ERROR_INVALID_LOGON_TYPE = 1367;
public const int ERROR_INVALID_MEMBER = 1388;
public const int ERROR_INVALID_MENU_HANDLE = 1401;
public const int ERROR_INVALID_MESSAGE = 1002;
public const int ERROR_INVALID_MESSAGEDEST = 1218;
public const int ERROR_INVALID_MESSAGENAME = 1217;
public const int ERROR_INVALID_MINALLOCSIZE = 195;
public const int ERROR_INVALID_MODULETYPE = 190;
public const int ERROR_INVALID_MSGBOX_STYLE = 1438;
public const int ERROR_INVALID_NAME = 123;
public const int ERROR_INVALID_NETNAME = 1214;
public const int ERROR_INVALID_ORDINAL = 182;
public const int ERROR_INVALID_OWNER = 1307;
public const int ERROR_INVALID_PARAMETER = 87;
public const int ERROR_INVALID_PASSWORD = 86;
public const int ERROR_INVALID_PASSWORDNAME = 1216;
public const int ERROR_INVALID_PIXEL_FORMAT = 2000;
public const int ERROR_INVALID_PRIMARY_GROUP = 1308;
public const int ERROR_INVALID_PRINTER_COMMAND = 1803;
public const int ERROR_INVALID_PRINTER_NAME = 1801;
public const int ERROR_INVALID_PRINTER_STATE = 1906;
public const int ERROR_INVALID_PRIORITY = 1800;
public const int ERROR_INVALID_SCROLLBAR_RANGE = 1448;
public const int ERROR_INVALID_SECURITY_DESCR = 1338;
public const int ERROR_INVALID_SEGDPL = 198;
public const int ERROR_INVALID_SEGMENT_NUMBER = 180;
public const int ERROR_INVALID_SEPARATOR_FILE = 1799;
public const int ERROR_INVALID_SERVER_STATE = 1352;
public const int ERROR_INVALID_SERVICENAME = 1213;
public const int ERROR_INVALID_SERVICE_ACCOUNT = 1057;
public const int ERROR_INVALID_SERVICE_CONTROL = 1052;
public const int ERROR_INVALID_SERVICE_LOCK = 1071;
public const int ERROR_INVALID_SHARENAME = 1215;
public const int ERROR_INVALID_SHOWWIN_COMMAND = 1449;
public const int ERROR_INVALID_SID = 1337;
public const int ERROR_INVALID_SIGNAL_NUMBER = 209;
public const int ERROR_INVALID_SPI_VALUE = 1439;
public const int ERROR_INVALID_STACKSEG = 189;
public const int ERROR_INVALID_STARTING_CODESEG = 188;
public const int ERROR_INVALID_SUB_AUTHORITY = 1335;
public const int ERROR_INVALID_TARGET_HANDLE = 114;
public const int ERROR_INVALID_THREAD_ID = 1444;
public const int ERROR_INVALID_TIME = 1901;
public const int ERROR_INVALID_USER_BUFFER = 1784;
public const int ERROR_INVALID_VERIFY_SWITCH = 118;
public const int ERROR_INVALID_WINDOW_HANDLE = 1400;
public const int ERROR_INVALID_WINDOW_STYLE = 2002;
public const int ERROR_INVALID_WORKSTATION = 1329;
public const int ERROR_IOPL_NOT_ENABLED = 197;
public const int ERROR_IO_DEVICE = 1117;
public const int ERROR_IO_INCOMPLETE = 996;
public const int ERROR_IO_PENDING = 997;
public const int ERROR_IRQ_BUSY = 1119;
public const int ERROR_IS_JOINED = 134;
public const int ERROR_IS_JOIN_PATH = 147;
public const int ERROR_IS_JOIN_TARGET = 133;
public const int ERROR_IS_SUBSTED = 135;
public const int ERROR_IS_SUBST_PATH = 146;
public const int ERROR_IS_SUBST_TARGET = 149;
public const int ERROR_ITERATED_DATA_EXCEEDS_64k = 194;
public const int ERROR_JOIN_TO_JOIN = 138;
public const int ERROR_JOIN_TO_SUBST = 140;
public const int ERROR_JOURNAL_HOOK_SET = 1430;
public const int ERROR_KEY_DELETED = 1018;
public const int ERROR_KEY_HAS_CHILDREN = 1020;
public const int ERROR_LABEL_TOO_LONG = 154;
public const int ERROR_LAST_ADMIN = 1322;
public const int ERROR_LB_WITHOUT_TABSTOPS = 1434;
public const int ERROR_LISTBOX_ID_NOT_FOUND = 1416;
public const int ERROR_LM_CROSS_ENCRYPTION_REQUIRED = 1390;
public const int ERROR_LOCAL_USER_SESSION_KEY = 1303;
public const int ERROR_LOCKED = 212;
public const int ERROR_LOCK_FAILED = 167;
public const int ERROR_LOCK_VIOLATION = 33;
public const int ERROR_LOGON_FAILURE = 1326;
public const int ERROR_LOGON_NOT_GRANTED = 1380;
public const int ERROR_LOGON_SESSION_COLLISION = 1366;
public const int ERROR_LOGON_SESSION_EXISTS = 1363;
public const int ERROR_LOGON_TYPE_NOT_GRANTED = 1385;
public const int ERROR_LOG_FILE_FULL = 1502;
public const int ERROR_LUIDS_EXHAUSTED = 1334;
public const int ERROR_MAPPED_ALIGNMENT = 1132;
public const int ERROR_MAX_THRDS_REACHED = 164;
public const int ERROR_MEDIA_CHANGED = 1110;
public const int ERROR_MEMBERS_PRIMARY_GROUP = 1374;
public const int ERROR_MEMBER_IN_ALIAS = 1378;
public const int ERROR_MEMBER_IN_GROUP = 1320;
public const int ERROR_MEMBER_NOT_IN_ALIAS = 1377;
public const int ERROR_MEMBER_NOT_IN_GROUP = 1321;
public const int ERROR_METAFILE_NOT_SUPPORTED = 2003;
public const int ERROR_META_EXPANSION_TOO_LONG = 208;
public const int ERROR_MOD_NOT_FOUND = 126;
public const int ERROR_MORE_DATA = 234;
public const int ERROR_MORE_WRITES = 1120;
public const int ERROR_MR_MID_NOT_FOUND = 317;
public const int ERROR_NEGATIVE_SEEK = 131;
public const int ERROR_NESTING_NOT_ALLOWED = 215;
public const int ERROR_NETLOGON_NOT_STARTED = 1792;
public const int ERROR_NETNAME_DELETED = 64;
public const int ERROR_NETWORK_ACCESS_DENIED = 65;
public const int ERROR_NETWORK_BUSY = 54;
public const int ERROR_NET_WRITE_FAULT = 88;
public const int ERROR_NOACCESS = 998;
public const int ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807;
public const int ERROR_NOLOGON_SERVER_TRUST_ACCOUNT = 1809;
public const int ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808;
public const int ERROR_NONE_MAPPED = 1332;
public const int ERROR_NON_MDICHILD_WINDOW = 1445;
public const int ERROR_NOTIFY_ENUM_DIR = 1022;
public const int ERROR_NOT_ALL_ASSIGNED = 1300;
public const int ERROR_NOT_CHILD_WINDOW = 1442;
public const int ERROR_NOT_CONNECTED = 2250;
public const int ERROR_NOT_CONTAINER = 1207;
public const int ERROR_NOT_DOS_DISK = 26;
public const int ERROR_NOT_ENOUGH_MEMORY = 8;
public const int ERROR_NOT_ENOUGH_QUOTA = 1816;
public const int ERROR_NOT_ENOUGH_SERVER_MEMORY = 1130;
public const int ERROR_NOT_JOINED = 136;
public const int ERROR_NOT_LOCKED = 158;
public const int ERROR_NOT_LOGON_PROCESS = 1362;
public const int ERROR_NOT_OWNER = 288;
public const int ERROR_NOT_READY = 21;
public const int ERROR_NOT_REGISTRY_FILE = 1017;
public const int ERROR_NOT_SAME_DEVICE = 17;
public const int ERROR_NOT_SUBSTED = 137;
public const int ERROR_NOT_SUPPORTED = 50;
public const int ERROR_NO_BROWSER_SERVERS_FOUND = 6118;
public const int ERROR_NO_DATA = 232;
public const int ERROR_NO_DATA_DETECTED = 1104;
public const int ERROR_NO_IMPERSONATION_TOKEN = 1309;
public const int ERROR_NO_INHERITANCE = 1391;
public const int ERROR_NO_LOGON_SERVERS = 1311;
public const int ERROR_NO_LOG_SPACE = 1019;
public const int ERROR_NO_MEDIA_IN_DRIVE = 1112;
public const int ERROR_NO_MORE_FILES = 18;
public const int ERROR_NO_MORE_ITEMS = 259;
public const int ERROR_NO_MORE_SEARCH_HANDLES = 113;
public const int ERROR_NO_NETWORK = 1222;
public const int ERROR_NO_NET_OR_BAD_PATH = 1203;
public const int ERROR_NO_PROC_SLOTS = 89;
public const int ERROR_NO_QUOTAS_FOR_ACCOUNT = 1302;
public const int ERROR_NO_SCROLLBARS = 1447;
public const int ERROR_NO_SECURITY_ON_OBJECT = 1350;
public const int ERROR_NO_SHUTDOWN_IN_PROGRESS = 1116;
public const int ERROR_NO_SIGNAL_SENT = 205;
public const int ERROR_NO_SPOOL_SPACE = 62;
public const int ERROR_NO_SUCH_ALIAS = 1376;
public const int ERROR_NO_SUCH_DOMAIN = 1355;
public const int ERROR_NO_SUCH_GROUP = 1319;
public const int ERROR_NO_SUCH_LOGON_SESSION = 1312;
public const int ERROR_NO_SUCH_MEMBER = 1387;
public const int ERROR_NO_SUCH_PACKAGE = 1364;
public const int ERROR_NO_SUCH_PRIVILEGE = 1313;
public const int ERROR_NO_SUCH_USER = 1317;
public const int ERROR_NO_SYSTEM_MENU = 1437;
public const int ERROR_NO_TOKEN = 1008;
public const int ERROR_NO_TRUST_LSA_SECRET = 1786;
public const int ERROR_NO_TRUST_SAM_ACCOUNT = 1787;
public const int ERROR_NO_UNICODE_TRANSLATION = 1113;
public const int ERROR_NO_USER_SESSION_KEY = 1394;
public const int ERROR_NO_VOLUME_LABEL = 125;
public const int ERROR_NO_WILDCARD_CHARACTERS = 1417;
public const int ERROR_NT_CROSS_ENCRYPTION_REQUIRED = 1386;
public const int ERROR_NULL_LM_PASSWORD = 1304;
public const int ERROR_OPEN_FAILED = 110;
public const int ERROR_OPEN_FILES = 2401;
public const int ERROR_OPERATION_ABORTED = 995;
public const int ERROR_OUTOFMEMORY = 14;
public const int ERROR_OUT_OF_PAPER = 28;
public const int ERROR_OUT_OF_STRUCTURES = 84;
public const int ERROR_PARTITION_FAILURE = 1105;
public const int ERROR_PASSWORD_EXPIRED = 1330;
public const int ERROR_PASSWORD_RESTRICTION = 1325;
public const int ERROR_PATH_BUSY = 148;
public const int ERROR_PATH_NOT_FOUND = 3;
public const int ERROR_PIPE_BUSY = 231;
public const int ERROR_PIPE_CONNECTED = 535;
public const int ERROR_PIPE_LISTENING = 536;
public const int ERROR_PIPE_NOT_CONNECTED = 233;
public const int ERROR_POPUP_ALREADY_ACTIVE = 1446;
public const int ERROR_POSSIBLE_DEADLOCK = 1131;
public const int ERROR_PRINTER_ALREADY_EXISTS = 1802;
public const int ERROR_PRINTER_DELETED = 1905;
public const int ERROR_PRINTER_DRIVER_ALREADY_INSTALLED = 1795;
public const int ERROR_PRINTER_DRIVER_IN_USE = 3001;
public const int ERROR_PRINTQ_FULL = 61;
public const int ERROR_PRINT_CANCELLED = 63;
public const int ERROR_PRINT_MONITOR_ALREADY_INSTALLED = 3006;
public const int ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED = 3005;
public const int ERROR_PRIVATE_DIALOG_INDEX = 1415;
public const int ERROR_PRIVILEGE_NOT_HELD = 1314;
public const int ERROR_PROCESS_ABORTED = 1067;
public const int ERROR_PROC_NOT_FOUND = 127;
public const int ERROR_PUBLIC_ONLY_HOOK = 1429;
public const int ERROR_READ_FAULT = 30;
public const int ERROR_REC_NON_EXISTENT = 4005;
public const int ERROR_REDIRECTOR_HAS_OPEN_HANDLES = 1794;
public const int ERROR_REDIR_PAUSED = 72;
public const int ERROR_REGISTRY_CORRUPT = 1015;
public const int ERROR_REGISTRY_IO_FAILED = 1016;
public const int ERROR_REGISTRY_RECOVERED = 1014;
public const int ERROR_RELOC_CHAIN_XEEDS_SEGLIM = 201;
public const int ERROR_REMOTE_SESSION_LIMIT_EXCEEDED = 1220;
public const int ERROR_REM_NOT_LIST = 51;
public const int ERROR_REQ_NOT_ACCEP = 71;
public const int ERROR_RESOURCE_DATA_NOT_FOUND = 1812;
public const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815;
public const int ERROR_RESOURCE_NAME_NOT_FOUND = 1814;
public const int ERROR_RESOURCE_TYPE_NOT_FOUND = 1813;
public const int ERROR_REVISION_MISMATCH = 1306;
public const int ERROR_RING2SEG_MUST_BE_MOVABLE = 200;
public const int ERROR_RING2_STACK_IN_USE = 207;
public const int ERROR_RPL_NOT_ALLOWED = 4006;
public const int ERROR_RXACT_COMMIT_FAILURE = 1370;
public const int ERROR_RXACT_INVALID_STATE = 1369;
public const int ERROR_SAME_DRIVE = 143;
public const int ERROR_SCREEN_ALREADY_LOCKED = 1440;
public const int ERROR_SECRET_TOO_LONG = 1382;
public const int ERROR_SECTOR_NOT_FOUND = 27;
public const int ERROR_SEEK = 25;
public const int ERROR_SEEK_ON_DEVICE = 132;
public const int ERROR_SEM_IS_SET = 102;
public const int ERROR_SEM_NOT_FOUND = 187;
public const int ERROR_SEM_OWNER_DIED = 105;
public const int ERROR_SEM_TIMEOUT = 121;
public const int ERROR_SEM_USER_LIMIT = 106;
public const int ERROR_SERIAL_NO_DEVICE = 1118;
public const int ERROR_SERVER_DISABLED = 1341;
public const int ERROR_SERVER_HAS_OPEN_HANDLES = 1811;
public const int ERROR_SERVER_NOT_DISABLED = 1342;
public const int ERROR_SERVICE_ALREADY_RUNNING = 1056;
public const int ERROR_SERVICE_CANNOT_ACCEPT_CTRL = 1061;
public const int ERROR_SERVICE_DATABASE_LOCKED = 1055;
public const int ERROR_SERVICE_DEPENDENCY_DELETED = 1075;
public const int ERROR_SERVICE_DEPENDENCY_FAIL = 1068;
public const int ERROR_SERVICE_DISABLED = 1058;
public const int ERROR_SERVICE_DOES_NOT_EXIST = 1060;
public const int ERROR_SERVICE_EXISTS = 1073;
public const int ERROR_SERVICE_LOGON_FAILED = 1069;
public const int ERROR_SERVICE_MARKED_FOR_DELETE = 1072;
public const int ERROR_SERVICE_NEVER_STARTED = 1077;
public const int ERROR_SERVICE_NOT_ACTIVE = 1062;
public const int ERROR_SERVICE_NO_THREAD = 1054;
public const int ERROR_SERVICE_REQUEST_TIMEOUT = 1053;
public const int ERROR_SERVICE_SPECIFIC_ERROR = 1066;
public const int ERROR_SERVICE_START_HANG = 1070;
public const int ERROR_SESSION_CREDENTIAL_CONFLICT = 1219;
public const int ERROR_SETCOUNT_ON_BAD_LB = 1433;
public const int ERROR_SETMARK_DETECTED = 1103;
public const int ERROR_SHARING_BUFFER_EXCEEDED = 36;
public const int ERROR_SHARING_PAUSED = 70;
public const int ERROR_SHARING_VIOLATION = 32;
public const int ERROR_SHUTDOWN_IN_PROGRESS = 1115;
public const int ERROR_SIGNAL_PENDING = 162;
public const int ERROR_SIGNAL_REFUSED = 156;
public const int ERROR_SOME_NOT_MAPPED = 1301;
public const int ERROR_SPECIAL_ACCOUNT = 1371;
public const int ERROR_SPECIAL_GROUP = 1372;
public const int ERROR_SPECIAL_USER = 1373;
public const int ERROR_SPL_NO_ADDJOB = 3004;
public const int ERROR_SPL_NO_STARTDOC = 3003;
public const int ERROR_SPOOL_FILE_NOT_FOUND = 3002;
public const int ERROR_STACK_OVERFLOW = 1001;
public const int ERROR_STATIC_INIT = 4002;
public const int ERROR_SUBST_TO_JOIN = 141;
public const int ERROR_SUBST_TO_SUBST = 139;
public const int ERROR_SUCCESS = 0;
public const int ERROR_SWAPERROR = 999;
public const int ERROR_SYSTEM_TRACE = 150;
public const int ERROR_THREAD_1_INACTIVE = 210;
public const int ERROR_TLW_WITH_WSCHILD = 1406;
public const int ERROR_TOKEN_ALREADY_IN_USE = 1375;
public const int ERROR_TOO_MANY_CMDS = 56;
public const int ERROR_TOO_MANY_CONTEXT_IDS = 1384;
public const int ERROR_TOO_MANY_LUIDS_REQUESTED = 1333;
public const int ERROR_TOO_MANY_MODULES = 214;
public const int ERROR_TOO_MANY_MUXWAITERS = 152;
public const int ERROR_TOO_MANY_NAMES = 68;
public const int ERROR_TOO_MANY_OPEN_FILES = 4;
public const int ERROR_TOO_MANY_POSTS = 298;
public const int ERROR_TOO_MANY_SECRETS = 1381;
public const int ERROR_TOO_MANY_SEMAPHORES = 100;
public const int ERROR_TOO_MANY_SEM_REQUESTS = 103;
public const int ERROR_TOO_MANY_SESS = 69;
public const int ERROR_TOO_MANY_SIDS = 1389;
public const int ERROR_TOO_MANY_TCBS = 155;
public const int ERROR_TRANSFORM_NOT_SUPPORTED = 2004;
public const int ERROR_TRUSTED_DOMAIN_FAILURE = 1788;
public const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;
public const int ERROR_TRUST_FAILURE = 1790;
public const int ERROR_UNABLE_TO_LOCK_MEDIA = 1108;
public const int ERROR_UNABLE_TO_UNLOAD_MEDIA = 1109;
public const int ERROR_UNEXP_NET_ERR = 59;
public const int ERROR_UNKNOWN_PORT = 1796;
public const int ERROR_UNKNOWN_PRINTER_DRIVER = 1797;
public const int ERROR_UNKNOWN_PRINTPROCESSOR = 1798;
public const int ERROR_UNKNOWN_PRINT_MONITOR = 3000;
public const int ERROR_UNKNOWN_REVISION = 1305;
public const int ERROR_UNRECOGNIZED_MEDIA = 1785;
public const int ERROR_UNRECOGNIZED_VOLUME = 1005;
public const int ERROR_USER_EXISTS = 1316;
public const int ERROR_VC_DISCONNECTED = 240;
public const int ERROR_WAIT_NO_CHILDREN = 128;
public const int ERROR_WINDOW_NOT_COMBOBOX = 1423;
public const int ERROR_WINDOW_NOT_DIALOG = 1420;
public const int ERROR_WINDOW_OF_OTHER_THREAD = 1408;
public const int ERROR_WINS_INTERNAL = 4000;
public const int ERROR_WRITE_FAULT = 29;
public const int ERROR_WRITE_PROTECT = 19;
public const int ERROR_WRONG_DISK = 34;
public const int ERROR_WRONG_PASSWORD = 1323;
public const int E_ABORT = unchecked((int) 0x80004004);
public const int E_ACCESSDENIED = unchecked((int) 0x80070005);
public const int E_FAIL = unchecked((int) 0x80004005);
public const int E_HANDLE = unchecked((int) 0x80070006);
public const int E_INVALIDARG = unchecked((int) 0x80070057);
public const int E_NOINTERFACE = unchecked((int) 0x80004002);
public const int E_NOTIMPL = unchecked((int) 0x80004001);
public const int E_OUTOFMEMORY = unchecked((int) 0x8007000E);
public const int E_POINTER = unchecked((int) 0x80004003);
public const int E_UNEXPECTED = unchecked((int) 0x8000FFFF);
public const int FACILITY_NT_BIT = 0x10000000;
public const int INPLACE_E_FIRST = unchecked((int) 0x800401A0);
public const int INPLACE_E_LAST = unchecked((int) 0x800401AF);
public const int INPLACE_E_NOTOOLSPACE = unchecked((int) 0x800401A1);
public const int INPLACE_E_NOTUNDOABLE = unchecked((int) 0x800401A0);
public const int INPLACE_S_FIRST = 0x401A0;
public const int INPLACE_S_LAST = 0x401AF;
public const int INPLACE_S_TRUNCATED = 0x401A0;
public const int MARSHAL_E_FIRST = unchecked((int) 0x80040120);
public const int MARSHAL_E_LAST = unchecked((int) 0x8004012F);
public const int MARSHAL_S_FIRST = 0x40120;
public const int MARSHAL_S_LAST = 0x4012F;
public const int MEM_E_INVALID_LINK = unchecked((int) 0x80080010);
public const int MEM_E_INVALID_ROOT = unchecked((int) 0x80080009);
public const int MEM_E_INVALID_SIZE = unchecked((int) 0x80080011);
public const int MK_E_CANTOPENFILE = unchecked((int) 0x800401EA);
public const int MK_E_CONNECTMANUALLY = unchecked((int) 0x800401E0);
public const int MK_E_ENUMERATION_FAILED = unchecked((int) 0x800401EF);
public const int MK_E_EXCEEDEDDEADLINE = unchecked((int) 0x800401E1);
public const int MK_E_FIRST = unchecked((int) 0x800401E0);
public const int MK_E_INTERMEDIATEINTERFACENOTSUPPORTED = unchecked((int) 0x800401E7);
public const int MK_E_INVALIDEXTENSION = unchecked((int) 0x800401E6);
public const int MK_E_LAST = unchecked((int) 0x800401EF);
public const int MK_E_MUSTBOTHERUSER = unchecked((int) 0x800401EB);
public const int MK_E_NEEDGENERIC = unchecked((int) 0x800401E2);
public const int MK_E_NOINVERSE = unchecked((int) 0x800401EC);
public const int MK_E_NOOBJECT = unchecked((int) 0x800401E5);
public const int MK_E_NOPREFIX = unchecked((int) 0x800401EE);
public const int MK_E_NOSTORAGE = unchecked((int) 0x800401ED);
public const int MK_E_NOTBINDABLE = unchecked((int) 0x800401E8);
public const int MK_E_NOTBOUND = unchecked((int) 0x800401E9);
public const int MK_E_NO_NORMALIZED = unchecked((int) 0x80080007);
public const int MK_E_SYNTAX = unchecked((int) 0x800401E4);
public const int MK_E_UNAVAILABLE = unchecked((int) 0x800401E3);
public const int MK_S_FIRST = 0x401E0;
public const int MK_S_HIM = 0x401E5;
public const int MK_S_LAST = 0x401EF;
public const int MK_S_ME = 0x401E4;
public const int MK_S_MONIKERALREADYREGISTERED = 0x401E7;
public const int MK_S_REDUCED_TO_SELF = 0x401E2;
public const int MK_S_US = 0x401E6;
public const int NOERROR = 0;
public const int NO_ERROR = 0;
public const int OLEOBJ_E_FIRST = unchecked((int) 0x80040180);
public const int OLEOBJ_E_INVALIDVERB = unchecked((int) 0x80040181);
public const int OLEOBJ_E_LAST = unchecked((int) 0x8004018F);
public const int OLEOBJ_E_NOVERBS = unchecked((int) 0x80040180);
public const int OLEOBJ_S_CANNOT_DOVERB_NOW = 0x40181;
public const int OLEOBJ_S_FIRST = 0x40180;
public const int OLEOBJ_S_INVALIDHWND = 0x40182;
public const int OLEOBJ_S_INVALIDVERB = 0x40180;
public const int OLEOBJ_S_LAST = 0x4018F;
public const int OLE_E_ADVF = unchecked((int) 0x80040001);
public const int OLE_E_ADVISENOTSUPPORTED = unchecked((int) 0x80040003);
public const int OLE_E_BLANK = unchecked((int) 0x80040007);
public const int OLE_E_CANTCONVERT = unchecked((int) 0x80040011);
public const int OLE_E_CANT_BINDTOSOURCE = unchecked((int) 0x8004000A);
public const int OLE_E_CANT_GETMONIKER = unchecked((int) 0x80040009);
public const int OLE_E_CLASSDIFF = unchecked((int) 0x80040008);
public const int OLE_E_ENUM_NOMORE = unchecked((int) 0x80040002);
public const int OLE_E_FIRST = unchecked((int) 0x80040000);
public const int OLE_E_INVALIDHWND = unchecked((int) 0x8004000F);
public const int OLE_E_INVALIDRECT = unchecked((int) 0x8004000D);
public const int OLE_E_LAST = unchecked((int) 0x800400FF);
public const int OLE_E_NOCACHE = unchecked((int) 0x80040006);
public const int OLE_E_NOCONNECTION = unchecked((int) 0x80040004);
public const int OLE_E_NOSTORAGE = unchecked((int) 0x80040012);
public const int OLE_E_NOTRUNNING = unchecked((int) 0x80040005);
public const int OLE_E_NOT_INPLACEACTIVE = unchecked((int) 0x80040010);
public const int OLE_E_OLEVERB = unchecked((int) 0x80040000);
public const int OLE_E_PROMPTSAVECANCELLED = unchecked((int) 0x8004000C);
public const int OLE_E_STATIC = unchecked((int) 0x8004000B);
public const int OLE_E_WRONGCOMPOBJ = unchecked((int) 0x8004000E);
public const int OLE_S_FIRST = 0x40000;
public const int OLE_S_LAST = 0x400FF;
public const int OLE_S_MAC_CLIPFORMAT = 0x40002;
public const int OLE_S_STATIC = 0x40001;
public const int OLE_S_USEREG = 0x40000;
public const int REGDB_E_CLASSNOTREG = unchecked((int) 0x80040154);
public const int REGDB_E_FIRST = unchecked((int) 0x80040150);
public const int REGDB_E_IIDNOTREG = unchecked((int) 0x80040155);
public const int REGDB_E_INVALIDVALUE = unchecked((int) 0x80040153);
public const int REGDB_E_KEYMISSING = unchecked((int) 0x80040152);
public const int REGDB_E_LAST = unchecked((int) 0x8004015F);
public const int REGDB_E_READREGDB = unchecked((int) 0x80040150);
public const int REGDB_E_WRITEREGDB = unchecked((int) 0x80040151);
public const int REGDB_S_FIRST = 0x40150;
public const int REGDB_S_LAST = 0x4015F;
public const int RPC_E_ATTEMPTED_MULTITHREAD = unchecked((int) 0x80010102);
public const int RPC_E_CALL_CANCELED = unchecked((int) 0x80010002);
public const int RPC_E_CALL_REJECTED = unchecked((int) 0x80010001);
public const int RPC_E_CANTCALLOUT_AGAIN = unchecked((int) 0x80010011);
public const int RPC_E_CANTCALLOUT_INASYNCCALL = unchecked((int) 0x80010004);
public const int RPC_E_CANTCALLOUT_INEXTERNALCALL = unchecked((int) 0x80010005);
public const int RPC_E_CANTCALLOUT_ININPUTSYNCCALL = unchecked((int) 0x8001010D);
public const int RPC_E_CANTPOST_INSENDCALL = unchecked((int) 0x80010003);
public const int RPC_E_CANTTRANSMIT_CALL = unchecked((int) 0x8001000A);
public const int RPC_E_CHANGED_MODE = unchecked((int) 0x80010106);
public const int RPC_E_CLIENT_CANTMARSHAL_DATA = unchecked((int) 0x8001000B);
public const int RPC_E_CLIENT_CANTUNMARSHAL_DATA = unchecked((int) 0x8001000C);
public const int RPC_E_CLIENT_DIED = unchecked((int) 0x80010008);
public const int RPC_E_CONNECTION_TERMINATED = unchecked((int) 0x80010006);
public const int RPC_E_DISCONNECTED = unchecked((int) 0x80010108);
public const int RPC_E_FAULT = unchecked((int) 0x80010104);
public const int RPC_E_INVALIDMETHOD = unchecked((int) 0x80010107);
public const int RPC_E_INVALID_CALLDATA = unchecked((int) 0x8001010C);
public const int RPC_E_INVALID_DATA = unchecked((int) 0x8001000F);
public const int RPC_E_INVALID_DATAPACKET = unchecked((int) 0x80010009);
public const int RPC_E_INVALID_PARAMETER = unchecked((int) 0x80010010);
public const int RPC_E_NOT_REGISTERED = unchecked((int) 0x80010103);
public const int RPC_E_OUT_OF_RESOURCES = unchecked((int) 0x80010101);
public const int RPC_E_RETRY = unchecked((int) 0x80010109);
public const int RPC_E_SERVERCALL_REJECTED = unchecked((int) 0x8001010B);
public const int RPC_E_SERVERCALL_RETRYLATER = unchecked((int) 0x8001010A);
public const int RPC_E_SERVERFAULT = unchecked((int) 0x80010105);
public const int RPC_E_SERVER_CANTMARSHAL_DATA = unchecked((int) 0x8001000D);
public const int RPC_E_SERVER_CANTUNMARSHAL_DATA = unchecked((int) 0x8001000E);
public const int RPC_E_SERVER_DIED = unchecked((int) 0x80010007);
public const int RPC_E_SERVER_DIED_DNE = unchecked((int) 0x80010012);
public const int RPC_E_SYS_CALL_FAILED = unchecked((int) 0x80010100);
public const int RPC_E_THREAD_NOT_INIT = unchecked((int) 0x8001010F);
public const int RPC_E_UNEXPECTED = unchecked((int) 0x8001FFFF);
public const int RPC_E_WRONG_THREAD = unchecked((int) 0x8001010E);
public const int RPC_S_ADDRESS_ERROR = 1768;
public const int RPC_S_ALREADY_LISTENING = 1713;
public const int RPC_S_ALREADY_REGISTERED = 1711;
public const int RPC_S_BINDING_HAS_NO_AUTH = 1746;
public const int RPC_S_CALL_FAILED = 1726;
public const int RPC_S_CALL_FAILED_DNE = 1727;
public const int RPC_S_CALL_IN_PROGRESS = 1791;
public const int RPC_S_CANNOT_SUPPORT = 1764;
public const int RPC_S_CANT_CREATE_ENDPOINT = 1720;
public const int RPC_S_DUPLICATE_ENDPOINT = 1740;
public const int RPC_S_ENTRY_ALREADY_EXISTS = 1760;
public const int RPC_S_ENTRY_NOT_FOUND = 1761;
public const int RPC_S_FP_DIV_ZERO = 1769;
public const int RPC_S_FP_OVERFLOW = 1771;
public const int RPC_S_FP_UNDERFLOW = 1770;
public const int RPC_S_GROUP_MEMBER_NOT_FOUND = 1898;
public const int RPC_S_INCOMPLETE_NAME = 1755;
public const int RPC_S_INTERFACE_NOT_FOUND = 1759;
public const int RPC_S_INTERNAL_ERROR = 1766;
public const int RPC_S_INVALID_AUTH_IDENTITY = 1749;
public const int RPC_S_INVALID_BINDING = 1702;
public const int RPC_S_INVALID_BOUND = 1734;
public const int RPC_S_INVALID_ENDPOINT_FORMAT = 1706;
public const int RPC_S_INVALID_NAF_ID = 1763;
public const int RPC_S_INVALID_NAME_SYNTAX = 1736;
public const int RPC_S_INVALID_NETWORK_OPTIONS = 1724;
public const int RPC_S_INVALID_NET_ADDR = 1707;
public const int RPC_S_INVALID_OBJECT = 1900;
public const int RPC_S_INVALID_RPC_PROTSEQ = 1704;
public const int RPC_S_INVALID_STRING_BINDING = 1700;
public const int RPC_S_INVALID_STRING_UUID = 1705;
public const int RPC_S_INVALID_TAG = 1733;
public const int RPC_S_INVALID_TIMEOUT = 1709;
public const int RPC_S_INVALID_VERS_OPTION = 1756;
public const int RPC_S_MAX_CALLS_TOO_SMALL = 1742;
public const int RPC_S_NAME_SERVICE_UNAVAILABLE = 1762;
public const int RPC_S_NOTHING_TO_EXPORT = 1754;
public const int RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758;
public const int RPC_S_NOT_LISTENING = 1715;
public const int RPC_S_NO_BINDINGS = 1718;
public const int RPC_S_NO_CALL_ACTIVE = 1725;
public const int RPC_S_NO_CONTEXT_AVAILABLE = 1765;
public const int RPC_S_NO_ENDPOINT_FOUND = 1708;
public const int RPC_S_NO_ENTRY_NAME = 1735;
public const int RPC_S_NO_MORE_BINDINGS = 1806;
public const int RPC_S_NO_MORE_MEMBERS = 1757;
public const int RPC_S_NO_PROTSEQS = 1719;
public const int RPC_S_NO_PROTSEQS_REGISTERED = 1714;
public const int RPC_S_OBJECT_NOT_FOUND = 1710;
public const int RPC_S_OUT_OF_RESOURCES = 1721;
public const int RPC_S_PROCNUM_OUT_OF_RANGE = 1745;
public const int RPC_S_PROTOCOL_ERROR = 1728;
public const int RPC_S_PROTSEQ_NOT_FOUND = 1744;
public const int RPC_S_PROTSEQ_NOT_SUPPORTED = 1703;
public const int RPC_S_SERVER_TOO_BUSY = 1723;
public const int RPC_S_SERVER_UNAVAILABLE = 1722;
public const int RPC_S_STRING_TOO_LONG = 1743;
public const int RPC_S_TYPE_ALREADY_REGISTERED = 1712;
public const int RPC_S_UNKNOWN_AUTHN_LEVEL = 1748;
public const int RPC_S_UNKNOWN_AUTHN_SERVICE = 1747;
public const int RPC_S_UNKNOWN_AUTHN_TYPE = 1741;
public const int RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750;
public const int RPC_S_UNKNOWN_IF = 1717;
public const int RPC_S_UNKNOWN_MGR_TYPE = 1716;
public const int RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737;
public const int RPC_S_UNSUPPORTED_TRANS_SYN = 1730;
public const int RPC_S_UNSUPPORTED_TYPE = 1732;
public const int RPC_S_UUID_NO_ADDRESS = 1739;
public const int RPC_S_WRONG_KIND_OF_BINDING = 1701;
public const int RPC_S_ZERO_DIVIDE = 1767;
public const int RPC_X_BAD_STUB_DATA = 1783;
public const int RPC_X_BYTE_COUNT_TOO_SMALL = 1782;
public const int RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781;
public const int RPC_X_NO_MORE_ENTRIES = 1772;
public const int RPC_X_NULL_REF_POINTER = 1780;
public const int RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779;
public const int RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773;
public const int RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774;
public const int RPC_X_SS_CONTEXT_DAMAGED = 1777;
public const int RPC_X_SS_HANDLES_MISMATCH = 1778;
public const int RPC_X_SS_IN_NULL_CONTEXT = 1775;
public const int SEVERITY_ERROR = 1;
public const int SEVERITY_SUCCESS = 0;
public const int STG_E_ABNORMALAPIEXIT = unchecked((int) 0x800300FA);
public const int STG_E_ACCESSDENIED = unchecked((int) 0x80030005);
public const int STG_E_CANTSAVE = unchecked((int) 0x80030103);
public const int STG_E_DISKISWRITEPROTECTED = unchecked((int) 0x80030013);
public const int STG_E_EXTANTMARSHALLINGS = unchecked((int) 0x80030108);
public const int STG_E_FILEALREADYEXISTS = unchecked((int) 0x80030050);
public const int STG_E_FILENOTFOUND = unchecked((int) 0x80030002);
public const int STG_E_INSUFFICIENTMEMORY = unchecked((int) 0x80030008);
public const int STG_E_INUSE = unchecked((int) 0x80030100);
public const int STG_E_INVALIDFLAG = unchecked((int) 0x800300FF);
public const int STG_E_INVALIDFUNCTION = unchecked((int) 0x80030001);
public const int STG_E_INVALIDHANDLE = unchecked((int) 0x80030006);
public const int STG_E_INVALIDHEADER = unchecked((int) 0x800300FB);
public const int STG_E_INVALIDNAME = unchecked((int) 0x800300FC);
public const int STG_E_INVALIDPARAMETER = unchecked((int) 0x80030057);
public const int STG_E_INVALIDPOINTER = unchecked((int) 0x80030009);
public const int STG_E_LOCKVIOLATION = unchecked((int) 0x80030021);
public const int STG_E_MEDIUMFULL = unchecked((int) 0x80030070);
public const int STG_E_NOMOREFILES = unchecked((int) 0x80030012);
public const int STG_E_NOTCURRENT = unchecked((int) 0x80030101);
public const int STG_E_NOTFILEBASEDSTORAGE = unchecked((int) 0x80030107);
public const int STG_E_OLDDLL = unchecked((int) 0x80030105);
public const int STG_E_OLDFORMAT = unchecked((int) 0x80030104);
public const int STG_E_PATHNOTFOUND = unchecked((int) 0x80030003);
public const int STG_E_READFAULT = unchecked((int) 0x8003001E);
public const int STG_E_REVERTED = unchecked((int) 0x80030102);
public const int STG_E_SEEKERROR = unchecked((int) 0x80030019);
public const int STG_E_SHAREREQUIRED = unchecked((int) 0x80030106);
public const int STG_E_SHAREVIOLATION = unchecked((int) 0x80030020);
public const int STG_E_TOOMANYOPENFILES = unchecked((int) 0x80030004);
public const int STG_E_UNIMPLEMENTEDFUNCTION = unchecked((int) 0x800300FE);
public const int STG_E_UNKNOWN = unchecked((int) 0x800300FD);
public const int STG_E_WRITEFAULT = unchecked((int) 0x8003001D);
public const int STG_S_CONVERTED = unchecked((int) 0x30200);
public const int S_FALSE = 0x1;
public const int S_OK = 0x0;
public const int TYPE_E_AMBIGUOUSNAME = unchecked((int) 0x8002802C);
public const int TYPE_E_BADMODULEKIND = unchecked((int) 0x800288BD);
public const int TYPE_E_BUFFERTOOSMALL = unchecked((int) 0x80028016);
public const int TYPE_E_CANTCREATETMPFILE = unchecked((int) 0x80028CA3);
public const int TYPE_E_CANTLOADLIBRARY = unchecked((int) 0x80029C4A);
public const int TYPE_E_CIRCULARTYPE = unchecked((int) 0x80029C84);
public const int TYPE_E_DLLFUNCTIONNOTFOUND = unchecked((int) 0x8002802F);
public const int TYPE_E_DUPLICATEID = unchecked((int) 0x800288C6);
public const int TYPE_E_ELEMENTNOTFOUND = unchecked((int) 0x8002802B);
public const int TYPE_E_INCONSISTENTPROPFUNCS = unchecked((int) 0x80029C83);
public const int TYPE_E_INVALIDID = unchecked((int) 0x800288CF);
public const int TYPE_E_INVALIDSTATE = unchecked((int) 0x80028029);
public const int TYPE_E_INVDATAREAD = unchecked((int) 0x80028018);
public const int TYPE_E_IOERROR = unchecked((int) 0x80028CA2);
public const int TYPE_E_LIBNOTREGISTERED = unchecked((int) 0x8002801D);
public const int TYPE_E_NAMECONFLICT = unchecked((int) 0x8002802D);
public const int TYPE_E_OUTOFBOUNDS = unchecked((int) 0x80028CA1);
public const int TYPE_E_QUALIFIEDNAMEDISALLOWED = unchecked((int) 0x80028028);
public const int TYPE_E_REGISTRYACCESS = unchecked((int) 0x8002801C);
public const int TYPE_E_SIZETOOBIG = unchecked((int) 0x800288C5);
public const int TYPE_E_TYPEMISMATCH = unchecked((int) 0x80028CA0);
public const int TYPE_E_UNDEFINEDTYPE = unchecked((int) 0x80028027);
public const int TYPE_E_UNKNOWNLCID = unchecked((int) 0x8002802E);
public const int TYPE_E_UNSUPFORMAT = unchecked((int) 0x80028019);
public const int TYPE_E_WRONGTYPEKIND = unchecked((int) 0x8002802A);
public const int VIEW_E_DRAW = unchecked((int) 0x80040140);
public const int VIEW_E_FIRST = unchecked((int) 0x80040140);
public const int VIEW_E_LAST = unchecked((int) 0x8004014F);
public const int VIEW_S_ALREADY_FROZEN = 0x40140;
public const int VIEW_S_FIRST = 0x40140;
public const int VIEW_S_LAST = 0x4014F;
}
}


全部類別轉成DLL檔
一、批次檔 加入如下：
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\csc.exe /target:library /out:OldWin32.dll Kernel.cs User.cs Win32.cs Shell.cs NetApi.cs GDI.cs Multimedia.cs ErrorCodes.cs
二、執行產生「OldWin32.dll 」檔。
三、使用時，加入專案的「參考」。
四、程式碼加入： using Win32;
五、範例： (傳回磁碟空間資訊)
using System;
using
System.Windows.Forms;
using System.Runtime.InteropServices;
using Win32;
namespace
DefaultNamespace
{
/// <summary>
/// Description of
MainForm.
/// </summary>
public class MainForm :
System.Windows.Forms.Form
{
private
System.Windows.Forms.Button button1;
private
System.Windows.Forms.RichTextBox richTextBox1;
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
this.richTextBox1 = new
System.Windows.Forms.RichTextBox();
this.button1 = new
System.Windows.Forms.Button();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(16,
16);
this.richTextBox1.Name =
"richTextBox1";
this.richTextBox1.Size = new
System.Drawing.Size(184, 168);
this.richTextBox1.TabIndex =
0;
this.richTextBox1.Text =
"richTextBox1";
//
//
button1
//
this.button1.Location =
new System.Drawing.Point(200, 216);
this.button1.Name =
"button1";
this.button1.TabIndex =
1;
this.button1.Text =
"button1";
this.button1.Click += new
System.EventHandler(this.Button1Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
15);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Controls.Add(this.button1);
this.Controls.Add(this.richTextBox1);
this.Name
= "MainForm";
this.Text =
"MainForm";
this.ResumeLayout(false);
}
#endregion
void
Button1Click(object sender, System.EventArgs
e)
{
ulong freeBytesAvailable, totalBytes,
freeBytes;
// 呼叫 Win32 API
傳回磁碟空間資訊
Win32.Kernel.GetDiskFreeSpaceEx ( "C:", out
freeBytesAvailable, out totalBytes, out freeBytes
);
richTextBox1.Clear();
richTextBox1.AppendText
( "Total space : " + totalBytes + " Bytes"
+"\n");
richTextBox1.AppendText( "Free space : " +
freeBytes + " Bytes" +"\n");
richTextBox1.AppendText(
"Available Free space : " + freeBytesAvailable + " Bytes" +"\n");
  }

 }
}


Microsoft Win32 to Microsoft .NET Framework API Map

http://msdn.microsoft.com/library/en-us/dndotnet/html/win32map.asp


片段Win 32 API用於C#方式
使用語法：
using System.Runtime.InteropServices;
...
[DllImport( dll_filename )]
[public|private] static extern ret_type function( [type para, ...] );
範例： （PlaySound 播放音樂 API應用）
using System;
using System.Runtime.InteropServices;
namespace APITest
{
class clsAPI
{
[DllImport("winmm.dll")]
public static extern long PlaySound(string lpszName,
long hModule, long
dwFlags);

[STAThread]
static void Main(string[]
args)
{
long retval;
string fname =
"e:\\sounds\\hit.wav";

retval = PlaySound( fname, 0, 1
);
}
}
}

參考工具：

API-Guide
網址： http://www.mentalis.org/agnet/apiguide.shtml
Win32 API For C#/VB.NET線上查詢及VS.NET外掛程式:
http://www.pinvoke.net/


取得系統訊息
1.取得作業系統版本：
System.Environment.OSVersion.ToString()
2.取得電腦識別名稱：
 System.Environment.MachineName.ToString()
3.取得系統目前使用者名稱：
System.Environment.UserName.ToString()
4.取得.NET Framework目前使用版本：
System.Environment.Version.ToString()
5.取得目前執行檔所在位置的完整資料夾路徑：
System.Environment.CurrentDirectory.ToString()
6.取得目前執行檔所在位置的完整資料夾路徑：(含執行檔名稱)
System.Environment.CommandLine.ToString()
7.取得系統目前已執行時間：
System.Environment.TickCount.ToString()


取得系統環境變數
using System;
using System.Collections;
....
void Button2Click(object sender, System.EventArgs e)
{
 IDictionary envars =Environment.GetEnvironmentVariables();
 IDictionaryEnumerator varEnumerator =envars.GetEnumerator();
 while(varEnumerator.MoveNext() != false)
 {
  richTextBox1.AppendText(varEnumerator.Key+"="+
                          varEnumerator.Value+"\n");
 }
}


取得程式共用資料夾位置
private void button1_Click(object sender, System.EventArgs e)
{
 //取得程式共用資料夾位置
 string a = System.Environment.GetFolderPath
            (Environment.SpecialFolder.CommonProgramFiles);
 textBox1.Text = a;
}

結果:
  C:\Program Files\Common Files


取得存放Cookie資料夾位置
private void button1_Click(object sender, System.EventArgs e)
{
 //取得存放Cookie資料夾位置
 string a = System.Environment.GetFolderPath
       (Environment.SpecialFolder.Cookies);
 textBox1.Text = a;
}

結果:
  C:\Documents and Settings\UserName\Cookies


取得桌面路徑位置
private void button1_Click(object sender, System.EventArgs
e)
{
//取得桌面路徑位置
string a = System.Environment.GetFolderPath
(Environment.SpecialFolder.Desktop);
textBox1.Text = a;
}

結果:
  C:\Documents and Settings\Administrator\桌面


取得我的最愛資料夾位置
private void button1_Click(object sender, System.EventArgs
e)
{
//取得我的最愛資料夾位置
string a = System.Environment.GetFolderPath
(Environment.SpecialFolder.Favorites);
textBox1.Text = a;
}

結果:
  C:\Documents and Settings\UserName\Favorites


取得歷史資料夾位置
private void button1_Click(object sender, System.EventArgs e)
{
 //取得歷史資料夾位置
 string a = System.Environment.GetFolderPath
            (Environment.SpecialFolder.History);
 textBox1.Text = a;
}

結果:
  C:\Documents and Settings\UserName\Local Settings\History


取得IE暫存資料夾位置
private
void button1_Click(object sender, System.EventArgs e)
{
//取得IE暫存資料夾位置
string a = System.Environment.GetFolderPath
             (Environment.SpecialFolder.InternetCache);
  textBox1.Text = a;
}

結果:
  C:\Documents and Settings\UserName\Local Settings\Temporary Internet Files


取得我的文件夾位置
private void button1_Click(object sender, System.EventArgs e)
{
 //取得我的文件夾位置
 string a = System.Environment.GetFolderPath
            (Environment.SpecialFolder.Personal);
 textBox1.Text = a;
}

結果:
  C:\Documents and Settings\UserName\My Documents


取得Program Files 路徑
private
void button1_Click(object sender, System.EventArgs e)
{
//取得Program
Files資料夾路徑
string a = System.Environment.GetFolderPath
(Environment.SpecialFolder.ProgramFiles);
textBox1.Text = a;
}

結果:
  C:\Program Files


取得啟動資料夾路徑
private void button1_Click(object sender, System.EventArgs e)
{
 //取得啟動資料夾路徑
 string a = System.Environment.GetFolderPath
           (Environment.SpecialFolder.Startup);
 textBox1.Text = a;
}

結果：
C:\Documents and Settings\Administrator\「開始」功能表\程式集\啟動


取得傳送資料夾位置
private void button1_Click(object sender, System.EventArgs
e)
{
//取得傳送資料夾位置
string a = System.Environment.GetFolderPath
        (Environment.SpecialFolder.SendTo);
  textBox1.Text = a;
}

結果:
  C:\Documents and Settings\UserName\SendTo


取得程式完整路徑(Application.ExecutablePath)
程式碼：
using System;
using
System.Windows.Forms;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
Console.Write("{0}\n",Application.ExecutablePath);
}
}
}
結果：
C:\SharpDevelop Projects\Console1\bin\Debug\Console1.exe
請按任意鍵繼續 . . .


取得公司名稱 (Application.CompanyName)
1.專案中，在「AssemblyInfo.cs」設定 [assembly: AssemblyCompany("")]
  為[assembly: AssemblyCompany("真好公司")]
2.程式中加入：
using System;
using
System.Windows.Forms;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
Console.Write("{0}\n",Application.CompanyName);
}
}
}
3.結果：
真好公司
請按任意鍵繼續 . . .


使用System.CodeDom建立簡單的程式編譯器
=>產生Hello Wolrd程式碼=>編譯=>執行
程式碼如下：
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.CSharp;
using Microsoft.VisualBasic;

// This example demonstrates building a Hello World program graph
// using System.CodeDom elements. It calls code generator and
// code compiler methods to build the program using CSharp, VB.
// A Windows Forms interface is included.
namespace CodeDOMExample
{
    public class CodeDomExample
    {
        //<Snippet2>
        // Build a Hello World program graph using
        // System.CodeDom types.
        public static CodeCompileUnit BuildHelloWorldGraph()
        {
            // Create a new CodeCompileUnit to contain
            // the program graph.
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare a new namespace called Samples.
            CodeNamespace samples = new CodeNamespace("Samples");
            // Add the new namespace to the compile unit.
            compileUnit.Namespaces.Add( samples );

            // Add the new namespace import for the System namespace.
            samples.Imports.Add( new CodeNamespaceImport("System") );

            // Declare a new type called Class1.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
            // Add the new type to the namespace type collection.
            samples.Types.Add(class1);

            // Declare a new code entry point method.
            CodeEntryPointMethod start = new CodeEntryPointMethod();

            // Create a type reference for the System.Console class.
            CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console");

            // Build a Console.WriteLine statement.
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
                csSystemConsoleType, "WriteLine",
                new CodePrimitiveExpression("Hello World!") );

            // Add the WriteLine call to the statement collection.
            start.Statements.Add(cs1);

            // Build another Console.WriteLine statement.
            CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(
                csSystemConsoleType, "WriteLine",
                new CodePrimitiveExpression("Press the Enter key to continue.") );

            // Add the WriteLine call to the statement collection.
            start.Statements.Add(cs2);

            // Build a call to System.Console.ReadLine.
            CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression(
                csSystemConsoleType, "ReadLine");

            // Add the ReadLine statement.
            start.Statements.Add(csReadLine);

            // Add the code entry point method to
            // the Members collection of the type.
            class1.Members.Add( start );

            return compileUnit;
        }
        //</Snippet2>

        //<Snippet3>
        public static void GenerateCode(CodeDomProvider provider,
            CodeCompileUnit compileunit)
        {
            // Build the source file name with the appropriate
            // language extension.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = "TestGraph" + provider.FileExtension;
            }
            else
            {
                sourceFile = "TestGraph." + provider.FileExtension;
            }

            // Obtain an ICodeGenerator from the CodeDomProvider.
            ICodeGenerator gen = provider.CreateGenerator();
            // Create an IndentedTextWriter, constructed with
            // a StreamWriter to the source file.
            IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, false), "    ");
            // Generate source code using the code generator.
            gen.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
            // Close the output file.
            tw.Close();
        }
        //</Snippet3>

        //<Snippet4>
        public static CompilerResults CompileCode(CodeDomProvider provider,
                                                  String sourceFile,
                                                  String exeFile)
        {
            // Obtain an ICodeCompiler from the CodeDomProvider.
            ICodeCompiler compiler = provider.CreateCompiler();
            // Configure a CompilerParameters that links System.dll
            // and produces the specified executable file.
            String [] referenceAssemblies = {"System.dll"};
            CompilerParameters cp = new CompilerParameters(referenceAssemblies,
                                                           exeFile, false);
            // Generate an executable rather than a DLL file.
            cp.GenerateExecutable = true;

            // Invoke compilation.
            CompilerResults cr = compiler.CompileAssemblyFromFile(cp, sourceFile);
            // Return the results of compilation.
            return cr;
        }
        //</Snippet4>
    }

    public class CodeDomExampleForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button run_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.Button compile_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.Button generate_button = new System.Windows.Forms.Button();
        private System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox();
        private System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox();
        private System.Windows.Forms.Label label1 = new System.Windows.Forms.Label();

        private void generate_button_Click(object sender, System.EventArgs e)
        {
            CodeDomProvider provider = GetCurrentProvider();
            CodeDomExample.GenerateCode(provider, CodeDomExample.BuildHelloWorldGraph());

            // Build the source file name with the appropriate
            // language extension.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = "TestGraph" + provider.FileExtension;
            }
            else
            {
                sourceFile = "TestGraph." + provider.FileExtension;
            }

            // Read in the generated source file and
            // display the source text.
            StreamReader sr = new StreamReader(sourceFile);
            textBox1.Text = sr.ReadToEnd();
            sr.Close();
        }

        private void compile_button_Click(object sender, System.EventArgs e)
        {
            CodeDomProvider provider = GetCurrentProvider();

            // Build the source file name with the appropriate
            // language extension.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = "TestGraph" + provider.FileExtension;
            }
            else
            {
                sourceFile = "TestGraph." + provider.FileExtension;
            }

            // Compile the source file into an executable output file.
            CompilerResults cr = CodeDomExample.CompileCode(provider,
                                                            sourceFile,
                                                            "TestGraph.exe");

            if(cr.Errors.Count > 0)
            {
                // Display compilation errors.
                textBox1.Text = "Errors encountered while building " +
                                sourceFile + " into " +cr.PathToAssembly+": \r\n\n";
                foreach(CompilerError ce in cr.Errors)
                    textBox1.AppendText(ce.ToString()+"\r\n");
                run_button.Enabled = false;
            }
            else
            {
                textBox1.Text = "Source " + sourceFile + " built into " +
                                cr.PathToAssembly+" with no errors.";
                run_button.Enabled = true;
            }
        }

        private void run_button_Click(object sender,
            System.EventArgs e)
        {
            Process.Start("TestGraph.exe");
        }

        private CodeDomProvider GetCurrentProvider()
        {
            CodeDomProvider provider;
            switch((string)this.comboBox1.SelectedItem)
            {
                case "CSharp":
                    provider = new CSharpCodeProvider();
                    break;
                case "Visual Basic":
                    provider = new VBCodeProvider();
                    break;
                default:
                    provider = new CSharpCodeProvider();
                    break;
            }
            return provider;
        }

        public CodeDomExampleForm()
        {
            this.SuspendLayout();
            // Set properties for label1
            this.label1.Location = new System.Drawing.Point(395, 20);
            this.label1.Size = new Size(180, 22);
            this.label1.Text = "Select a programming language:";
            // Set properties for comboBox1
            this.comboBox1.Location = new System.Drawing.Point(560, 16);
            this.comboBox1.Size = new Size(190, 23);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Items.AddRange( new string[] { "CSharp", "Visual Basic" } );
            this.comboBox1.Anchor = System.Windows.Forms.AnchorStyles.Left
                                    | System.Windows.Forms.AnchorStyles.Right
                                    | System.Windows.Forms.AnchorStyles.Top;
            this.comboBox1.SelectedIndex = 0;
            // Set properties for generate_button.
            this.generate_button.Location = new System.Drawing.Point(8, 16);
            this.generate_button.Name = "generate_button";
            this.generate_button.Size = new System.Drawing.Size(120, 23);
            this.generate_button.Text = "Generate Code";
            this.generate_button.Click += new System.EventHandler(this.generate_button_Click);
            // Set properties for compile_button.
            this.compile_button.Location = new System.Drawing.Point(136, 16);
            this.compile_button.Name = "compile_button";
            this.compile_button.Size = new System.Drawing.Size(120, 23);
            this.compile_button.Text = "Compile";
            this.compile_button.Click += new System.EventHandler(this.compile_button_Click);
            // Set properties for run_button.
            this.run_button.Enabled = false;
            this.run_button.Location = new System.Drawing.Point(264, 16);
            this.run_button.Name = "run_button";
            this.run_button.Size = new System.Drawing.Size(120, 23);
            this.run_button.Text = "Run";
            this.run_button.Click += new System.EventHandler(this.run_button_Click);
            // Set properties for textBox1.
            this.textBox1.Anchor = (System.Windows.Forms.AnchorStyles.Top
                                     | System.Windows.Forms.AnchorStyles.Bottom
                                     | System.Windows.Forms.AnchorStyles.Left
                                     | System.Windows.Forms.AnchorStyles.Right);
            this.textBox1.Location = new System.Drawing.Point(8, 48);
            this.textBox1.Multiline = true;
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(744, 280);
            this.textBox1.Text = "";
            // Set properties for the CodeDomExampleForm.
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(768, 340);
            this.MinimumSize = new System.Drawing.Size(750, 340);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {this.textBox1,
                this.run_button, this.compile_button, this.generate_button,
                this.comboBox1, this.label1 });
            this.Name = "CodeDomExampleForm";
            this.Text = "CodeDom Hello World Example";
            this.ResumeLayout(false);
        }

        protected override void Dispose( bool disposing )
        {
            base.Dispose( disposing );
        }

        [STAThread]
        static void Main()
        {
            Application.Run(new CodeDomExampleForm());
        }
    }
}
參考：
http://longhorn.msdn.microsoft.com/?//longhorn.msdn.microsoft.com/lhsdk/ref/ns/system.codedom.compiler/c/codedomprovider/codedomprovider.aspx


使用 System.IO 讀取文字檔
底下連結的文章示範如何從文字檔擷取資訊，並且使用 ArrayList 類別顯示這項資訊給使用者。
http://support.microsoft.com/default.aspx?scid=kb;EN-US;306777


確認檔案是否存在
using System.IO;
...
private
void button1_Click(object sender, System.EventArgs e)
{
string file
= @"c:\temp\a.ini";
if (File.Exists(file) == true)
{
MessageBox.Show("已存在!");
}
}


檔案拷貝
using System;
using System.IO;
public struct modmain
{
void
Main()
{
File.Copy("c:\autoexec.bat",
"c:\autocopy.ext");
}
}
另一範例：
using System.IO;
...
private void button1_Click(object sender,
System.EventArgs e)
{
string FromFile = @"c:\temp\a.ini"; //來源
string ToFile = @"c:\temp\b.ini";
//目的
try
{
File.Copy(FromFile,ToFile);
}catch
(IOException)
{
MessageBox.Show("拷貝錯誤");
}

//亦這樣寫
//File.Copy(FromFile,ToFile,true);
}

private void button2_Click(object sender,
System.EventArgs e)
{
//亦可這樣
FileInfo fn1 = new
FileInfo(@"c:\temp\a.ini");
fn1.CopyTo(@"c:\temp\b.ini",true);
}


刪除檔案
using System.IO;
...
private void button3_Click(object sender, System.EventArgs e)
{
  //執行先判斷是否存在，在執行刪除動作，不然會出現錯誤
  string File = @"c:\temp\a.ini";
  System.IO.File.Delete(File);
}


開啟外部執行檔
程式碼：
using System;
using
System.Diagnostics;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
Process proc = new
Process();
proc.StartInfo.FileName =
@"Notepad.exe";
proc.StartInfo.Arguments =
"";
proc.Start();
}
}
}


取得目前執行中的GUI程式列表
說明：取得目前執行中的GUI程式列表。
程式碼：
using System;
using
System.Diagnostics;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
foreach ( Process p
in Process.GetProcesses(System.Environment.MachineName)
)
{
if(
p.MainWindowHandle !=
IntPtr.Zero)
{
//這是一個
GUI 應用程式
Console.WriteLine(
p ); // string s =
p.ToString();
}
}
}
}
}
結果：
System.Diagnostics.Process (SharpDevelop)
System.Diagnostics.Process (cmd)
System.Diagnostics.Process (explorer)
請按任意鍵繼續 . . .


取得全部執行中程式列表
程式碼：
using System;
using
System.Diagnostics;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
foreach ( Process p
in Process.GetProcesses()
)
{
Console.WriteLine(
p ); // string s =
p.ToString();
}
}
}
}

結果：
System.Diagnostics.Process (cmd)
System.Diagnostics.Process (cidaemon)
System.Diagnostics.Process (svchost)
System.Diagnostics.Process (services)
System.Diagnostics.Process (svchost)
System.Diagnostics.Process (smss)
System.Diagnostics.Process (cisvc)
System.Diagnostics.Process (sm56hlpr)
System.Diagnostics.Process (wmiprvse)
System.Diagnostics.Process (EarthAgent)
System.Diagnostics.Process (mdm)
System.Diagnostics.Process (svchost)
System.Diagnostics.Process (StOPP)
System.Diagnostics.Process (svchost)
System.Diagnostics.Process (svchost)
System.Diagnostics.Process (SpntSvc)
System.Diagnostics.Process (winlogon)
System.Diagnostics.Process (alg)
System.Diagnostics.Process (inetinfo)
System.Diagnostics.Process (Console1)
System.Diagnostics.Process (StWatchDog)
System.Diagnostics.Process (ctfmon)
System.Diagnostics.Process (SharpDevelop)
System.Diagnostics.Process (svchost)
System.Diagnostics.Process (csrss)
System.Diagnostics.Process (explorer)
System.Diagnostics.Process (Idle)
請按任意鍵繼續 . . .


取得電腦全部IP位址
程式碼：
using System;
using
System.Net;
namespace DefaultNamespace
{
class
MainClass
{
public static void Main(string[]
args)
{
string s
="";
System.Net.IPAddress[] addressList =
Dns.GetHostByName(Dns.GetHostName()).AddressList;
for (int i = 0; i < addressList.Length; i
++)
{
s += addressList[i].ToString() +
"\n";
}
Console.WriteLine("{0}",s);
}
}
}
結果：
192.168.0.1
220.131.5.131
請按任意鍵繼續 . . .


取得AssemblyName的程式名稱
using System;
using System.Windows.Forms;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main(string[] args)
  {
   MessageBox.Show(System.Reflection.Assembly.GetEntryAssembly().GetName().Name);
  }
 }
}


MDI基本範例
步驟：
一、主視窗設定：
1.檔案->新增專案->選擇「C#」->Windows應用程式->確定=>產生「MainForm.cs」
2.「專案管理」書籤->更改「MainForm.cs」為「MDIForm.cs」
3.切換到「表單視窗設計」書籤->修改MainForm屬性：
   (a)「Name」為MDIForm
   (b)「IsMDIContainer」 設為True
   (c)「WindowState」設為「Maximized」
4.切換到「程式碼編輯器」，將MDIForm.cs的名稱空間改為「MDI」
二、子視窗設定：
1.檔案->新增檔案->C#->表單->確定=>產生「form1.cs」
2.切換到「程式碼編輯器」，將form1.cs的名稱空間改為「MDI」
3.儲存
4.到專案管理->專案名稱按右鍵->新增->加入外部檔案「form1.cs」
三、回到「MDIForm主視窗」，加入開啟Form1程式碼：
如下：（紅色部分）
  public
MDIForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();
//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
//===new ChildForm1===
Form1
ChildForm1=new
Form1();
ChildForm1.MdiParent=this;
ChildForm1.Show();
}
四、執行本程式


MDI應用程式範例
(請參考 專案的處理--自製MDI範本)
步驟：
1.新增MDIForm視窗應用程式專案
2.新增表單Form1=>存成 form1.cs
3.新增表單Form2=>存成 form2.cs
4.開啟專案管理書籤==>加入外部檔案form1.cs、form2.cs到專案中
5.執行==>完成
MDI主視窗(MDIForm)
using System;
using System.Windows.Forms;
namespace MDIdemo
{
///
<summary>
/// Description of MDIForm.
///
</summary>
public class MDIForm :
System.Windows.Forms.Form
{
public
MDIForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
//===new ChildForm1===
Form1
ChildForm1=new
Form1();
ChildForm1.MdiParent=this;
ChildForm1.Show();
//===new
ChildForm2===
Form2 ChildForm2=new
Form2();
ChildForm2.MdiParent=this;
ChildForm2.Show();

}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MDIForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void
InitializeComponent()
{
//
// MDIForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
13);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Text = "MDIForm";
this.Name
=
"MDIForm";
this.IsMdiContainer=true;
}
#endregion
}
}
MDI子視窗(Form1)
using System;
using System.Windows.Forms;
namespace MDIdemo
{
///
<summary>
/// Description of Form1.
///
</summary>
public class Form1 :
System.Windows.Forms.Form
{
public
Form1()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

#region
Windows Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void
InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
13);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Text = "Form1";
this.Name =
"Form1";
}
#endregion
}
}
MDI子視窗(Form2)
using System;
using System.Windows.Forms;
namespace MDIdemo
{
///
<summary>
/// Description of Form2.
///
</summary>
public class Form2 :
System.Windows.Forms.Form
{
public
Form2()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

#region
Windows Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void
InitializeComponent()
{
//
// Form2
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
13);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Text = "Form2";
this.Name =
"Form2";
}
#endregion
}
}


取得其他表單變數
將form1的instance傳給form2。
class form1
{
public string str1;
void Button1_Click( ......  )
{
form2 f2 = new
form2();
f2.f1 = this;
}
}
class form2
{
public form1
f1;
private void func1()
{
string str = f1.str1;
}
}
[MainForm程式碼]
using System;
using System.Windows.Forms;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button1;
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.button1 = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(184, 128);
   this.button1.Name = "button1";
   this.button1.TabIndex = 0;
   this.button1.Text = "button1";
   this.button1.Click += new System.EventHandler(this.Button1Click);
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Controls.Add(this.button1);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.ResumeLayout(false);
  }
  #endregion

  public string str1;
  void Button1Click(object sender, System.EventArgs e)
  {
           Form1 f2 = new Form1();
             f2.f1 = this;
  }

 }
}
[Form1程式碼]
using System;
using System.Windows.Forms;
namespace DefaultNamespace
{
///
<summary>
/// Description of Form1.
///
</summary>
public class Form1 :
System.Windows.Forms.Form
{
public
Form1()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

#region
Windows Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void
InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
13);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Text = "Form1";
this.Name =
"Form1";
}
#endregion

 public MainForm f1;
 private void func1()
 {
      string str = f1.str1;
 }
 }
}


Label 屬性設定
1.Label 自動調整大小設定：
label1.AutoSize = true;
label2.AutoSize = false;
□
2. 使用 Label 設定焦點位置：
Label1.Text="label1(&A)";
Label2.Text="label2(&B)";
Label3.Text="label3(&C)";
如圖：
例如：鍵盤使用「Alt」+「C」切換到textBox3位置


LinkLabel 超連結標籤設定
一、開啟文件：
private void linkLabel1_Click(object sender, System.EventArgs e)
{
  System.Diagnostics.Process.Start(@"c:\temp\" + this.linkLabel1.Text);
}
二、開啟網站：
linkLabel1.Text="http://tw.yahoo.com";
private void linkLabel1_LinkClicked(object sender,
                          System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
  System.Diagnostics.Process.Start(this.linkLabel1.Text);
}
三、包含文字與圖片的超連結：
linkLabel1.Text="c:\文章.txt";
linkLabel1.Image="圖片.bmp";
private void linkLabel1_Click(object sender, System.EventArgs e)
{
  System.Diagnostics.Process.Start(@"c:\temp\" + this.linkLabel1.Text);
}


Button 屬性設定
一、Button 的文字設定：
this.button1.Text = "按扭";
二、Button 的停用設定：
this.button1.Enabled = false;
三、Button 的位置設定：
this.button1.TextAlign = ContentAlignment.BottomCenter; //靠下置中
其他：BottomCenter、BottomLeft、
BottomRight、MiddleCenter、
MiddleLeft、MiddleRight
四、Button 的外觀設定：
this.button1.FlatStyle = FlatStyle.Flat;
this.button2.FlatStyle = FlatStyle.Popup;
this.button3.FlatStyle = FlatStyle.Standard;
this.button4.FlatStyle = FlatStyle.System; //XP效果
五、設定Button上的圖示：
this.button1.Image = System.Drawing.Image.FromFile(@"c:\temp\agentdp2.ico");
註:ImageAlign為設定圖示位置


Button 取得子視窗傳回值
private void button1_Click_1(object sender,
System.EventArgs e)
{
Form2 f = new Form2(); //建立Form2子表單視窗
f.ShowDialog(this);
f.Dispose();  /* 資源釋放 */
if (f.DialogResult ==
DialogResult.OK)
{
textBox1.Text =
"OK";
}
if (f.DialogResult ==
DialogResult.Cancel)
{
textBox1.Text =
"Cancel";
}
}
子表單視窗，兩按鈕設定如下：
this.button1.DialogResult = DialogResult.OK;
this.button2.DialogResult = DialogResult.Cancel;


Button Sender判斷
1.表單建立三個按鈕、和一個textBox文字盒
2.建立自訂的myEvent事件，程式碼如下：
 private void myEvent(object sender, System.EventArgs e)
  {
   Button btn = (Button)sender;
   if (btn.Name == "button1")
   {
    textBox1.Text = "按扭1";
   }
   if (btn.Name == "button2")
   {
    textBox1.Text = "按扭2";
   }
   if (btn.Name == "button3")
   {
    textBox1.Text = "按扭3";
   }
  }
3.點選各個按鈕的Click事件，選擇引用myEvent事件
4.完成「Button Sender判斷」
[完整程式碼]
/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2004/8/30
 * Time: 下午 08:30
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;
namespace DefaultNamespace
{
///
<summary>
/// Description of MainForm.
///
</summary>
public class MainForm :
System.Windows.Forms.Form
{
private
System.Windows.Forms.Button button3;
private
System.Windows.Forms.Button button1;
private
System.Windows.Forms.TextBox textBox1;
private
System.Windows.Forms.Button button2;
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
this.button2 = new
System.Windows.Forms.Button();
this.textBox1 = new
System.Windows.Forms.TextBox();
this.button1 = new
System.Windows.Forms.Button();
this.button3 = new
System.Windows.Forms.Button();
this.SuspendLayout();
//
// button2
//
this.button2.Location = new System.Drawing.Point(96,
80);
this.button2.Name =
"button2";
this.button2.TabIndex =
1;
this.button2.Text =
"button2";
this.button2.Click += new
System.EventHandler(this.myEvent);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(88,
24);
this.textBox1.Name =
"textBox1";
this.textBox1.TabIndex =
3;
this.textBox1.Text = "textBox1";
//
// button1
//
this.button1.Location = new System.Drawing.Point(16,
80);
this.button1.Name =
"button1";
this.button1.TabIndex =
0;
this.button1.Text =
"button1";
this.button1.Click += new
System.EventHandler(this.myEvent);
//
// button3
//
this.button3.Location = new System.Drawing.Point(176,
80);
this.button3.Name =
"button3";
this.button3.TabIndex =
2;
this.button3.Text =
"button3";
this.button3.Click += new
System.EventHandler(this.myEvent);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
15);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name
= "MainForm";
this.Text =
"MainForm";
this.ResumeLayout(false);
}
#endregion

private void myEvent(object sender,
System.EventArgs e)
{
Button btn =
(Button)sender;
if (btn.Name ==
"button1")
{
textBox1.Text =
"按扭1";
}
if (btn.Name ==
"button2")
{
textBox1.Text =
"按扭2";
}
if (btn.Name ==
"button3")
{
textBox1.Text =
"按扭3";
}
}
 }
}


CheckBox 屬性設定
一、CheckBox 外觀設定：
(1)文字位置：
checkBox1.CheckAlign = ContentAlignment.MiddleLeft;
checkBox2.CheckAlign = ContentAlignment.MiddleRight;
( 2)按鈕樣式：
checkBox3.Appearance = Appearance.Button;
二、CheckBox初始化設定：
checkBox1.Checked = true;
取得checkBox狀態:
 checkBox2.CheckState = CheckState.Checked;
三、CheckBox 中間狀態設定：
checkBox1.ThreeState = true;


CheckBox 狀態判斷寫法：
private void button1_Click(object sender, System.EventArgs e)
{
    if (checkBox1.Checked == true)
    {
        MessageBox.Show("已選擇為TRUE");
    }
    //判斷狀態
    if (checkBox1.CheckState == CheckState.Checked)
    {
        MessageBox.Show("已選擇為TRUE");
    }
}


使用CheckedChanged事件判斷CheckBox是否改變狀態寫法：
private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
{
    string a;
    if (checkBox1.Checked == true)
    {
        a = "為TRUE";
    }
    else
    {
        a = "為False";
    }
    MessageBox.Show(a);
}


判斷選取狀態
/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2004/9/2
 * Time:
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;
namespace
DefaultNamespace
{
/// <summary>
/// Description of
MainForm.
/// </summary>
public class MainForm :
System.Windows.Forms.Form
{
private
System.Windows.Forms.TextBox textBox1;
private
System.Windows.Forms.Button button1;
private
System.Windows.Forms.RadioButton radioButton1;
private
System.Windows.Forms.RadioButton radioButton2;
private
System.Windows.Forms.RadioButton radioButton3;
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
this.radioButton3 = new
System.Windows.Forms.RadioButton();
this.radioButton2 = new
System.Windows.Forms.RadioButton();
this.radioButton1 = new
System.Windows.Forms.RadioButton();
this.button1 = new
System.Windows.Forms.Button();
this.textBox1 = new
System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// radioButton3
//
this.radioButton3.Location = new System.Drawing.Point(8,
56);
this.radioButton3.Name =
"radioButton3";
this.radioButton3.TabIndex =
2;
this.radioButton3.Text =
"radioButton3";
//
//
radioButton2
//
this.radioButton2.Location = new System.Drawing.Point(8,
32);
this.radioButton2.Name =
"radioButton2";
this.radioButton2.TabIndex =
1;
this.radioButton2.Text =
"radioButton2";
//
//
radioButton1
//
this.radioButton1.Checked =
true;
this.radioButton1.Location = new
System.Drawing.Point(8, 8);
this.radioButton1.Name =
"radioButton1";
this.radioButton1.TabIndex =
0;
this.radioButton1.TabStop =
true;
this.radioButton1.Text =
"radioButton1";
//
//
button1
//
this.button1.Location =
new System.Drawing.Point(144, 32);
this.button1.Name =
"button1";
this.button1.TabIndex =
3;
this.button1.Text =
"button1";
this.button1.Click += new
System.EventHandler(this.Button1Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(8,
88);
this.textBox1.Name =
"textBox1";
this.textBox1.Size = new
System.Drawing.Size(200, 22);
this.textBox1.TabIndex =
4;
this.textBox1.Text = "textBox1";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
15);
this.ClientSize = new System.Drawing.Size(232,
126);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.radioButton3);
this.Controls.Add(this.radioButton2);
this.Controls.Add(this.radioButton1);
this.Name
= "MainForm";
this.Text =
"MainForm";
this.ResumeLayout(false);
}
#endregion
void Button1Click(object sender,
System.EventArgs e)
{
if (radioButton1.Checked ==
true)
{
textBox1.Text =
"radioButton1已被選取";
}
if (radioButton2.Checked ==
true)
{
textBox1.Text =
"radioButton2已被選取";
}
if (radioButton3.Checked ==
true)
{
textBox1.Text =
"radioButton3已被選取";
}
  }

 }
}


基本用法
groupBox1的Text屬性設為：第一群組
groupBox2的Text屬性設為：第二群組
如圖：


checkedListBox 新增資料
選擇checkedListBox的Items屬性：
依序填入：
check1
check2
check3
或程式寫法：
checkedListBox1.Items.Add("check1");
checkedListBox1.Items.Add("check2");
checkedListBox1.Items.Add("check3");


檢查checkedListBox項目數
一、已存在的項目數：
  void Button1Click(object sender, System.EventArgs e)
  {
   int cnt = checkedListBox1.Items.Count;
   MessageBox.Show(cnt.ToString());
  }

二、已設為True的項目數：
  void Button2Click(object sender, System.EventArgs e)
  {
   int cnt = checkedListBox1.CheckedItems.Count;
   MessageBox.Show(cnt.ToString());
  }


取得被選取的項目名稱
void Button1Click(object sender, System.EventArgs
e)
{
for (int i=0; i< checkedListBox1.CheckedItems.Count;i++)
{
MessageBox.Show(checkedListBox1.CheckedItems[i].ToString());
}
}
結果：(若選擇以下兩者為真，則顯示以下名稱)
check1
check3
同樣效果，另一寫法：
  void Button1Click(object sender,
System.EventArgs e)
{
foreach (string
a in checkedListBox1.CheckedItems)
{
MessageBox.Show(a);
}
}


設定測試框立體樣式
void Button2Click(object sender, System.EventArgs e)
  {
   checkedListBox1.ThreeDCheckBoxes = true;
  }


設為可重複選項
this.checkedListBox1.MultiColumn = true;


新增資料
設定ComboBox的Items屬性：
依序加入：
item1
item2
item3
或 程式寫法：
comboBox1.Items.Clear();
comboBox1.Items.Add("item1");
comboBox1.Items.Add("item2");
comboBox1.Items.Add("item3");


設定初始值
comboBox1.Text = "item2";
comboBox1.Items.Clear();
comboBox1.Items.Add("item1");
comboBox1.Items.Add("item2");
comboBox1.Items.Add("item3");


外觀樣式設定
有三種：
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
comboBox2.DropDownStyle = ComboBoxStyle.Simple;
comboBox3.DropDownStyle = ComboBoxStyle.DropDownList;


取得comboBox的項目資料
// text
string a = comboBox1.Text;
MessageBox.Show(a+"顯示已取得的資料");

//
SelectedItem
if (comboBox1.SelectedItem != null)
{
string b =
comboBox1.SelectedItem.ToString();
MessageBox.Show(b+"取得已選取的項目資料");
}

//
SelectedIndex
if (comboBox1.SelectedIndex != -1)
{
int i =
comboBox1.SelectedIndex;
string c =
comboBox1.Items[i].ToString();
MessageBox.Show(c+"依據索引值取得項目資料");
}


SelectedIndexChanged事件
When the item which is selected modifies:
private void comboBoxDrives_SelectedIndexChanged(object sender, System.EventArgs e)
{
 string a = comboBox1.SelectedItem as string;
 if ( a == null ) return;
}


加入子節點
.在.Net的程式中創建一個TreeView的元件，其實就是創建了一個可以放置TreeNode節點的“容器”(Container)。而在該容器中加入一個節點，其實就是加入一個TreeNode物件，刪除一個節點，就是刪除一個TreeNode物件。

    TreeView元件雖然是一個操作起來比較麻煩的元件，但歸根到底，可以總結滛三種基本操作：加入子節點、加入兄弟節點和刪除節點

加入子節點：

    所謂子節點，就是處於選定節點的下一級節點。加入子節點的具體過程是：首先要在TreeView元件中定位要加入的子節點的位置，然後創建一個節點物件，然後利用TreeVeiw類中對節點的加入方法（即：Add ( )方法），加入此節點物件。

if(myTreeView.SelectedNode!=null)
{
 TreeNode ChildNode=new TreeNode(“子節點”);
 myTreeView.SelectedNode.Nodes.Add(ChildNode);
 myTreeView.ExpandAll();
}


加入兄弟節點
  所謂兄弟節點，就是在選定的節點的平級的節點。加入兄弟節點的方法和加入子節點的方法基本一致，只是在最後的實現方法上有著略微的區別。
if(myTreeView.SelectedNode!=null)
{
TreeNode
BrotherNode=new TreeNode(“兄弟節點”);
myTreeView.SelectedNode.Parent.Nodes.Add(BrotherNode);
myTreeView.ExpandAll();
}


刪除節點
    刪除節點必須保證要刪除的節點沒有下一級節點，否則必須先刪除此節點中的所有下一級節點，然後再刪除此節點。
//判斷選定的節點是否存在下一級節點
if ( myTreeView.SelectedNode.Nodes.Count == 0 )
//刪除節點
treeView1.SelectedNode.Remove () ;


一些其他常用操作
這些常用操作無非是，展開所有節點，展開指定的節點、和折疊所有節點。

展開所有節點：

    要展開TreeView元件中的所有節點，首先就要把選定的節點指標定位在TreeView元件的根節點上，然後調用選定元件的ExpandAll方法就可以了，下面是具體代碼：
//定位根節點
myTreeView.SelectedNode = myTreeView.Nodes [0] ;
//展開元件中的所有節點
treeView1.SelectedNode.ExpandAll ( ) ;

折疊所有節點：

    折疊所有節點和展開所有節點是一組互操作.
//定位根節點
myTreeView.SelectedNode = myTreeView.Nodes [0] ;
//折疊元件中所有節點
myTreeView.SelectedNode.Collapse ( ) ;

展開選定節點的下一級節點：

    由於只是展開下一級節點，所以就沒有必要用ExpandAll ( )方法了。展開下一級節點只需要調用Expand ( )方法就可以了，下面是具體的實現代碼：

myTreeView.SelectedNode.Expand ( ) ;


取得所選取的顏色
private void button1_Click(object sender, System.EventArgs e)
{
    if (colorDialog1.ShowDialog() == DialogResult.OK)
    {
        button1.ForeColor = colorDialog1.Color;
    }
}


開啟colorDialog延伸功能
colorDialog1.FullOpen = true;


使用 ADO.NET 連接到資料庫並執行命令
底下連結的文章說明如何使用 ActiveX Data Objects (ADO) .NET 連接到資料庫並執行命令。
http://support.microsoft.com/?id=306636


Read and Write BLOB Data
http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q309158&


Copy a Picture from a Database Directly to a PictureBox Control
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q317701


 read and save Images in a Sql Server Database using ADO.NET
http://www.c-sharpcorner.com/Code/2002/Feb/FlashCardsMG.asp


/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2004/8/1
 * Time: 下午 03:15
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace mdbproject
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.DataGrid dataGrid1;
  private System.Data.DataSet dataSet1;
  private System.Data.OleDb.OleDbConnection oleDbConnection1;
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
   this.dataSet1 = new System.Data.DataSet();
   this.dataGrid1 = new System.Windows.Forms.DataGrid();
   ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
   this.SuspendLayout();
   //
   // dataSet1
   //
   this.dataSet1.DataSetName = "NewDataSet";
   this.dataSet1.Locale = new System.Globalization.CultureInfo("zh-TW");
   this.dataSet1.Namespace = "mdbproject";
   //
   // dataGrid1
   //
   this.dataGrid1.DataMember = "";
   this.dataGrid1.DataSource = this.dataSet1;
   this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
   this.dataGrid1.Location = new System.Drawing.Point(8, 8);
   this.dataGrid1.Name = "dataGrid1";
   this.dataGrid1.Size = new System.Drawing.Size(560, 256);
   this.dataGrid1.TabIndex = 0;
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(584, 278);
   this.Controls.Add(this.dataGrid1);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Load += new System.EventHandler(this.MainFormLoad);
   ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
   this.ResumeLayout(false);
  }
  #endregion
  void MainFormLoad(object sender, System.EventArgs e)
  {
   oleDbConnection1.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb";
   oleDbConnection1.Open();
   OleDbDataAdapter adapter = new OleDbDataAdapter();
         adapter.SelectCommand = new OleDbCommand("select * from myTable", oleDbConnection1);
         adapter.Fill(dataSet1);
  }

 }
}


資料庫連結設定大全

  • SQL Server
    • ODBC

      • Standard Security:
        "Driver={SQL Server};Server=Aron1;Database=pubs;Uid=sa;Pwd=asdasd;"
      • Trusted connection:
        "Driver={SQL Server};Server=Aron1;Database=pubs;Trusted_Connection=yes;"
      • Prompt for username and password:
        oConn.Properties("Prompt") = adPromptAlways
        oConn.Open "Driver={SQL Server};Server=Aron1;DataBase=pubs;"
    • OLE DB, OleDbConnection (.NET)

      • Standard Security:
        "Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"
      • Trusted Connection:
        "Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"
        (use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)
      • Prompt for username and password:
        oConn.Provider = "sqloledb"
        oConn.Properties("Prompt") = adPromptAlways
        oConn.Open "Data Source=Aron1;Initial Catalog=pubs;"
      • Connect via an IP address:
        "Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"
        (DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))
    • SqlConnection (.NET)

      • Standard Security:
        "Data Source=Aron1;Initial Catalog=pubs;User Id=sa;Password=asdasd;"
        - or -
        "Server=Aron1;Database=pubs;User ID=sa;Password=asdasd;Trusted_Connection=False"
        (booth connection strings produces the same result)
      • Trusted Connection:
        "Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"
        - or -
        "Server=Aron1;Database=pubs;Trusted_Connection=True;"
        (booth connection strings produces the same result)
        (use serverName\instanceName as Data Source to use an specifik SQLServer instance, only SQLServer2000)
      • Connect via an IP address:
        "Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"
        (DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the port to use (1433 is the default))
      • Declare the SqlConnection:
        C#:
using System.Data.SqlClient;
SqlConnection
      oSQLConn = new SqlConnection();
oSQLConn.ConnectionString="my
      connectionstring";
oSQLConn.Open();
        VB.NET:
        Imports System.Data.SqlClient
        Dim oSQLConn As SqlConnection = New SqlConnection()
        oSQLConn.ConnectionString="my connectionstring"
        oSQLConn.Open()
    • Data Shape

      • MS Data Shape
        "Provider=MSDataShape;Data Provider=SQLOLEDB;Data Source=Aron1;Initial Catalog=pubs;User ID=sa;Password=asdasd;"
        Want to learn data shaping? Check out 4GuyfFromRolla's great article about Data Shaping >>
    • Read more

      • How to define wich network protocol to use

        • Example:
          "Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=sa;Password=asdasd;"

          Name | Network library
          dbnmpntw | Win32 Named Pipes
          dbmssocn | Win32 Winsock TCP/IP
          dbmsspxn | Win32 SPX/IPX
          dbmsvinn | Win32 Banyan Vines
          dbmsrpcn | Win32 Multi-Protocol (Windows RPC)

          Important note!
          When connecting through the SQLOLEDB provider use the syntax Network Library=dbmssocn
          and when connecting through MSDASQL provider use the syntax Network=dbmssocn

      • All SqlConnection connectionstring properties

        • This table shows all connectionstring properties for the ADO.NET SqlConnection object. Most of the properties are also used in ADO. All properties and descriptions is from msdn.

          Name | Default | Description
          Application Name | The name of the application, or '.Net SqlClient Data Provider' if no application name is provided.
          AttachDBFilename
          -or-
          extended properties
          -or-
          Initial File Name           		The name of the primary file, including the full path name, of an attachable database. The database name must be specified with the keyword 'database'.
          Connect Timeout
          -or-
          Connection Timeout           		15 The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
          Connection Lifetime | 0 | When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. Useful in clustered configurations to force load balancing between a running server and a server just brought on-line.
          Connection Reset | 'true' | Determines whether the database connection is reset when being removed from the pool. Setting to 'false' avoids making an additional server round-trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset.
          Current Language | The SQL Server Language record name.
          Data Source
          -or-
          Server
          -or-
          Address
          -or-
          Addr
          -or-
          Network Address           		The name or network address of the instance of SQL Server to which to connect.
          Enlist | 'true' | When true, the pooler automatically enlists the connection in the creation thread's current transaction context.
          Initial Catalog
          -or-
          Database           		The name of the database.
          Integrated Security
          -or-
          Trusted_Connection           		'false' Whether the connection is to be a secure connection or not. Recognized values are 'true', 'false', and 'sspi', which is equivalent to 'true'.
          Max Pool Size | 100 | The maximum number of connections allowed in the pool.
          Min Pool Size | 0 | The minimum number of connections allowed in the pool.
          Network Library
          -or-
          Net           		'dbmssocn' The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP).
          The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used.
          Packet Size | 8192 | Size in bytes of the network packets used to communicate with an instance of SQL Server.
          Password
          -or-
          Pwd           		The password for the SQL Server account logging on.
          Persist Security Info | 'false' | When set to 'false', security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password.
          Pooling | 'true' | When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool.
          User ID | The SQL Server login account.
          Workstation ID | the local computer name | The name of the workstation connecting to SQL Server.

          Note
          Use ; to separate each property.
          If a name occurs more than once, the value from the last one in the connectionstring will be used.
          If you are building your connectionstring in your app using values from user input fields, make sure the user can't change the connectionstring by inserting an additional property with another value within the user value.
    • Access
      • ODBC

        • Standard Security:
          "Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;"
        • Workgroup:
          "Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;SystemDB=C:\mydatabase.mdw;"
        • Exclusive:
          "Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;Exclusive=1;Uid=admin;Pwd="
      • OLE DB, OleDbConnection (.NET)

        • Standard security:
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;User Id=admin;Password=;"
        • Workgroup (system database):
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:System Database=system.mdw;"
        • With password:
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;Jet OLEDB:Database Password=MyDbPassword;"
    • Oracle
      • ODBC

        • New version:
          "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=Username;Pwd=asdasd;"
        • Old version:
          "Driver={Microsoft ODBC Driver for Oracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;"
      • OLE DB, OleDbConnection (.NET)

        • Standard security:
          "Provider=msdaora;Data Source=MyOracleDB;User Id=UserName;Password=asdasd;"
          This one's from Microsoft, the following are from Oracle
        • Standard Security:
          "Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;User Id=Username;Password=asdasd;"
        • Trusted Connection:
          "Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;"
      • OracleConnection (.NET)

        • Standard:
          "Data Source=Oracle8i;Integrated Security=yes;"
          This one works only with Oracle 8i release 3 or later
        • Specifying username and password:
          "Data Source=Oracle8i;User Id=username;Password=passwd;Integrated Security=no;"
          This one works only with Oracle 8i release 3 or later
        • Declare the OracleConnection:
          C#:
using
      System.Data.OracleClient;
OracleConnection oOracleConn = new
      OracleConnection();
oOracleConn.ConnectionString = "my
      connectionstring";
oOracleConn.Open();
          VB.NET:
          Imports System.Data.OracleClient
          Dim oOracleConn As OracleConnection = New OracleConnection()
          oOracleConn.ConnectionString = "my connectionstring"
          oOracleConn.Open()
      • Core Labs OraDirect (.NET)

        • Standard:
          "User ID=scott; Password=tiger; Host=ora; Pooling=true; Min Pool Size=0;Max Pool Size=100; Connection Lifetime=0"
          Read more at Core Lab and the product page.
      • Data Shape

        • MS Data Shape:
          "Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;Data Source=orac;user id=username;password=mypw"
          Want to learn data shaping? Check out 4GuyfFromRolla's great article about Data Shaping >>
    • MySQL
      • ODBC

        • Local database:
          "Driver={mySQL};Server=mySrvName;Option=16834;Database=mydatabase;"
        • Remote database:
          "Driver={mySQL};Server=data.domain.com;Port=3306;Option=131072;Stmt=;Database=my-database;Uid=username;Pwd=password;"
      • OLE DB, OleDbConnection (.NET)

        • Standard:
          "Provider=MySQLProv;Data Source=mydb;User Id=UserName;Password=asdasd;"
      • MySqlConnection (.NET)

        • eInfoDesigns.dbProvider:
          "Data Source=server;Database=mydb;User ID=username;Password=pwd;Command Logging=false"
          This one is used with eInfoDesigns dbProvider, an add-on to .NET
        • Declare the MySqlConnection:
          C#:
using
      eInfoDesigns.dbProvider.MySqlClient;
MySqlConnection oMySqlConn = new
      MySqlConnection();
oMySqlConn.ConnectionString = "my
      connectionstring";
oMySqlConn.Open();
          VB.NET:
          Imports eInfoDesigns.dbProvider.MySqlClient
          Dim oMySqlConn As MySqlConnection = New MySqlConnection()
          oMySqlConn.ConnectionString = "my connectionstring"
          oMySqlConn.Open()
      • SevenObjects MySqlClient (.NET)

        • Standard:
          "Host=server; UserName=myusername; Password=mypassword;Database=mydb;"
          This is a freeware ADO.Net data provider from SevenObjects
      • Core Labs MySQLDirect (.NET)

        • Standard:
          "User ID=root; Password=pwd; Host=localhost; Port=3306; Database=test;Direct=true; Protocol=TCP; Compress=false; Pooling=true; Min Pool Size=0;Max Pool Size=100; Connection Lifetime=0"
          Read more at Core Lab and the product page.
    • Interbase
      • ODBC, Easysoft

        • Local computer:
          "Driver={Easysoft IB6 ODBC};Server=localhost;Database=localhost:C:\mydatabase.gdb;Uid=username;Pwd=password"
        • Remote Computer:
          "Driver={Easysoft IB6 ODBC};Server=ComputerName;Database=ComputerName:C:\mydatabase.gdb;Uid=username;Pwd=password"
          Read more about this driver: Easysoft ODBC-Interbase driver >>
      • ODBC, Intersolv

        • Local computer:
          "Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};Server=localhost;Database=localhost:C:\mydatabase.gdb;Uid=username;Pwd=password"
        • Remote Computer:
          "Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};Server=ComputerName;Database=ComputerName:C:\mydatabase.gdb;Uid=username;Pwd=password"
          This driver are provided by DataDirect Technologies >> (formerly Intersolv)
      • OLE DB, SIBPROvider

        • Standard:
          "provider=sibprovider;location=localhost:;data source=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey"
        • Specifying character set:
          "provider=sibprovider;location=localhost:;data source=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey;character set=ISO8859_1"
        • Specifying role:
          "provider=sibprovider;location=localhost:;data source=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey;role=DIGITADORES"
          Read more about SIBPROvider >>
          Read more about connecting to Interbase in this Borland Developer Network article http://community.borland.com/article/0,1410,27152,00.html
    • IBM DB2
      • OLE DB, OleDbConnection (.NET) from ms

        • TCP/IP:
          "Provider=DB2OLEDB;Network Transport Library=TCPIP;Network Address=XXX.XXX.XXX.XXX;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"
        • APPC:
          "Provider=DB2OLEDB;APPC Local LU Alias=MyAlias;APPC Remote LU Alias=MyRemote;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"
      • IBM's OLE DB Provider (shipped with IBM DB2 UDB v7 or above)

        • TCP/IP:
          Provider=IBMDADB2;Database=sample;HOSTNAME=db2host;PROTOCOL=TCPIP;PORT=50000;uid=myUserName;pwd=myPwd;
      • ODBC

        • Standard:
          "driver={IBM DB2 ODBC DRIVER};Database=myDbName;hostname=myServerName;port=myPortNum;protocol=TCPIP; uid=myUserName; pwd=myPwd"
    • Sybase
      • ODBC

        • Standard Sybase System 12 (or 12.5) Enterprise Open Client:
          "Driver={SYBASE ASE ODBC Driver};Srvr=Aron1;Uid=username;Pwd=password"
        • Standard Sybase System 11:
          "Driver={SYBASE SYSTEM 11};Srvr=Aron1;Uid=username;Pwd=password;"
          Do you know a userguide for Sybase System 11, 12, 12.5? E-mail the URL to connectionstrings.com now!! >>
        • Intersolv 3.10:
          "Driver={INTERSOLV 3.10 32-BIT Sybase};Srvr=Aron1;Uid=username;Pwd=password;"
        • Sybase SQL Anywhere (former Watcom SQL ODBC driver):
          "ODBC; Driver=Sybase SQL Anywhere 5.0; DefaultDir=c:\dbfolder\;Dbf=c:\mydatabase.db;Uid=username;Pwd=password;Dsn="""""
          Note! The two double quota following the DSN parameter at the end are escaped quotas (VB syntax), you may have to change this to your language specific escape syntax. The empty DSN parameter is indeed critical as not including it will result in error 7778.
          Read more in the Sybase SQL Anywhere User Guide >>
      • OLE DB

        • Adaptive Server Anywhere (ASA):
          "Provider=ASAProv;Data source=myASA"
          Read more in the ASA User Guide >>
        • Adaptive Server Enterprise (ASE) with Data Source .IDS file:
          "Provider=Sybase ASE OLE DB Provider; Data source=myASE"
          Note that you must create a Data Source .IDS file using the Sybase Data Administrator. These .IDS files resemble ODBC DSNs.
        • Adaptive Server Enterprise (ASE):
          "Provider=Sybase.ASEOLEDBProvider;Srvr=myASEserver,5000;Catalog=myDBname;User Id=username;Password=password"
          - some reports on problem using the above one, try the following as an alternative -

          "Provider=Sybase.ASEOLEDBProvider;Server Name=myASEserver,5000;Initial Catalog=myDBname;User Id=username;Password=password"
          This one works only from Open Client 12.5 where the server port number feature works,燼llowing fully qualified connection strings to be used without defining燼ny .IDS Data Source files.
      • AseConnection (.NET)

        • Standard:
          "Data Source='myASEserver';Port=5000;Database='myDBname';UID='username';PWD='password';"
        • Declare the AseConnection:
          C#:
using Sybase.Data.AseClient;
AseConnection
      oCon = new AseConnection();
oCon.ConnectionString="my connection
      string";
oCon.Open();
          VB.NET:
          Imports System.Data.AseClient
          Dim oCon As AseConnection = New AseConnection()
          oCon.ConnectionString="my connection string"
          oCon.Open()
    • Informix
      • ODBC

        • Informix 3.30:
          "Dsn='';Driver={INFORMIX 3.30 32 BIT};Host=hostname;Server=myserver;Service=service-name;Protocol=olsoctcp;Database=mydb;UID=username;PWD=myPwd
        • Informix-CLI 2.5:
          "Driver={Informix-CLI 2.5 (32 Bit)};Server=myserver;Database=mydb;Uid=username;Pwd=myPwd"
      • OLE DB

        • IBM Informix OLE DB Provider:
          "Provider=Ifxoledbc.2;password=myPw;User ID=myUser;Data Source=dbName@serverName;Persist Security Info=true"
    • Ingres
      • ODBC

        • DSN-less
          "Provider=MSDASQL.1;DRIVER=Ingres;SRVR=xxxxx;DB=xxxxx;Persist Security Info=False;uid=xxxx;pwd=xxxxx;SELECTLOOPS=N;Extended Properties="""SERVER=xxxxx;DATABASE=xxxxx;SERVERTYPE=INGRES""
    • Mimer SQL
      • ODBC

        • Standard Security:
          "Driver={MIMER};Database=mydb;Uid=myuser;Pwd=mypw;"
        • Prompt for username and password:
          "Driver={MIMER};Database=mydb;"
    • PostgreSQL
      • Core Labs PostgreSQLDirect (.NET)

        • Standard:
          "User ID=root; Password=pwd; Host=localhost; Port=5432; Database=testdb;Pooling=true; Min Pool Size=0; Max Pool Size=100; Connection Lifetime=0"
          Read more at Core Lab and the product page.
    • DSN
      • ODBC

        • DSN:
          "DSN=myDsn;Uid=username;Pwd=;"
        • File DSN:
          "FILEDSN=c:\myData.dsn;Uid=username;Pwd=;"
    • Excel
      • ODBC

        • Standard:
          "Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath;"

      • OLE DB

        • Standard:
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
          "HDR=Yes;" indicates that the first row contains columnnames, not data
          "IMEX=1;" tells the driver to always read "intermixed" data columns as text
          TIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$" and wrapped in "[" "]" brackets.
    • Text
      • ODBC

        • Standard:
          "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:\txtFilesFolder\;Extensions=asc,csv,tab,txt;"
      • OLE DB

        • Standard:
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\txtFilesFolder\;Extended Properties=""text;HDR=Yes;FMT=Delimited"""
          "HDR=Yes;" indicates that the first row contains columnnames, not data
    • DBF / FoxPro
      • ODBC

        • standard:
          "Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:\mydbpath;"
      • OLE DB, OleDbConnection (.NET)

        • standard:
          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;Password="
    • AS/400
      • OLE DB

        • IBM Client Access OLE DB provider:
          "PROVIDER=IBMDA400; DATA SOURCE=MY_SYSTEM_NAME;Uid=myUserName;Pwd=myPwd"
          Where MY_SYSTEM_NAME is the name given to the system connection in OperationsNavigator
      • ODBC

        • IBM Client Access ODBC driver:
          "Driver={Client Access ODBC Driver (32-bit)};System=my_system_name;Uid=myUserName;Pwd=myPwd"
    • Visual FoxPro
      • OLE DB, OleDbConnection (.NET)

        • Database container (.DBC):
          "Provider=vfpoledb.1;Data Source=C:\MyDbFolder\MyDbContainer.dbc;Password=MyPassWord;Collating Sequence=machine"
        • Free table directory:
          "Provider=vfpoledb.1;Data Source=C:\MyDataDirectory\;Password=MyPassWord;Collating Sequence=general"
          Read more (Microsoft msdn) >>
      • ODBC

        • Database container (.DBC):
          "Driver={Microsoft Visual FoxPro Driver};SourceType=DBC;SourceDB=c:\myvfpdb.dbc;Exclusive=No;Collate=Machine;"
        • Free Table directory:
          "Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=c:\myvfpdbfolder;Exclusive=No;Collate=Machine;"
          "Collate=Machine" is the default setting, for other settings check the list of supported collating sequences >>
          Microsoft Visual Foxpro site: http://msdn.microsoft.com/vfoxpro
    • Pervasive
      • ODBC

        • Standard:
          "Driver={Pervasive ODBC Client Interface};ServerName=srvname;dbq=@dbname"
          Pervasive ODBC info >>
      • OLE DB

        • Standard:
          "Provider=PervasiveOLEDB;Data Source=C:\path"
          Pervasive OLE DB info >>
    • UDL
      • UDL

        • UDL:
          "File Name=c:\myDataLink.udl;"


SharpDevelop Fidalgo 安裝MySQL元件
1.下載：ByteFX.Data.MySQLClient
        http://sourceforge.net/projects/mysqlnet/

2.安裝：ByteFX.MySqlClient.76=>Setup.msi

3.開啟SharpDevelop，安裝MySQL元件：
  =>工具(Tools)面版=>右鍵選單=>Configure Sidebar(引用項目)
  =>新增分類(New)=>設定名稱：MySQL.Net
  =>新增元件(Add Components)=>ByteFX.MySqlClient和ByteFX.MySqlClient.Design=>Ok
  =>ok

4.開新專案(New Combine)=>看工具(Tools)面版==>多一個MySQL.Net=>元件安裝完成


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的.NET程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/1
 * 建立時間: 下午 10:36
 * 功    能: MySQL資料庫連結
 * 修改日期:
 */
using System;
using System.Windows.Forms;
using ByteFX.Data.MySqlClient;

namespace MySQLproject
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.DataGrid dataGrid1;
  private System.Data.DataSet dataSet1;
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.dataSet1 = new System.Data.DataSet();
   this.dataGrid1 = new System.Windows.Forms.DataGrid();
   this.button1 = new System.Windows.Forms.Button();
   ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
   this.SuspendLayout();
   //
   // dataSet1
   //
   this.dataSet1.DataSetName = "NewDataSet";
   this.dataSet1.Locale = new System.Globalization.CultureInfo("zh-TW");
   this.dataSet1.Namespace = "mdbproject";
   //
   // dataGrid1
   //
   this.dataGrid1.DataMember = "";
   this.dataGrid1.DataSource = this.dataSet1;
   this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
   this.dataGrid1.Location = new System.Drawing.Point(8, 40);
   this.dataGrid1.Name = "dataGrid1";
   this.dataGrid1.Size = new System.Drawing.Size(560, 224);
   this.dataGrid1.TabIndex = 0;
   //
   // button1
   //
   this.button1.BackColor = System.Drawing.SystemColors.ActiveCaption;
   this.button1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
   this.button1.Location = new System.Drawing.Point(464, 8);
   this.button1.Name = "button1";
   this.button1.Size = new System.Drawing.Size(104, 24);
   this.button1.TabIndex = 1;
   this.button1.Text = "連線MySQL資料庫";
   this.button1.Click += new System.EventHandler(this.Button1Click);
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(584, 278);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.dataGrid1);
   this.Name = "MainForm";
   this.Text = "MainForm";
   ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
   this.ResumeLayout(false);
  }
  #endregion

  void Button1Click(object sender, System.EventArgs e)
  {
   MySqlConnection myConnection = new MySqlConnection("Database=delphi;Data Source=localhost;User Id=root;Password=");
   MySqlDataAdapter adapter = new MySqlDataAdapter();
   adapter.SelectCommand = new MySqlCommand("select * from forum_forum", myConnection);
   adapter.Fill(dataSet1);
   myConnection.Open();
  }
 }
}


ODBC.NET 方式連到MySQL
/**
* @sample    : mycon.cs
* @purpose   : Demo sample for ODBC.NET using Connector/ODBC
* @author    : Venu, venu@mysql.com
*
* (C) Copyright MySQL AB, 1995-2003
*
**/

/* build command
  *
  *  csc /t:exe
  *      /out:mycon.exe mycon.cs
  *      /r:Microsoft.Data.Odbc.dll
  */

using Console = System.Console;
using Microsoft.Data.Odbc;

namespace myodbc3
{
  class mycon
  {
    static void Main(string[] args)
    {
      try
      {
        //Connection string for Connector/ODBC 2.50
        /*string MyConString = "DRIVER={MySQL};" +
                             "SERVER=localhost;" +
                             "DATABASE=test;" +
                             "UID=venu;" +
                             "PASSWORD=venu;" +
                             "OPTION=3";
        */
        //Connection string for Connector/ODBC 3.51
        string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" +
                             "SERVER=localhost;" +
                             "DATABASE=test;" +
                             "UID=venu;" +
                             "PASSWORD=venu;" +
                             "OPTION=3";

        //Connect to MySQL using Connector/ODBC
        OdbcConnection MyConnection = new OdbcConnection(MyConString);
        MyConnection.Open();

        Console.WriteLine("\n !!! success, connected successfully !!!\n");

        //Display connection information
        Console.WriteLine("Connection Information:");
        Console.WriteLine("\tConnection String:" + MyConnection.ConnectionString);
        Console.WriteLine("\tConnection Timeout:" + MyConnection.ConnectionTimeout);
        Console.WriteLine("\tDatabase:" + MyConnection.Database);
        Console.WriteLine("\tDataSource:" + MyConnection.DataSource);
        Console.WriteLine("\tDriver:" + MyConnection.Driver);
        Console.WriteLine("\tServerVersion:" + MyConnection.ServerVersion);

        //Create a sample table
        OdbcCommand MyCommand = new OdbcCommand("DROP TABLE IF EXISTS my_odbc_net",MyConnection);
        MyCommand.ExecuteNonQuery();
        MyCommand.CommandText = "CREATE TABLE my_odbc_net(id int, name varchar(20), idb bigint)";
        MyCommand.ExecuteNonQuery();

        //Insert
        MyCommand.CommandText = "INSERT INTO my_odbc_net VALUES(10,'venu', 300)";
        Console.WriteLine("INSERT, Total rows affected:" + MyCommand.ExecuteNonQuery());;

        //Insert
        MyCommand.CommandText = "INSERT INTO my_odbc_net VALUES(20,'mysql',400)";
        Console.WriteLine("INSERT, Total rows affected:" + MyCommand.ExecuteNonQuery());

        //Insert
        MyCommand.CommandText = "INSERT INTO my_odbc_net VALUES(20,'mysql',500)";
        Console.WriteLine("INSERT, Total rows affected:" + MyCommand.ExecuteNonQuery());

        //Update
        MyCommand.CommandText = "UPDATE my_odbc_net SET id=999 WHERE id=20";
        Console.WriteLine("Update, Total rows affected:" + MyCommand.ExecuteNonQuery());

        //COUNT(*)
        MyCommand.CommandText = "SELECT COUNT(*) as TRows FROM my_odbc_net";
        Console.WriteLine("Total Rows:" + MyCommand.ExecuteScalar());

        //Fetch
        MyCommand.CommandText = "SELECT * FROM my_odbc_net";
        OdbcDataReader MyDataReader;
        MyDataReader =  MyCommand.ExecuteReader();
        while (MyDataReader.Read())
        {
         if(string.Compare(MyConnection.Driver,"myodbc3.dll") == 0) {
           Console.WriteLine("Data:" + MyDataReader.GetInt32(0) + " " +
                                       MyDataReader.GetString(1) + " " +
                                       MyDataReader.GetInt64(2)); //Supported only by Connector/ODBC 3.51
         }
         else {
           Console.WriteLine("Data:" + MyDataReader.GetInt32(0) + " " +
                                       MyDataReader.GetString(1) + " " +
                                       MyDataReader.GetInt32(2)); //BIGINTs not supported by Connector/ODBC
         }
        }

        //Close all resources
        MyDataReader.Close();
        MyConnection.Close();
      }
      catch (OdbcException MyOdbcException) //Catch any ODBC exception ..
      {
        for (int i=0; i < MyOdbcException.Errors.Count; i++)
        {
          Console.Write("ERROR #" + i + "\n" +
            "Message: " + MyOdbcException.Errors[i].Message + "\n" +
            "Native: " + MyOdbcException.Errors[i].NativeError.ToString() + "\n" +
            "Source: " + MyOdbcException.Errors[i].Source + "\n" +
            "SQL: " + MyOdbcException.Errors[i].SQLState + "\n");
        }
      }
    }
  }
}


顏色表示方式 (System.Drawing.Color)
顏色可用兩種表示方式：
1.System.Drawing.Color的表示："0xRRGGBB"
2.使用HexRgbString字串函數表示 ：Color.Red
範例：
//using System.Drawing;

public static String HexRgbString(Color color) {
 return String.Format("0x{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}

public static void Main(String[] args) {
 Console.WriteLine(HexRgbString(Color.Red));  // "0xFF0000"
}


畫單線範例
範例一：
using System.Drawing;
....
void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
{
 Graphics  g = e.Graphics;
 g.DrawLine(Pens.Black, 10, 10, 200, 100);
}
範例二：
using System.Drawing;
....
void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
{
 Graphics  g = e.Graphics;
 Pen Fpen = new Pen(Color.Black, 3.0F);//改變線的粗細3.0F=3.0
 g.DrawLine(Fpen, 10, 10, 200, 100);
}

範例三：
using System.Drawing;
....

void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
{
 Graphics  g = e.Graphics;
 Pen pen = new Pen(Color.Black, 3.0F);//改變線的粗細
 g.TranslateTransform(100, 100);      //平移X和Y各加100
 g.ScaleTransform(2, 3);              //X延伸2倍,Y延伸3倍
 g.RotateTransform(90);               //旋轉90度
 g.DrawLine(pen, 10, 10, 200, 100);   //畫直線
}
[完整程式]
/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/6
 * 建立時間: 上午 01:34
 * 功    能: Drawing with C# (畫線範例)
 * 修改日期: 上午 01:34
 */
using System;
using System.Windows.Forms;
using System.Drawing;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion
  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
       // Get the graphics object
       Graphics gfx = e.Graphics;
       // Create a new pen that we shall use for drawing the line
       Pen myPen = new Pen(Color.Black);
       // Loop and create a new line 10 pixels below the last one
       for(int i = 20; i < 250; i = i + 10)
        gfx.DrawLine(myPen, 20, i, 270, i);
  }
 }
}


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/6
 * 建立時間: 上午 01:34
 * 功    能: Drawing with C# (畫方格圖範例)
 * 修改日期: 上午 01:34
 */
using System;
using System.Windows.Forms;
using System.Drawing;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion
  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
            // Get the graphics object
            Graphics gfx = e.Graphics;
            // Create a new pen that we shall use for drawing the line
            Pen myPen = new Pen(Color.Black);
            // Loop and create a horizontal line 10 pixels below the last one
            for(int i = 20; i <= 250; i = i + 10)
            {
                gfx.DrawLine(myPen, 20, i, 270, i);
            }
            // Loop and create a vertical line 10 pixels next to the last one
            for(int x = 20; x < 280; x = x + 10)
            {
                gfx.DrawLine(myPen, x, 20, x, 250);
            }
  }
 }
}


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/6
 * 建立時間: 上午 01:34
 * 功    能: Drawing with C# (Rectangles範例)
 * 修改日期: 上午 01:34
 */
using System;
using System.Windows.Forms;
using System.Drawing;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion
  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
            // Get the graphics object
            Graphics gfx = e.Graphics;
            // Create a new pen that we shall use for drawing the line
            Pen myPen = new Pen(Color.Black);
            // Loop until the coordinates reach 250 (the lower right corner of the form)
            for(int i = 0; i < 250; i = i + 50)
            {
                // Draw a 50x50 pixels rectangle
                gfx.DrawRectangle(myPen, i, i, 50, 50);
            }
  }
 }
}


畫橢圓及圓形
畫橢圓
using System.Drawing;
...
 void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   Graphics g = this.CreateGraphics();
   Pen pen = new Pen(Color.Black, 1);
   g.DrawEllipse(pen, 0, 0, 100, 20);
  }
畫圓形
using System.Drawing;
...
 void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   Graphics g = this.CreateGraphics();
   Pen pen = new Pen(Color.Black, 1);
   g.DrawEllipse(pen, 0, 0, 100, 100);
  }
畫橢圓(填滿顏色)

using System.Drawing;
...
 void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   Graphics g = this.CreateGraphics();
   Pen pen = new Pen(Color.Black, 1);
   SolidBrush
solidBrush = new SolidBrush(Color.DarkCyan); //填滿顏色
g.FillEllipse(solidBrush, 0, 0,
100,
20);
//填滿顏色
g.DrawEllipse(pen, 0, 0, 100, 20);
}
畫圓形(填滿顏色)

using System.Drawing;
...
 void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   Graphics g = this.CreateGraphics();
   Pen pen = new Pen(Color.Black, 1);
   SolidBrush solidBrush = new SolidBrush(Color.DarkCyan); //填滿顏色
   g.FillEllipse(solidBrush, 0, 0, 100, 100);              //填滿顏色
   g.DrawEllipse(pen, 0, 0, 100, 100);
  }


畫半橢圓 (中心點、高度、角度控制)
程式碼：
using System;
using System.Windows.Forms;
using System.Drawing;

namespace
DefaultNamespace
{
/// <summary>
/// Description of
MainForm.
/// </summary>
public class MainForm :
System.Windows.Forms.Form
{
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
//
//
MainForm
//
this.AutoScaleBaseSize =
new System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292, 266);
this.Name =
"MainForm";
this.Text =
"MainForm";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
}
#endregion
void MainFormPaint(object sender,
System.Windows.Forms.PaintEventArgs e)
{
Graphics g =
this.CreateGraphics();
Pen
myPen= new Pen(Color.Black,
1);

float x_center =550.0F;
float
y_center = 180.0F;
float width =
150.0F;
float height =
50.0F;
float
startAngle =  90.0F;
float sweepAngle =
180.0F;
for (int
i=0;i<100;i++)
{
x_center-=4;
height+=1;
g.DrawArc(myPen, x_center, y_center, width, height,
startAngle,
sweepAngle);
}
}

}
}
結果：


畫點線面
圓外定出10個點，然後將這些點連起來。
程式碼：
using System;
using System.Windows.Forms;
using System.Drawing;

namespace
DefaultNamespace
{
/// <summary>
/// Description of
MainForm.
/// </summary>
public class MainForm :
System.Windows.Forms.Form
{
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
//
//
MainForm
//
this.AutoScaleBaseSize =
new System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292, 266);
this.Name =
"MainForm";
this.Text =
"MainForm";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
}
#endregion
void
MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
int[] x = new
int[10];
int[] y = new int[10];
int
x_center=360,y_center=100,rad=100;
int
i,j;
Graphics g =
this.CreateGraphics();
Pen mypen=new Pen(Color.Black,
1);
for
(i=0;i<10;i++)
{
x[i]=(int)(x_center+rad*Math.Cos(36*i*3.14159/180));
y[i]=(int)(y_center+rad*Math.Sin(36*i*3.14159/180));
}
for(i=0;i<10;i++)
for(j=0;j<10;j++)
g.DrawLine(mypen,x[i],y[i],x[j],y[j]);
}

}
}
結果：
此範例使用了陣列、Sin/Cos數學函數、浮點數強制轉換為整數、畫筆、畫線函數等。


畫特殊線條圖形
程式碼：
using System;
using
System.Windows.Forms;
using
System.Drawing;

namespace DefaultNamespace
{
///
<summary>
/// Description of MainForm.
///
</summary>
public class MainForm :
System.Windows.Forms.Form
{
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
//
//
MainForm
//
this.AutoScaleBaseSize =
new System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292, 266);
this.Name =
"MainForm";
this.Text =
"MainForm";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
}
#endregion
void
MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
int[] x=new
int[4];
int[] y=new int[4];
int
i,j,step;
step=40;
x[0]=x[3]=10;
y[0]=y[1]=10;
x[1]=x[2]=410;
y[2]=y[3]=410;
Graphics
g=this.CreateGraphics();
Pen mypen=new
Pen(Color.Black,1);
for(i=0;i<11;i++)
{
g.DrawLine(mypen,x[0],y[0],x[1],y[1]+step*i);
g.DrawLine(mypen,x[0],y[0],x[3]+step*i,y[3]);
g.DrawLine(mypen,x[1],y[1],x[2]-step*i,y[2]);
g.DrawLine(mypen,x[1],y[1],x[0],y[0]+step*i);
g.DrawLine(mypen,x[2],y[2],x[0]+step*i,y[1]);
g.DrawLine(mypen,x[2],y[2],x[0],y[0]+step*i);
g.DrawLine(mypen,x[3],y[3],x[0]+step*i,y[0]);
g.DrawLine(mypen,x[3],y[3],x[1],y[1]+step*i);
}
for(j=1;j<10;j++)
for(i=1;i<10;i++)
{
g.DrawLine(mypen,x[0]+step*j,y[0],x[3]+step*i,y[3]);
g.DrawLine(mypen,x[1],y[1]+step*j,x[3],y[3]-step*i);
}
}

}
}
結果：


圖形與線條混合應用
程式碼：
using System;
using
System.Windows.Forms;
using
System.Drawing;

namespace DefaultNamespace
{
///
<summary>
/// Description of MainForm.
///
</summary>
public class MainForm :
System.Windows.Forms.Form
{
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
//
//
MainForm
//
this.AutoScaleBaseSize =
new System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292, 266);
this.Name =
"MainForm";
this.Text =
"MainForm";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
}
#endregion
void
MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
int[] x=new
int[24];
int[] y=new int[24];
int
x_center=360,y_center=180,rad=150,i,j;

Graphics
g=this.CreateGraphics();
Pen mypen=new
Pen(Color.Black,1);
Pen Cpen=new
Pen(Color.Black,2);
for(i=0;i<24;i++)
{
x[i]=(int)(x_center+rad*Math.Cos(18*i*Math.PI/100));
y[i]=(int)(y_center+rad*Math.Sin(18*i*Math.PI/100));
}
for(i=0;i<24;i++)
for(j=0;j<24;j++)
{
g.DrawLine(mypen,x[i],y[i],x[j],y[j]);
}
g.DrawEllipse(Cpen,
210, 30, x_center-60, y_center+120);
}

}
}
結果：


畫放射線
程式碼：
using System;
using
System.Windows.Forms;
using System.Drawing;

namespace
DefaultNamespace
{
/// <summary>
/// Description of
MainForm.
/// </summary>
public class MainForm :
System.Windows.Forms.Form
{
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
//
//
MainForm
//
this.AutoScaleBaseSize =
new System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292, 266);
this.Name =
"MainForm";
this.Text =
"MainForm";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
}
#endregion

void
MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs
e)
{
int i,x1,y1,x2,y2;
double
a,b;
x1=150;
y1=100;
b=0.809F;
Graphics g=this.CreateGraphics();
Pen mypen=new
Pen(Color.Black,1);

for(i=0;i<16;i++)
{
a=(2*Math.PI/16)*i;
x2=(int)(Math.Ceiling(x1+48*Math.Cos(a)));
y2=(int)(Math.Ceiling(y1+48*Math.Sin(a)*b));
g.DrawLine(mypen,x1,y1,x2,y2);
}
}

}
}
結果：


畫三角形 (DrawPolygon多邊形函數應用)
程式碼：

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

namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion
  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   Graphics g=this.CreateGraphics();

   PointF point1 = new PointF(200.0f, 50.0f); //開始點
   PointF point2 = new PointF(100.0f, 150.0f);
   PointF point3 = new PointF(300.0f, 150.0f);
   PointF point4 = new PointF(200.0f, 50.0f);  //回到開始點

   PointF[] curvePoints = {point1,
point2, point3, point4 };
g.DrawPolygon(new Pen(Color.Black, 1), curvePoints);
//g.DrawPolygon多邊形函數
}

}
}


畫圓-理解篇
程式碼：
using System;
using System.Windows.Forms;
using System.Drawing;

namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion

  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   int x_center,y_center,rad;
   Graphics g=this.CreateGraphics();
   Pen mypen=new Pen(Color.Black,1);
   x_center=5;
   y_center=5;
   rad=100;
   g.DrawEllipse(mypen,x_center, y_center, rad, rad);    //左上
   g.DrawRectangle(mypen,x_center, y_center, rad, rad);

   g.DrawEllipse(mypen,x_center+100, y_center+100, rad, rad);  //右下
   g.DrawRectangle(mypen,x_center+100, y_center+100, rad, rad);

   g.DrawEllipse(mypen,x_center+100, y_center, rad, rad);  //右上
   g.DrawRectangle(mypen,x_center+100, y_center, rad, rad);

   g.DrawEllipse(mypen,x_center, y_center+100, rad, rad);  //左下
   g.DrawRectangle(mypen,x_center, y_center+100, rad, rad);

   g.DrawEllipse(mypen,x_center+50, y_center+50, rad, rad); //以大四方形中心畫圓
  }

 }
}
結果：


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/6
 * 建立時間: 上午 01:34
 * 功    能: Drawing with C# (畫漸層色彩範例)
 * 修改日期: 上午 01:34
 */
using System;
using System.Windows.Forms;
using System.Drawing;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion
  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
            // Get the graphics object
            Graphics gfx = e.Graphics;
            int x1 = 0;
            int y1 = 0;
            // Loop trough the 255 values red can have
            for(int i = 0; i <= 255; i++)
            {
                // Create new brush with a defined color
                Color brushColor = Color.FromArgb(i, 0, 0);
                // The brush is solid because we want a solid rectangle
                SolidBrush myBrush = new SolidBrush(brushColor);
                // Actually draw the rectangle
                gfx.FillRectangle(myBrush, x1, y1, 10, 10);
                // The next rectangle should be near the last one
                x1 = x1 + 10;
                // If the row is complete start another one
                if((x1 % 290) == 0)
                {
                    y1 = y1 + 10;
                    x1 = 0;
                }
            }
            for(int i = 0; i <= 255; i++)
            {
             Color brushColor = Color.FromArgb(0, i, 0);
             SolidBrush myBrush = new SolidBrush(brushColor);
             gfx.FillRectangle(myBrush, x1, y1, 10, 10);
             x1 = x1 + 10;
             if((x1 % 290) == 0)
             {
                 y1 = y1 + 10;
                 x1 = 0;
             }
            }
             for(int i = 0; i <= 255; i++)
             {
              Color brushColor = Color.FromArgb(0, 0, i);
              SolidBrush myBrush = new SolidBrush(brushColor);
              gfx.FillRectangle(myBrush, x1, y1, 10, 10);
              x1 = x1 + 10;
              if((x1 % 290) == 0)
              {
                  y1 = y1 + 10;
                  x1 = 0;
              }
           }
     }
 }
}


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/7
 * 建立時間: 下午 06:24
 * 功    能: 3D GDI+ Effect
 * 修改日期: 2004/8/7 下午 06:24
 */
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(464, 358);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
  }
  #endregion

  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
   // Create a pen and font
   Graphics g = e.Graphics;
   Pen blackPen = new Pen(Color.Black, 2);
   Font verdanaFont = new Font( "Verdana", 60, FontStyle.Bold);
   // Create points that define polygon.
   Point[] curvePoints1 = { new Point(200, 15),
   new Point(200, 200), new Point(375, 250) };
   Point[] curvePoints2 = { new Point(0, 250),
   new Point(200, 200), new Point(375, 250) };
   Point[] curvePoints3 = { new Point(200, 15),
   new Point(200, 200), new Point(0, 250) };
   // Create linear gradient brushes
   Point pt1 = new Point(10, 10);
   Point pt2 = new Point(30, 30);
   LinearGradientBrush lgBrush1 =
   new LinearGradientBrush(pt1, pt2, Color.Red, Color.Blue);
   LinearGradientBrush lgBrush2 =
   new LinearGradientBrush(pt1, pt2, Color.Red, Color.Green);
   LinearGradientBrush lgBrush3 =
   new LinearGradientBrush(pt1, pt2, Color.Blue, Color.Green);
   // If you want to draw three lines
   //e.Graphics.DrawLine(blackPen, 200, 55, 200, 200);
   //e.Graphics.DrawLine(blackPen, 50, 250, 200, 200);
   //e.Graphics.DrawLine(blackPen, 345, 260, 200, 200);
   // Set quality of text and shape
   g.TextRenderingHint = TextRenderingHint.AntiAlias;
   g.SmoothingMode = SmoothingMode.AntiAlias;
   // Draw three polygons and string
   e.Graphics.FillPolygon(new SolidBrush(Color.FromArgb(80, 255, 0, 0)), curvePoints1);
   e.Graphics.FillPolygon(new SolidBrush(Color.FromArgb(80, 0, 255, 0)), curvePoints2);
   e.Graphics.FillPolygon(new SolidBrush(Color.FromArgb(80, 0, 0, 255)), curvePoints3);
   // Draw C# using the DrawString method
   // Starting @ point 140, 150
   g.DrawString("C#", verdanaFont, lgBrush1, new PointF(140,150) );
   // Dispose Graphics
   g.Dispose();

  }

 }
}


畫類比時鐘
原理：
以
X = 圓心X座標 + 半徑*sin(角度)
Y = 圓心Y座標 + 半徑*cos(角度)
可以得到一個圓，角度
0 度是在 3 點鐘方向
90 度(M_PI/2) 是在 12 點鐘方向
180 度(M_PI) 是在 9 點鐘方向
270 度(M_PI*1.5) 是在 6 點鐘方向
當您需要畫指針時，先算出角度，再由以上公式（半徑以指針長度代入）算出指針端點座標與圓心畫直線即可。
程式碼：
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using
System.Data;
using System.Drawing.Drawing2D;

namespace AnalogClock
{
   public class AnalogClock : System.Windows.Forms.Form
   {
      private System.ComponentModel.IContainer components;
   private System.Windows.Forms.Timer timer1;

      public AnalogClock()
{
InitializeComponent();
}

protected override void Dispose( bool
disposing )
{
if( disposing )
{
if
(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code

private void InitializeComponent() {
this.components = new
System.ComponentModel.Container();
this.timer1 = new
System.Windows.Forms.Timer(this.components);
//
// timer1
//
this.timer1.Enabled =
true;
this.timer1.Interval =
1000;
this.timer1.Tick += new
System.EventHandler(this.OnTick);
//
// AnalogClock
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
15);
this.ClientSize = new System.Drawing.Size(674,
480);
this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox
= false;
this.Name =
"AnalogClock";
this.Text = "C#
類比時鐘";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.OnFormPaint);
}
#endregion

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

      private void OnFormPaint(object sender,
System.Windows.Forms.PaintEventArgs e)
{
int
i,j,x1,x2,y1,y2;
Graphics g = e.Graphics;
g.TranslateTransform(300, 240,
MatrixOrder.Append);
DrawClock( e.Graphics
);

Graphics gx =
this.CreateGraphics();
Pen
pen = new Pen(Color.Black,
1);
gx.DrawEllipse(pen,
198,140, 203, 200);
gx.DrawEllipse(pen, 196,137, 207,
207);
for(i=0;i<60;i++)
{
if(i%5==0)
j=15;
else
j=5;
x1=(int)(100*Math.Cos(i*6*Math.PI/180)+300);
y1=(int)(100*Math.Sin(i*6*Math.PI/180)+240);
x2=(int)((100-j)*Math.Cos(i*6*Math.PI/180)+300);
y2=(int)((100-j)*Math.Sin(i*6*Math.PI/180)+240);
gx.DrawLine(pen,x1,y1,x2,y2);
}
}

private void DrawClock(Graphics g)
{
const double pai = Math.PI;
Point center = new Point
(0, 0);

         DateTime time =
DateTime.Now;
double secAng
= 2.0*pai*time.Second/60.0;
double minAng = 2.0*pai*(time.Minute + time.Second/60.0)/60.0;
double hourAng =
2.0*pai*(time.Hour + time.Minute/60.0)/12.0;
int r = Math.Min(
ClientSize.Width, ClientSize.Height ) / 2;
int secHandLength =
(int)(0.7*r)-70;
int
minHandLength = (int)(0.9*r)-125;
int hourHandLength =
(int)(0.5*r)-45;

         Point secHand = new
Point((int)(secHandLength*Math.Sin(secAng)),
(int)(-secHandLength*Math.Cos(secAng)));
Point minHand = new
Point((int)(minHandLength*Math.Sin(minAng)),
(int)(-minHandLength*Math.Cos(minAng)));
Point hourHand = new
Point((int)(hourHandLength*Math.Sin(hourAng)),
(int)(-hourHandLength*Math.Cos(hourAng)));

         Pen BluePen = new
Pen(Color.Blue, 3);
g.DrawLine(BluePen, center, secHand);

         Pen GreenPen = new
Pen(Color.Green, 5);
g.DrawLine(GreenPen, center, minHand);

         Pen RedPen = new
Pen(Color.Red, 7);
g.DrawLine(RedPen, center, hourHand);
}

      private void OnTick(object sender, System.EventArgs e)
      {
         Invalidate();
      }
   }
}
http://debatt.passagen.se/show.fcgi?category=500000000000002&conference=500000000000067&posting=19500000001322959

http://www.thecodeproject.com/csharp/analogclock.asp


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/6
 * 建立時間: 上午 01:34
 * 功    能: Charting in GDI+ with C#
 * 修改日期: 上午 01:34
 */
using System;
using System.Windows.Forms;
using System.Drawing;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.TextBox textBox5;
  private System.Windows.Forms.TextBox textBox1;
  private System.Windows.Forms.TextBox textBox3;
  private System.Windows.Forms.TextBox textBox2;
  private System.Windows.Forms.TextBox textBox4;
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.textBox4 = new System.Windows.Forms.TextBox();
   this.textBox2 = new System.Windows.Forms.TextBox();
   this.textBox3 = new System.Windows.Forms.TextBox();
   this.textBox1 = new System.Windows.Forms.TextBox();
   this.textBox5 = new System.Windows.Forms.TextBox();
   this.SuspendLayout();
   //
   // textBox4
   //
   this.textBox4.Location = new System.Drawing.Point(176, 8);
   this.textBox4.Name = "textBox4";
   this.textBox4.Size = new System.Drawing.Size(48, 22);
   this.textBox4.TabIndex = 3;
   this.textBox4.Text = "80";
   //
   // textBox2
   //
   this.textBox2.Location = new System.Drawing.Point(64, 8);
   this.textBox2.Name = "textBox2";
   this.textBox2.Size = new System.Drawing.Size(48, 22);
   this.textBox2.TabIndex = 1;
   this.textBox2.Text = "53";
   //
   // textBox3
   //
   this.textBox3.Location = new System.Drawing.Point(120, 8);
   this.textBox3.Name = "textBox3";
   this.textBox3.Size = new System.Drawing.Size(48, 22);
   this.textBox3.TabIndex = 2;
   this.textBox3.Text = "61";
   //
   // textBox1
   //
   this.textBox1.Location = new System.Drawing.Point(8, 8);
   this.textBox1.Name = "textBox1";
   this.textBox1.Size = new System.Drawing.Size(48, 22);
   this.textBox1.TabIndex = 0;
   this.textBox1.Text = "73";
   //
   // textBox5
   //
   this.textBox5.Location = new System.Drawing.Point(232, 8);
   this.textBox5.Name = "textBox5";
   this.textBox5.Size = new System.Drawing.Size(48, 22);
   this.textBox5.TabIndex = 4;
   this.textBox5.Text = "56";
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(292, 266);
   this.Controls.Add(this.textBox5);
   this.Controls.Add(this.textBox4);
   this.Controls.Add(this.textBox3);
   this.Controls.Add(this.textBox2);
   this.Controls.Add(this.textBox1);
   this.Name = "MainForm";
   this.Text = "MainForm";
   this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
   this.ResumeLayout(false);
  }
  #endregion
  void MainFormPaint(object sender, System.Windows.Forms.PaintEventArgs e)
  {
             Point[] pointarray=new Point[5];
             Random r=new Random();
             this.textBox1.Text=r.Next(100).ToString();
             this.textBox2.Text=r.Next(100).ToString();
             this.textBox3.Text=r.Next(100).ToString();
             this.textBox4.Text=r.Next(100).ToString();
             this.textBox5.Text=r.Next(100).ToString();
             float a=Convert.ToInt32(this.textBox1.Text.ToString());
             a=a*3;
             a=a/2;
             a=150-a;
             float b=Convert.ToInt32(this.textBox2.Text.ToString());
             b=b*3;
             b=b/2;
             b=150-b;
             float c=Convert.ToInt32(this.textBox3.Text.ToString());
             c=c*3;
             c=c/2;
             c=150-c;
             float d=Convert.ToInt32(this.textBox4.Text.ToString());
             d=d*3;
             d=d/2;
             d=150-d;
             float f=Convert.ToInt32(this.textBox5.Text.ToString());
             f=f*3;
             f=f/2;
             f=150-f;
             Pen newpen = new Pen(Color.Black);
             Graphics g=Graphics.FromHwnd(this.Handle);
             //Set point of origin to be 50,50 on the form
             g.TranslateTransform(50,50);
             g.DrawLine(newpen,1,1,1,150);
             g.DrawLine(newpen,1,150,150,150);
             //Draw X and y axis
             g.DrawLine(newpen,-3,30,3,30);
             g.DrawLine(newpen,-3,60,3,60);
             g.DrawLine(newpen,-3,90,3,90);
             g.DrawLine(newpen,-3,120,3,120);
             g.DrawLine(newpen,30,147,30,153);
             g.DrawLine(newpen,60,147,60,153);
             g.DrawLine(newpen,90,147,90,153);
             g.DrawLine(newpen,120,147,120,153);
             g.DrawLine(newpen,150,147,150,153);
             Font newfont=new Font("Arial",10);
             //label Y axis
             g.DrawString("100",newfont,new SolidBrush(Color.Black),-25,-5);
             g.DrawString("80",newfont,new SolidBrush(Color.Black),-25,25);
             g.DrawString("60",newfont,new SolidBrush(Color.Black),-25,55);
             g.DrawString("40",newfont,new SolidBrush(Color.Black),-25,85);
             g.DrawString("20",newfont,new SolidBrush(Color.Black),-25,115);

             //Label X axis
             g.DrawString("0",newfont,new SolidBrush(Color.Black),-10,145);
             g.DrawString("p1",newfont,new SolidBrush(Color.Black),25,155);
             g.DrawString("p2",newfont,new SolidBrush(Color.Black),55,155);
             g.DrawString("p3",newfont,new SolidBrush(Color.Black),85,155);
             g.DrawString("p4",newfont,new SolidBrush(Color.Black),115,155);
             g.DrawString("p5",newfont,new SolidBrush(Color.Black),145,155);
             //Plot points
             g.DrawEllipse(new Pen(Color.Blue),30-2,a-2,4,4);
             g.DrawEllipse(new Pen(Color.Red),60-2,b-2,4,4);
             g.DrawEllipse(new Pen(Color.Green),90-2,c-2,4,4);
             g.DrawEllipse(new Pen(Color.Black),120-2,d-2,4,4);
             g.DrawEllipse(new Pen(Color.Gold),150-2,f-2,4,4);
             //Join the points
             pointarray[0]=new Point(30,Convert.ToInt32(a));
             pointarray[1]=new Point(60,Convert.ToInt32(b));
             pointarray[2]=new Point(90,Convert.ToInt32(c));
             pointarray[3]=new Point(120,Convert.ToInt32(d));
             pointarray[4]=new Point(150,Convert.ToInt32(f));
             g.DrawLines(new Pen(Color.DarkSalmon),pointarray);
     }

 }
}


使用GDI+做螢幕抓圖
/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2004/8/30
* Time: 下午 02:32
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace ScreenCapture
{
///
<summary>
/// Description of MainForm.
///
</summary>
public class MainForm :
System.Windows.Forms.Form
{
private
System.Windows.Forms.Button button1;
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
this.button1 = new
System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(192,
168);
this.button1.Name =
"button1";
this.button1.TabIndex =
0;
this.button1.Text =
"button1";
this.button1.Click += new
System.EventHandler(this.Button1Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
15);
this.ClientSize = new System.Drawing.Size(292,
266);
this.Controls.Add(this.button1);
this.Name
= "MainForm";
this.Text =
"MainForm";
this.ResumeLayout(false);
}
#endregion

//============================呼叫系統DLL================
class GDI32
{
[DllImport("GDI32.dll")]
public static extern
bool BitBlt(int hdcDest,int nXDest,int
nYDest,
int nWidth,int nHeight,int
hdcSrc,
int nXSrc,int nYSrc,int dwRop);
[DllImport("GDI32.dll")]
public static extern
int CreateCompatibleBitmap(int hdc,int nWidth,
int nHeight);
[DllImport("GDI32.dll")]
public static extern
int CreateCompatibleDC(int hdc);
[DllImport("GDI32.dll")]
public static extern
bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
public static extern
bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
public static extern
int GetDeviceCaps(int hdc,int nIndex);
[DllImport("GDI32.dll")]
public static extern
int SelectObject(int hdc,int hgdiobj);
}
class
User32
{
[DllImport("User32.dll")]
public static extern
int GetDesktopWindow();
[DllImport("User32.dll")]
public static extern
int GetWindowDC(int hWnd);
[DllImport("User32.dll")]
public static extern
int ReleaseDC(int hWnd,int hDC);
}
//============================應用========================
public void CaptureScreen(string
fileName,ImageFormat imageFormat)
{
int hdcSrc =
User32.GetWindowDC(User32.GetDesktopWindow()),
hdcDest =
GDI32.CreateCompatibleDC(hdcSrc),
hBitmap =
GDI32.CreateCompatibleBitmap(hdcSrc,
GDI32.GetDeviceCaps(hdcSrc,8),GDI32.GetDeviceCaps(hdcSrc,10));
GDI32.SelectObject(hdcDest,hBitmap);
GDI32.BitBlt(hdcDest,0,0,GDI32.GetDeviceCaps(hdcSrc,8),
GDI32.GetDeviceCaps(hdcSrc,10),
hdcSrc,0,0,0x00CC0020);
SaveImageAs(hBitmap,fileName,imageFormat);
Cleanup(hBitmap,hdcSrc,hdcDest);
}

private void
Cleanup(int hBitmap,int hdcSrc,int
hdcDest)
{
User32.ReleaseDC(User32.GetDesktopWindow(),hdcSrc);
GDI32.DeleteDC(hdcDest);
GDI32.DeleteObject(hBitmap);
}
private void SaveImageAs(int hBitmap,string fileName,ImageFormat imageFormat)
{
Bitmap image =
new Bitmap(Image.FromHbitmap(new IntPtr(hBitmap)),
Image.FromHbitmap(new IntPtr(hBitmap)).Width,
Image.FromHbitmap(new IntPtr(hBitmap)).Height);
image.Save(fileName,imageFormat);
}

void Button1Click(object sender, System.EventArgs e)
{
CaptureScreen("c:\\qoo.bmp",ImageFormat.Bmp);
}
}
}


簡單動畫
/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2004/8/30
* Time: 下午 06:53
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Animated
{
///
<summary>
/// Description of MainForm.
///
</summary>
public class MainForm :
System.Windows.Forms.Form
{
private
System.ComponentModel.IContainer components;
private
System.Windows.Forms.PictureBox pictureBox1;
private
System.Windows.Forms.Timer timer1;
private int
curFrame=0;

public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
SetStyle(ControlStyles.UserPaint,
true);
SetStyle(ControlStyles.AllPaintingInWmPaint,
true);
SetStyle(ControlStyles.DoubleBuffer,
true);
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
this.components = new
System.ComponentModel.Container();
System.Resources.ResourceManager
resources = new
System.Resources.ResourceManager(typeof(MainForm));
this.timer1
= new
System.Windows.Forms.Timer(this.components);
this.pictureBox1
= new
System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled =
true;
this.timer1.Interval =
1000;
this.timer1.Tick += new
System.EventHandler(this.Timer1Tick);
//
// pictureBox1
//
this.pictureBox1.Image =
((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));//載入GIF檔
this.pictureBox1.Location
= new System.Drawing.Point(24, 32);
this.pictureBox1.Name =
"pictureBox1";
this.pictureBox1.Size = new
System.Drawing.Size(96, 104);
this.pictureBox1.TabIndex =
0;
this.pictureBox1.TabStop =
false;
this.pictureBox1.Visible =
false;
//
//
MainForm
//
this.AutoScaleBaseSize =
new System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292,
266);
this.Controls.Add(this.pictureBox1);
this.Name
= "MainForm";
this.Text =
"MainForm";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.MainFormPaint);
this.ResumeLayout(false);
}
#endregion
void MainFormPaint(object sender,
System.Windows.Forms.PaintEventArgs
e)
{
Graphics
g=e.Graphics;
int
frames=pictureBox1.Image.GetFrameCount(FrameDimension.Time);
curFrame++;
if(curFrame>=frames)
curFrame=0;
pictureBox1.Image.SelectActiveFrame(FrameDimension.Time,
curFrame);
g.DrawImage(pictureBox1.Image,
this.ClientRectangle);
Invalidate();
}

void
Timer1Tick(object sender, System.EventArgs
e)
{
framesPerSecondCount=0;
}

}
}


五子棋 (預先選擇兩個黑棋與白棋bmp圖片載入imageList1)
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace WindowsApplication2
{
 public class Form1 : System.Windows.Forms.Form
 {
  private System.ComponentModel.IContainer components;
  private System.Windows.Forms.MenuItem menuItem6;
  private System.Windows.Forms.MenuItem menuItem5;
  private System.Windows.Forms.MenuItem menuItem10;
  private System.Windows.Forms.MenuItem menuItem9;
  private System.Windows.Forms.MenuItem menuItem8;
  private System.Windows.Forms.ImageList imageList1;
  private System.Windows.Forms.MenuItem menuItem4;
  private System.Windows.Forms.MenuItem menuItem1;
  private System.Windows.Forms.MainMenu mainMenu1;
  private System.Windows.Forms.MenuItem menuItem7;
  private const int None = -1;//沒有棋子
  private const int White = 0;//代表白棋
  private const int Black = 1;//代表黑棋
  private int [,]checkerBoard = new int [15, 15];//棋盤(用來保存每一個棋子)
  private int nextPlayer;//下一個選手

  private int Player
  {
   get
   {
    return nextPlayer;
   }
   set
   {
    nextPlayer = value;
    ReDrawNextPlayerMark();
   }
  }

  private Stack History;//下棋的歷史記錄
  public Form1()
  {
   //
   // Required for Windows Form Designer support
   //
   InitializeComponent();
   //
   // TODO: Add any constructor code after InitializeComponent call
   //   checkerBoard = new int [15,15];
   History = new Stack();
   Player = White;//預設設置為白棋先下
   Reset();
  }
  ///
<summary>
/// Clean up any resources being used.
///
</summary>
protected override void Dispose( bool disposing
)
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
  #region Windows Form Designer generated
code
/// <summary>
/// Required method for Designer
support - do not modify
/// the contents of this method with the code
editor.
/// </summary>
private void
InitializeComponent()
{
this.components = new
System.ComponentModel.Container();
System.Resources.ResourceManager
resources = new
System.Resources.ResourceManager(typeof(Form1));
this.menuItem7 = new
System.Windows.Forms.MenuItem();
this.mainMenu1 = new
System.Windows.Forms.MainMenu();
this.menuItem1 = new
System.Windows.Forms.MenuItem();
this.menuItem4 = new
System.Windows.Forms.MenuItem();
this.imageList1 = new
System.Windows.Forms.ImageList(this.components);
this.menuItem8 = new
System.Windows.Forms.MenuItem();
this.menuItem9 = new
System.Windows.Forms.MenuItem();
this.menuItem10 = new
System.Windows.Forms.MenuItem();
this.menuItem5 = new
System.Windows.Forms.MenuItem();
this.menuItem6 = new
System.Windows.Forms.MenuItem();
//
// menuItem7
//
this.menuItem7.Index = 4;
this.menuItem7.Text =
"-";
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[]
{
this.menuItem1});
//
//
menuItem1
//
this.menuItem1.Index =
0;
this.menuItem1.MenuItems.AddRange(new
System.Windows.Forms.MenuItem[]
{
this.menuItem5,
this.menuItem9,
this.menuItem10,
this.menuItem8,
this.menuItem7,
this.menuItem6});
this.menuItem1.Text
= "系統 (&S)";
this.menuItem1.Popup += new
System.EventHandler(this.menuItem1_Popup);
//
//
menuItem4
//
this.menuItem4.Index =
-1;
this.menuItem4.Text = "";
//
// imageList1 (預先選擇兩個黑棋與白棋bmp圖片載入imageList1)
//
this.imageList1.ColorDepth =
System.Windows.Forms.ColorDepth.Depth24Bit;
this.imageList1.ImageSize =
new System.Drawing.Size(20, 20);
this.imageList1.ImageStream =
((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor
= System.Drawing.Color.Transparent;
//
//
menuItem8
//
this.menuItem8.Index =
3;
this.menuItem8.Shortcut =
System.Windows.Forms.Shortcut.AltBksp;
this.menuItem8.Text = "悔一步棋
(&H)";
this.menuItem8.Click += new
System.EventHandler(this.menuItem8_Click);
//
//
menuItem9
//
this.menuItem9.Index =
1;
this.menuItem9.Text = "-";
//
//
menuItem10
//
this.menuItem10.Index =
2;
this.menuItem10.Text = "黑棋先下
(&B)";
this.menuItem10.Click += new
System.EventHandler(this.menuItem10_Click);
//
//
menuItem5
//
this.menuItem5.Index =
0;
this.menuItem5.Shortcut =
System.Windows.Forms.Shortcut.CtrlN;
this.menuItem5.Text = "重新開始
(&N)";
this.menuItem5.Click += new
System.EventHandler(this.menuItem5_Click);
//
//
menuItem6
//
this.menuItem6.Index =
5;
this.menuItem6.Shortcut =
System.Windows.Forms.Shortcut.CtrlX;
this.menuItem6.Text = "退出
(&X)";
this.menuItem6.Click += new
System.EventHandler(this.menuItem6_Click);
//
//
Form1
//
this.AccessibleDescription =
"";
this.AllowDrop = true;
this.AutoScale =
false;
this.AutoScaleBaseSize = new System.Drawing.Size(10,
25);
this.ClientSize = new System.Drawing.Size(338,
384);
this.Cursor =
System.Windows.Forms.Cursors.Hand;
this.Font = new
System.Drawing.Font("Microsoft Sans Serif", 16F);
this.FormBorderStyle
= System.Windows.Forms.FormBorderStyle.FixedDialog;
this.ImeMode =
System.Windows.Forms.ImeMode.Off;
this.MaximizeBox =
false;
this.Menu = this.mainMenu1;
this.Name =
"Form1";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text =
"五子棋";
this.Paint += new
System.Windows.Forms.PaintEventHandler(this.Form1Paint);
}
#endregion
  /// <summary>
/// The main
entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
  private void menuItem4_Click(object
sender, System.EventArgs e)
{
this.Close();
}
  private void menuItem6_Click(object
sender, System.EventArgs e)
{
this.Close();
}
  private void menuItem5_Click(object
sender, System.EventArgs e)
{
if(History.Count > 0) this.Reset();
}
  private void menuItem8_Click(object
sender, System.EventArgs e)
{
Penitence();
}
  //重載重畫函數
protected override void OnPaint(PaintEventArgs e)
{
System.Drawing.Graphics g = this.CreateGraphics();
for(int x =
0; x < 15; x++)
{
for(int y= 0; y <
15; y++)
{
if(checkerBoard[ y,
x ] != None) DrawChess(new Point(x, y), checkerBoard[ y, x
]);
}
}
ReDrawNextPlayerMark();
base.OnPaint(e);
}
  //重載滑鼠按下事件
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
base.OnMouseDown(e);
switch(
e.Button )
{
//take left button
down
case MouseButtons.Left:
if( (History.Count == 0) && (2 < e.X) && (e.X < 22)
&& (309 < e.Y) && (e.Y < 329) ) Player = (Player ==
White)? Black: White;
else AddChess( MToA( new
Point(e.X, e.Y) ) );
break;
//take right button
down
case MouseButtons.Right:
//     OnRButtonDown(new
Point(e.X,e.Y));
break;
}
}
  //把滑鼠坐標轉換成棋盤坐標
  private Point MToA(Point p)
  {
   return new Point( (p.X - 15) / 20, (p.Y - 6) / 20);
  }
//開始新的棋局，所有資料復位並重畫棋盤
private void Reset()
{
for( int i = 0; i < 15; i++ )
{
for(
int j = 0; j < 15; j++)
{
checkerBoard[i,j] = None;
}
}
History.Clear();//清空歷史記錄
DrawCheckerBoard();//重畫棋盤
}
  //重畫棋盤
  private void DrawCheckerBoard()
  {
   this.BackColor = System.Drawing.SystemColors.Desktop;
   this.BackColor = System.Drawing.SystemColors.Control;
  }
  //重畫下一個選手的標誌棋子
  private void ReDrawNextPlayerMark()
  {
   System.Drawing.Graphics g = this.CreateGraphics();
   imageList1.Draw(g, 2, 309, 20, 20, Player);
  }
  //在棋盤上畫一個棋子
private void DrawChess(Point pCoordinates,int iPlayer)
{
System.Drawing.Graphics g =
this.CreateGraphics();
imageList1.Draw(g, 15 + pCoordinates.X *
20, 6 + pCoordinates.Y * 20, 20, 20, iPlayer);
}
  //在指定的棋盤坐標位置添加一個棋子
private void AddChess(Point p)
{
//判斷是否超出邊界
if( (p.X < 0 || p.X > 14) || (p.Y < 0 || p.Y
> 14) ) return;
//判斷該位置有無棋子
if( checkerBoard[
p.Y, p.X ] != None ) return;//如果已經有了棋子則退出（這顆棋不能下）
DrawChess(
p,Player );
if(Player == White)//該白棋下
{
checkerBoard[ p.Y, p.X ] = White;
Player = Black;
}
else
{
checkerBoard[ p.Y, p.X ] = Black;
Player = White;
}
History.Push( new Point(p.X,
p.Y) );//添加歷史記錄
CheckGameResult( p );
}
  //檢查遊戲結果
/*
* 算法：
*
由於根據遊戲規則，只有先放成 5 個相連的棋子的一方或剩，
* 所以只要以剛剛下過的那個棋子為中心，檢查有沒有 5
個相連的同顏色棋子就好了。
*/
private void
CheckGameResult(Point sourcePoint)
{
int
x,y;
int LastPlayer = (Player == White)? Black:
White;
int n;

//檢查行
n = 1;
y = sourcePoint.Y;
for(x = sourcePoint.X - 1; x >= 0; x--)
{
if(checkerBoard[ y, x ] == LastPlayer)
n++;
else break;
}
for(x =
sourcePoint.X + 1; x < 15; x++)
{
if(checkerBoard[ y, x ] == LastPlayer) n++;
else
break;
}
if(n >= 5)
{
Win(LastPlayer);
return;
}
   //檢查列
n = 1;
x = sourcePoint.X;
for(y = sourcePoint.Y
- 1; y >= 0; y--)
{
if(checkerBoard[ y,
x ] == LastPlayer) n++;
else break;
}
for(y = sourcePoint.Y + 1; y < 15; y++)
{
if(checkerBoard[ y, x ] == LastPlayer)
n++;
else break;
}
if(n
>= 5)
{
Win(LastPlayer);
return;
}
//檢查左斜線
n=1;
for(x = sourcePoint.X + 1 , y =
sourcePoint.Y - 1; x < 15 && y >= 0; x++,
y--)//檢查左斜線的上半截
{
if(checkerBoard[ y, x ]
== LastPlayer) n++;
else break;
}
for(x = sourcePoint.X - 1 , y = sourcePoint.Y + 1; x >= 0
&& y < 15; x--, y++)//檢查左斜線的下半截
{
if(checkerBoard[ y, x ] == LastPlayer)
n++;
else break;
}
if(n
>= 5)
{
Win(LastPlayer);
return;
}
//檢查右斜線
n = 1;
for(x = sourcePoint.X - 1 , y =
sourcePoint.Y - 1; x >= 0 && y >= 0; x--,
y--)//檢查右斜線的上半截
{
if(checkerBoard[ y, x ]
== LastPlayer) n++;
else break;
}
for(x = sourcePoint.X + 1 , y = sourcePoint.Y + 1; x < 15
&& y < 15; x++, y++)//檢查右斜線的下半截
{
if(checkerBoard[ y, x ] == LastPlayer)
n++;
else break;
}
if(n
>= 5)
{
Win(LastPlayer);
return;
}
   //棋盤滿棋，平手
   if(History.Count >= 225)
   {
    Win(None);
    return;
   }
  }
  //顯示指定選手的獲勝信息
private void Win(int NPlayer)
{
switch(NPlayer)
{
case
None:
MessageBox.Show("本局平手!","恭喜！");
break;
case White:
MessageBox.Show("本局 白棋 獲勝 !","恭喜！");
break;
case Black:
MessageBox.Show("本局 黑棋 獲勝 !","恭喜！");
break;
}
Reset();
}
  //悔棋 1 步
private
void Penitence()
{
if(History.Count >
0)
{
Point p =
(Point)History.Pop();
checkerBoard[ p.Y, p.X ] =
None;
nextPlayer = (Player == White)? Black:
White;
DrawCheckerBoard();
}
}
  private void
menuItem10_Click(object sender, System.EventArgs e)
{
Player = (Player == White)? Black: White;
}
  private void
menuItem1_Popup(object sender, System.EventArgs e)
{
if(History.Count == 0)
{
menuItem10.Visible = true;
menuItem10.Text = (Player ==
White)? "黑棋先下 (&B)": "白棋先下 (&W)";
}
else
menuItem10.Visible = false;
}
  //畫出棋盤
  void Form1Paint(object
sender, System.Windows.Forms.PaintEventArgs e)
{

Graphics gfx =
e.Graphics;
Pen myPen = new
Pen(Color.Black);
for(int i
= 5; i <= 320; i = i + 20)
{
gfx.DrawLine(myPen,15, i, 315,
i);
}
Pen myPenu = new
Pen(Color.Black);
for(int x = 5; x
< 320; x = x + 20)
{
gfx.DrawLine(myPenu, x+10, 5, x+10, 305);
}
}
}
}


FormChart.Net Version 1.0
(With Complete Dessign Time Support)

Download Component

Download Sample Project
Installation and Setup Instructions

What is FormChart.Net?

FormChart.Net is a custom user control library that you can use on Windows Forms to render your data in the sahpe of charts or graphs. Last month we release our ASPChart.Net library for drawing graphs and charts. The same library acts as the drawing engine for this custom user control.

What Functionlaity Is Supported In Current Version?

As it has been mentioned earlier that this component is based on ASPChart.Net engine, it supports all the features of that library. But we have taken that library to a higher level. This control provides you complete design time support. Following are some of the highlights of this control library.

  • Ability to add the control library to Visual Studio .Net IDE Toolbox
  • Drag and drop of controls from toolbox onto Windows Form designer
  • Complete design time support. This helps in cutting down your development time by making you type less code.
  • WYSIWYG (What you see is what you get) features let you specify all the appearnace and alignment attributes right from the Properties view of IDE.

Where Can I User It?

The control has infinite possibilites. You can use it anywhere where you need to display the information as Pie Charts, Bar Charts, Line Graphs, etc.

How to install it?

We have created a install document. You can download it from our web site and follow it step by step to get going.

How to use it?

The control is very easy to use like any other .Net windows controls. Drag and drop the control onto Windows Forms designer, modify the properties to specify the appearance and alignment you want. And the necessary code will be added to your CS or VB file.

After you have completed the initial step. There are two more steps that are needed. Without this control will not function.

  • The control accepts the data as an XML document. In the current version of control we don't have support for DataBinding. This support will be added in next version. For now you will need to create the XML document and load it in control.
  • The control gives you ability to select option to specify if you want to use random colors generated by ASPChart.Net drawing engine or you want to specify your own list of colors. If you select Random Color generation, then you don't need to perform any more steps. Otherwise, create a StringCollection object containing string representation of KnownColor values. And set to Colors property of this control.

The following code demonstrates the steps we discissed above. For more details, look at the source code of the attached WinChartApp project.

public ChartForm()
{
    InitializeComponent();
    barChart2DControl1.LoadData(this.CreateChartData());

    if (!barChart2DControl1.UseRandomColors)
    {
        barChart2DControl1.Colors = this.CreateColorNames();
    }
}

public XmlDocument CreateChartData()
{
    XmlDocument obXmlDoc = new XmlDocument();
    obXmlDoc.Load("BarChartData.xml");
    return obXmlDoc;
}

private StringCollection CreateColorNames()
{
    StringCollection obColorNames = new StringCollection();
    obColorNames.Add("Red");
    obColorNames.Add("Blue");
    obColorNames.Add("Black");
    obColorNames.Add("Pink");
    obColorNames.Add("Khaki");
    obColorNames.Add("Green");
    obColorNames.Add("Gray");
    obColorNames.Add("Beige");
    obColorNames.Add("Purple");
    obColorNames.Add("Yellow");
    return obColorNames;
}


CsGL (C sharp Graphics Library)
網址：http://csgl.sourceforge.net/

Features

CsGL (C sharp Graphics Library) implements a wrapper for the quite well known and powerful C-library OpenGL allowing any .NET language make use of it.
It feature:
  • OpenGL 1.4 API and this list of extension
  • an extension "generator" in <csgl>/extras/generator/generator.exe.
  • a font "engine", the CsGL.OpenGL.GDITextureFont. Demonstrated in the <csgl>/examples/CS/gdifont.cs
  • mouse and keyboard classes (CsGL.Util.Mouse & CsGL.Util.Keyboard) for simplified event management. Demonstrated in <csgl>/examples/CS/event.cs
  • a fullscreen window, able to change screen definition (CsGL.Util.ScreenForm). Demonstrated in the CsGLExamples.


Windows MediaPlayer操作範例-收音機製作
(Windows MediaPlayer 9採用非視覺方式製作-加入「參考」方式)
程式碼如下：
/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/25
 * 建立時間: 下午 08:05
 * 功    能:
 * 修改日期: 2004/8/25 下午 08:05
 */
using System;
using System.Windows.Forms;
using System.ComponentModel;
using WMPLib;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private ColorButton.ColorButton colorButton2;
  private ColorButton.ColorButton colorButton1;
  private System.Windows.Forms.ListBox listBox1;
  private WMPLib.WindowsMediaPlayer Paly=new WindowsMediaPlayer();
  private System.ComponentModel.Container components = null;
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }
  /// <summary>
  /// 記憶體釋放
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
     if (components != null)
     {
      components.Dispose();
     }
   }
   base.Dispose( disposing );
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.listBox1 = new System.Windows.Forms.ListBox();
   this.colorButton1 = new ColorButton.ColorButton();
   this.colorButton2 = new ColorButton.ColorButton();
   this.SuspendLayout();
   //
   // listBox1
   //
   this.listBox1.ItemHeight = 12;
   this.listBox1.Items.AddRange(new object[] {
      "mms://live.media.hinet.net/UFO_Music1",
      "mms://live.media.hinet.net/kissradio ",
      "mms://live.media.hinet.net/vot "});
   this.listBox1.Location = new System.Drawing.Point(8, 8);
   this.listBox1.Name = "listBox1";
   this.listBox1.Size = new System.Drawing.Size(272, 64);
   this.listBox1.TabIndex = 1;
   this.listBox1.Click += new System.EventHandler(this.listBox1Click);
   //
   // colorButton1
   //
   this.colorButton1.Active = true;
   this.colorButton1.ButtonStyle = ColorButton.ColorButton.ButtonStyles.Rectangle;
   this.colorButton1.Font = new System.Drawing.Font("Verdana", 10F, System.Drawing.FontStyle.Bold);
   this.colorButton1.GradientStyle = ColorButton.ColorButton.GradientStyles.Vertical;
   this.colorButton1.HoverBorderColor = System.Drawing.Color.MediumVioletRed;
   this.colorButton1.HoverColorA = System.Drawing.Color.MediumVioletRed;
   this.colorButton1.HoverColorB = System.Drawing.Color.White;
   this.colorButton1.Location = new System.Drawing.Point(8, 80);
   this.colorButton1.Name = "colorButton1";
   this.colorButton1.NormalBorderColor = System.Drawing.Color.Green;
   this.colorButton1.NormalColorA = System.Drawing.Color.Green;
   this.colorButton1.NormalColorB = System.Drawing.Color.Honeydew;
   this.colorButton1.Size = new System.Drawing.Size(64, 32);
   this.colorButton1.SmoothingQuality = ColorButton.ColorButton.SmoothingQualities.AntiAlias;
   this.colorButton1.TabIndex = 2;
   this.colorButton1.Text = "播放";
   this.colorButton1.Click += new System.EventHandler(this.ColorButton1Click);
   //
   // colorButton2
   //
   this.colorButton2.Active = true;
   this.colorButton2.ButtonStyle = ColorButton.ColorButton.ButtonStyles.Rectangle;
   this.colorButton2.Font = new System.Drawing.Font("Verdana", 10F, System.Drawing.FontStyle.Bold);
   this.colorButton2.GradientStyle = ColorButton.ColorButton.GradientStyles.Vertical;
   this.colorButton2.HoverBorderColor = System.Drawing.Color.MediumVioletRed;
   this.colorButton2.HoverColorA = System.Drawing.Color.MediumVioletRed;
   this.colorButton2.HoverColorB = System.Drawing.Color.White;
   this.colorButton2.Location = new System.Drawing.Point(80, 80);
   this.colorButton2.Name = "colorButton2";
   this.colorButton2.NormalBorderColor = System.Drawing.Color.Green;
   this.colorButton2.NormalColorA = System.Drawing.Color.Green;
   this.colorButton2.NormalColorB = System.Drawing.Color.Honeydew;
   this.colorButton2.Size = new System.Drawing.Size(64, 32);
   this.colorButton2.SmoothingQuality = ColorButton.ColorButton.SmoothingQualities.AntiAlias;
   this.colorButton2.TabIndex = 3;
   this.colorButton2.Text = "停止";
   this.colorButton2.Click += new System.EventHandler(this.ColorButton2Click);
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(296, 126);
   this.Controls.Add(this.colorButton2);
   this.Controls.Add(this.colorButton1);
   this.Controls.Add(this.listBox1);
   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
   this.MaximizeBox = false;
   this.Name = "MainForm";
   this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   this.Text = "簡易收音機";
   this.ResumeLayout(false);
  }
  #endregion

  void listBox1Click(object sender, System.EventArgs e)
  {
    Paly.URL=listBox1.SelectedItem.ToString();
  }

  void ColorButton1Click(object sender, System.EventArgs e)
  {
      if (listBox1.SelectedItem.ToString().Length>0)
   {
    Paly.controls.play();
   }
  }

  void ColorButton2Click(object sender, System.EventArgs e)
  {
   Paly.controls.stop();
  }

 }
}


用C#.NET實現電子郵件客戶程式
--------------------------------------------------------------------------------
【摘要】通過C#這種VisualSTudio.NET中新引入的物件導向且類型安全的設計語言，
        在.NET平台上開發電子郵件客戶程式。通過套接字設計實現網路通信連接，
        闡述SMTP（簡單郵件傳輸協議）和POP3（郵局協議）的工作原理，然後具體
        講解了根據SMTP協議開發電子郵件客戶端的郵件發送程式，根據POP3協議開
        發電子郵件客戶端的郵件接收程式。

【關鍵詞】套接字  簡單郵件傳輸協議  郵局協議
http://msdn.microsoft.com/library/en-us/dncodefun/html/code4fun03282003.asp
1 C#中套接字的設計
套接字是通信的基石，是支持TCP/IP協議網路通信的基本操作單元。
可以將套接字看做不同主機間的進程進行雙向通信的端點，它構成了單個主機內及整個
網路間的設計界面。套接字存在於通信域中。通信域是為了處理一般的執行緒通過套接
字通信而引進的一種抽像概念。套接字通常和同一個域中的套接字交換資料（資料交換
也可能穿越域的界限，但這時一定要執行某種解釋程式）。各種進程使用這個相同的域
互相之間用Internet協議簇來進行通信。
針對C#中Socket設計用Socket類來進行，.NET 框架的Socket類是包含在System.Net.Sockets名字空間中
的一個非常重要的類，其中為實現網路設計提供了大量的方法。使用Socket類開發windows網路應用程式
原來有規可尋，它們在大多數情況下遵循大致相同的步驟。
在使用之前，你需要首先創建Socket對象的實例，這可以通過Socket類的構造方法來實現：
public Socket(AddressFamily addressFamily,SocketType socketType,ProtocolType protocolType);
其中，addressFamily參數指定Socket使用的尋址方案；
      socketType參數，指定Socket的類型；
      protocolType參數，指定Socket使用的協議。

下面的示例語句創建一個Socket，它可用於在基於TCP/IP的網路（如Internet）上通訊。
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
若要使用UDP而不是TCP，需要更改協議類型，如下面的示例所示：
Socket s=newSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
一旦創建Socket，在客戶端，將可以通過Connect方法連接到指定的伺服器，
並通過Send/SendTo方法向遠程伺服器發送資料，而後可以通過Receive/ReceiveFrom方法
從服務端接收資料；而在伺服器端，你需要使用Bind方法綁定所指定的介面使Socket與
一個本地終結點相聯，並通過Listen方法偵聽該介面上的請求，當偵聽到用戶端的連接時，
調用Accept完成連接的操作，創建新的Socket以處理傳入的連接請求。
使用完Socket後，記住使用Shutdown方法禁用Socket，並使用Close方法關閉Socket。
 2 SMTP和POP3協議的工作程序

在Internet上發送/接收電子郵件，要用到二個協議：
    SMTP（簡單郵件傳輸協議）和POP3（郵局協議）。

下面從SMTP和POP3協議入手，說明如何發送和接收電子郵件。
如圖1，描述了從發件人使用主機（Client1）發送一封郵件
從郵箱 one@server1.com 發往郵箱 two@server2.com
（其中域名為server1.com的郵件系統安裝在Server1上，域名為server2.com的郵件系統安裝在Server2上）
，收件人通過主機（Client2）接收到這封郵件的程序。
在郵件傳送的各個階段要採用不同的網路協議。

（1）發件人採用Mail Client端軟體在Client 1處撰寫一封郵件發給收件人，
     首先是將該郵件從Client1發送到他本人的郵箱 one@server1.com 所在的伺服器Server1上。
     這一步由Client1發往Server的程序採用的是SMTP協議。

                          圖1 電子郵件傳送程序示意圖

（2）郵件可以從發件人的郵件伺服器Server1直接傳送到收件人郵箱 two@server2.com 所在的伺服器
     Server2上，也可能需要經過第三方的郵件伺服器Server3做中轉後再送達接收方，這個程序稱
     為Relay。
     這一步在Mail Server之間進行郵件傳送的程序採用的是SMTP協議。
     郵件發送到接收方的伺服器Server2上後，由Server2負責將該郵件投遞到收件人的郵箱
     two@server2.com 中，保存在Server2的磁碟陣列中。此時，郵件傳送程序結束。

（3）收件人訪問他在Server2上的郵箱 two@server2.com 時，採用Mail Client端軟體Client2將Server2
     郵箱中的郵件下載到本地硬碟上閱讀。
     這一步將郵件從Server下載到Client的程序採用的是POP3協議。

     開發電子郵件客戶端實際上也就是利用套接字(Socket)設計進行對話通訊，
     按照SMTP協議和POP3協議的規範完成郵件傳輸。

3 郵件發送模塊的實現
 SMTP協議是TCP/IP協議棧中的一個廣為使用的上層協議。
 SMTP定義了如何在兩個用戶間傳輸郵件，使用了spooling的概念，允許將郵件從一個本地應用發送
 到一個SMTP應用。
 SMTP應用把郵件存儲到一個設備或記憶體中，一旦郵件到達SMTP應用，該郵件被放入到一個隊列中，
 一個伺服器檢查是否有郵件到達，然後試圖投遞到達的郵件。

 如果郵件的收方不存在，伺服器然後還會再進行嘗試。

 最終，如果郵件不能被投遞，則將該郵件丟棄或返回給郵件的發送者。
 這一概念被稱為端到端的投遞，並且它將郵件保存在隊列中，直到郵件被投遞出去。
 我們可以從兩個RFC中找到有關SMTP的討論。RFC822描述了報文的結構，其中還包括了信封。
 RFC821規定了在兩台機器間控制郵件交換的協議。

 以下模塊利用TcpClient類開發一個SMTP客戶端，以發送郵件。
3.1 發送SMTP命令
SMTP伺服器一般都識別UTF8碼，所有發送命令都使用UTF8編碼，每個命令均以回車換行符結束。
下列程式碼實現命令的發送功能。
private void WriteToNetStream(ref NetworkStream NetStream.string Command)
{
  string stringToSend = Command + "\r\n";
  Byte[] arrayToSend = System.Text.Encoding.UTF8.GetBytes(stringToSend.ToCharArray());
  NetStream.Write(arrayToSend,0,arrayToSend.Length);
}
3.2 答應碼的接收
SMTP伺服器對每一個都發出響應。下列程式碼實現接受答應碼的功能。
private string ReadFromNetStream(ref NetworkStream NetStream)
{
  byte[] bb=new byte[512];
  NetStream.Read(bb,0,bb.Length);
  string read=System.Text.Encoding.UTF8.GetString(bb);
}
3.3 應答碼檢查

發送郵件客戶端必須要檢查應答碼，以判斷伺服器是否已經執行了命令。
如果伺服器沒有執行，則重新發送命令或採用其他措施。
下列程式碼可以檢查伺服器是否正確地執行了命令。
private string checkForError(string
strMessage,string check)
{
if (strMessage.Indexof(check) ==
-1)
{
return
"err";
}
else
{
return
"correct";
}
}
上述方法的第一個參數是伺服器返回信息，第二個參數是要檢查的答應碼。
如果伺服器返回的信息中不存在第二個參數的字串，則返回"err"，表明伺服器沒正確執行命令。
 3.4 發送郵件

客戶端發出DATA命令，在伺服器作出354應答後，即可開始郵件內容的發送。
郵件以<CRLF>.<CRLF>結束。下列程式碼實現了郵件發送功能。
private void sendMail(ref NetworkStream NetStream, string message)
{
   Byte[] attayToSend = System.Text.Encoding.UTF8.GetBytes(message.ToCharArray());
   NetStream.Write(arrayToSend,0,arrayToSend.Length);
}
4 郵件接收模塊的實現

POP允許本地郵件UA(User Agent，用戶代理)連接SERVER並將郵件取回到用戶本地系統，
用戶也在本地機上閱讀和響應消息。POP3UA通過TCP/IP與伺服器連接(通常使用端口110)。
輸入用戶名和密碼經過認證後，UA可通過POP3命令取回或刪除郵件。
POP3僅僅是接收協議。
POP3UA使用SMTP向伺服器發送郵件。
利用POP3協議開發一個郵件接收程式，使用USER、PASS、STAT、LIST、RETR、DELE、QUIT命令。
下面開始開發程序。
 4.1 發送命令碼

 在此發送命令碼也使用的是ASCII碼。下列方法用於向伺服器發送命令碼：

private void WriteToNetStream(ref NetworkStream NetStream.string Command)
{
   string stringToSend = Command + "\r\n";
   Byte[]arrayToSend= System.Text.Encoding.ASCII.GetBytes(stringToSend.ToCharArray());
   NetStream.Write(arrayToSend,0,arrayToSend.Length);
}
4.2 接收伺服器應答
一般而言，接收伺服器應答，既可使用ASCII碼，也可以使用UTF8碼，這裡使用的是ASCII碼。
下列方法用於接受伺服器的應答。
private string ReadFromNetStream(ref NetworkStream NetStream)
{
   byte[] bb=new byte[1024];
   NetStream.Read(bb,0,bb.Length);
   string read=System.Text.Encoding.ASCII.GetString(bb);
   return read;
}
4.3 接受郵件
在此接收郵件用UTF8碼，當遇到<CRKF>.<CRLF>，則結束讀取資料。下列程式碼用於接收郵件：
private void ReadMail(ref
NetworkStream NetStream,int number)
{
int
k=0;
bool check=false;
byte[] bb=new
byte[6400];
while(!check)
{
k=NetStream.Read(bb,0,bb.Length);
string read=System.Text.Encoding.UTF8.GetString(bb,0,k);
int x= read.IndexOf("\r\n.\r\n");
if(x!=-1)
{
check=true;
}
richTextBox2.AppendText(read);
WriteToNetStream(ref
NetStream,"DELE "+number.ToString());
string
back=ReadFromNetStream(ref NetStream );
richTextBox1.AppendText("DELE "+number.ToString()+"命令應答："+back+"\r\n");
}
}

5 結束語
把郵件發送模塊和郵件接收模塊合起來,就成為一個電子郵件的客戶端程式。
在實際應用中，在上面基礎上加以改進，如果再進一步結合資料庫技術，這可以開發出易用、
可靠的電子郵件的客戶端程式。


透過WebBrowser 控制項 來 Post Form Data
底下連結的文章中詳細說明如何在 Visual C# .NET 使用 WebBrowser ActiveX 控制項來執行 post of form data。
http://support.microsoft.com/default.aspx?scid=KB;EN-US;313068


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/25
 * 建立時間: 下午 11:56
 * 功    能: axWebBrowser基本瀏覽器製作
 * 修改日期: 2004/8/25 下午 11:56
 */
using System;
using System.Windows.Forms;
namespace DefaultNamespace
{
///
<summary>
/// Description of MainForm.
///
</summary>
public class MainForm :
System.Windows.Forms.Form
{
private
System.Windows.Forms.Button button3;
private
System.Windows.Forms.Button button2;
private
System.Windows.Forms.Button button1;
private
AxSHDocVw.AxWebBrowser axWebBrowser1;
private
System.Windows.Forms.Button button5;
private
System.Windows.Forms.Button button4;
private
System.Windows.Forms.Panel panel1;
private
System.Windows.Forms.TextBox textBox1;
public
MainForm()
{
//
// The
InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();

//
//
TODO: Add constructor code after the InitializeComponent()
call.
//
}

[STAThread]
public
static void Main(string[]
args)
{
Application.Run(new
MainForm());
}

#region Windows
Forms Designer generated code
///
<summary>
/// This method is required for Windows Forms
designer support.
/// Do not change the method contents inside
the source code editor. The Forms designer might
/// not be able
to load this method if it was changed manually.
///
</summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new
System.Resources.ResourceManager(typeof(MainForm));
this.textBox1
= new System.Windows.Forms.TextBox();
this.panel1 = new
System.Windows.Forms.Panel();
this.button4 = new
System.Windows.Forms.Button();
this.button5 = new
System.Windows.Forms.Button();
this.axWebBrowser1 = new
AxSHDocVw.AxWebBrowser();
this.button1 = new
System.Windows.Forms.Button();
this.button2 = new
System.Windows.Forms.Button();
this.button3 = new
System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0,
0);
this.textBox1.Name =
"textBox1";
this.textBox1.Size = new
System.Drawing.Size(528, 22);
this.textBox1.TabIndex =
1;
this.textBox1.Text = " http://tw.yahoo.com ";
//
//
panel1
//
this.panel1.Dock =
System.Windows.Forms.DockStyle.Top;
this.panel1.Location =
new System.Drawing.Point(0, 0);
this.panel1.Name =
"panel1";
this.panel1.Size = new System.Drawing.Size(600,
64);
this.panel1.TabIndex = 7;
//
// button4
//
this.button4.FlatStyle =
System.Windows.Forms.FlatStyle.System;
this.button4.Location
= new System.Drawing.Point(168, 32);
this.button4.Name =
"button4";
this.button4.TabIndex =
5;
this.button4.Text =
"首頁";
this.button4.Click += new
System.EventHandler(this.Button4Click);
//
// button5
//
this.button5.FlatStyle =
System.Windows.Forms.FlatStyle.System;
this.button5.Location
= new System.Drawing.Point(248, 32);
this.button5.Name =
"button5";
this.button5.TabIndex =
6;
this.button5.Text =
"搜尋";
this.button5.Click += new
System.EventHandler(this.Button5Click);
//
// axWebBrowser1
//
this.axWebBrowser1.Dock =
System.Windows.Forms.DockStyle.Fill;
this.axWebBrowser1.Enabled
= true;
this.axWebBrowser1.Location = new
System.Drawing.Point(0, 64);
this.axWebBrowser1.OcxState =
((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState")));
this.axWebBrowser1.Size
= new System.Drawing.Size(600,
278);
this.axWebBrowser1.TabIndex =
0;
//
//
button1
//
this.button1.FlatStyle =
System.Windows.Forms.FlatStyle.System;
this.button1.Location
= new System.Drawing.Point(536, 0);
this.button1.Name =
"button1";
this.button1.Size = new System.Drawing.Size(56,
24);
this.button1.TabIndex =
2;
this.button1.Text =
"GO";
this.button1.Click += new
System.EventHandler(this.Button1Click);
//
// button2
//
this.button2.FlatStyle =
System.Windows.Forms.FlatStyle.System;
this.button2.Location
= new System.Drawing.Point(8, 32);
this.button2.Name =
"button2";
this.button2.TabIndex =
3;
this.button2.Text =
"上一頁";
this.button2.Click += new
System.EventHandler(this.Button2Click);
//
// button3
//
this.button3.FlatStyle =
System.Windows.Forms.FlatStyle.System;
this.button3.Location
= new System.Drawing.Point(88, 32);
this.button3.Name =
"button3";
this.button3.TabIndex =
4;
this.button3.Text =
"下一頁";
this.button3.Click += new
System.EventHandler(this.Button3Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5,
15);
this.ClientSize = new System.Drawing.Size(600,
342);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.axWebBrowser1);
this.Controls.Add(this.panel1);
this.Name
= "MainForm";
this.Text =
"MainForm";
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit();
this.ResumeLayout(false);
}
#endregion

  //首頁
  void Button4Click(object sender, System.EventArgs e)
  {
   axWebBrowser1.GoHome();
  }
//上一頁
void Button2Click(object sender,
System.EventArgs
e)
{
try
{
axWebBrowser1.GoBack();
}
catch(Exception
ee)
{
MessageBox.Show("訊息:"+ee.Message.ToString());
}
}

  //開啟網址
  void Button1Click(object sender, System.EventArgs e)
  {
   object oNull = null;
   axWebBrowser1.Navigate(textBox1.Text,ref oNull, ref oNull,ref oNull,ref oNull);
  }
//下一頁
void Button3Click(object sender,
System.EventArgs
e)
{
try
{
axWebBrowser1.GoForward();
}
catch(Exception
ee)
{
MessageBox.Show("訊息:"+ee.Message.ToString());
}
}
//搜尋
void Button5Click(object sender,
System.EventArgs
e)
{
axWebBrowser1.GoSearch();
}

}
}


寄信程式
在.NET中發送郵件需要什麼？ 首先，也是最重要的，需要安裝.NET Framework。
其次需要引用System.Web.dll（ASP.NET應用程式已經自動包含了）。
接著需要引用System.Web.Main命名空間，以便建立和發送email信息。

因為SWM只是簡單的封裝了兩個COM庫：CDONTS.NewMail（可以在cdonts.dll中找到）
和CDO.Message（可以在cdosys.dll中找到），因此伺服器上同樣也需要他們。
如果使用NT4或Win9x，cdonts.dll會隨著NT4的Option Pack或者Personal webserver一起安裝。
預設情況cdosys.dll已經安裝在Windows 2003和Windows XP中了，
同樣安裝Microsoft Office也會安裝cdosys.dll

使用SWM發送郵件時，你需要一個轉發伺服器。
轉發伺服器就是一個郵件伺服器或者一個SMTP伺服器/服務，它可以發送郵件。
SWM簡單的發送郵件到轉發伺服器，轉發伺服器負責傳送到最終目的地。
程式碼如下：
//
// Created by SharpDevelop.
// User: Administrator
// Date: 2004/7/31
// Time: 下午 11:19
//
// To change this template use Tools | Options | Coding | Edit Standard Headers.
//
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Web.Mail;
namespace DefaultNamespace
{
 public class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button2;
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.MenuItem menuItem7;
  private System.Windows.Forms.TextBox textBox4;
  private System.Windows.Forms.MenuItem menuItem3;
  private System.Windows.Forms.MenuItem menuItem2;
  private System.Windows.Forms.MenuItem menuItem1;
  private System.Windows.Forms.MenuItem menuItem6;
  private System.Windows.Forms.MenuItem menuItem5;
  private System.Windows.Forms.MenuItem menuItem4;
  private System.Windows.Forms.ContextMenu contextMenu1;
  private System.Windows.Forms.Label label3;
  private System.Windows.Forms.Label label2;
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.RichTextBox richTextBox1;
  private System.Windows.Forms.Label label5;
  private System.Windows.Forms.Label label4;
  private System.Windows.Forms.TextBox textBox1;
  private System.Windows.Forms.TextBox textBox3;
  private System.Windows.Forms.TextBox textBox2;
  public static void Main()
  {
   MainForm fMainForm = new MainForm();
   fMainForm.ShowDialog();
  }
#region Windows Forms Designer generated code
  // This method is required for Windows Forms designer support.
  // Do not change the method contents inside the source code editor. The Forms designer might
  // not be able to load this method if it was changed manually.
  public MainForm()
  {
   base.New();
   //
   // The Me.InitializeComponent call is required for Windows Forms designer support.
   //
   this.InitializeComponent();
   //
   // TODO : Add constructor code after InitializeComponents
   //
  }
  private void InitializeComponent()
  {
   this.textBox2 = new System.Windows.Forms.TextBox();
   this.textBox3 = new System.Windows.Forms.TextBox();
   this.textBox1 = new System.Windows.Forms.TextBox();
   this.label4 = new System.Windows.Forms.Label();
   this.label5 = new System.Windows.Forms.Label();
   this.richTextBox1 = new System.Windows.Forms.RichTextBox();
   this.label1 = new System.Windows.Forms.Label();
   this.label2 = new System.Windows.Forms.Label();
   this.label3 = new System.Windows.Forms.Label();
   this.contextMenu1 = new System.Windows.Forms.ContextMenu();
   this.menuItem4 = new System.Windows.Forms.MenuItem();
   this.menuItem5 = new System.Windows.Forms.MenuItem();
   this.menuItem6 = new System.Windows.Forms.MenuItem();
   this.menuItem1 = new System.Windows.Forms.MenuItem();
   this.menuItem2 = new System.Windows.Forms.MenuItem();
   this.menuItem3 = new System.Windows.Forms.MenuItem();
   this.textBox4 = new System.Windows.Forms.TextBox();
   this.menuItem7 = new System.Windows.Forms.MenuItem();
   this.button1 = new System.Windows.Forms.Button();
   this.button2 = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   //textBox2
   //
   this.textBox2.BackColor = System.Drawing.SystemColors.Info;
   this.textBox2.Location = new System.Drawing.Point(104, 32);
   this.textBox2.Name = "textBox2";
   this.textBox2.Size = new System.Drawing.Size(160, 22);
   this.textBox2.TabIndex = 7;
   this.textBox2.Text = "";
   //
   //textBox3
   //
   this.textBox3.Location = new System.Drawing.Point(104, 57);
   this.textBox3.Name = "textBox3";
   this.textBox3.Size = new System.Drawing.Size(160, 22);
   this.textBox3.TabIndex = 8;
   this.textBox3.Text = "";
   //
   //textBox1
   //
   this.textBox1.BackColor = System.Drawing.SystemColors.Info;
   this.textBox1.Location = new System.Drawing.Point(104, 7);
   this.textBox1.Name = "textBox1";
   this.textBox1.Size = new System.Drawing.Size(128, 22);
   this.textBox1.TabIndex = 6;
   this.textBox1.Text = "";
   //
   //label4
   //
   this.label4.ForeColor = System.Drawing.SystemColors.ActiveCaption;
   this.label4.Location = new System.Drawing.Point(44, 87);
   this.label4.Name = "label4";
   this.label4.Size = new System.Drawing.Size(56, 16);
   this.label4.TabIndex = 4;
   this.label4.Text = "信件主旨";
   //
   //label5
   //
   this.label5.ForeColor = System.Drawing.SystemColors.ActiveCaption;
   this.label5.Location = new System.Drawing.Point(44, 112);
   this.label5.Name = "label5";
   this.label5.Size = new System.Drawing.Size(56, 16);
   this.label5.TabIndex = 5;
   this.label5.Text = "信件內容";
   //
   //richTextBox1
   //
   this.richTextBox1.ContextMenu = this.contextMenu1;
   this.richTextBox1.Location = new System.Drawing.Point(104, 112);
   this.richTextBox1.Name = "richTextBox1";
   this.richTextBox1.Size = new System.Drawing.Size(512, 200);
   this.richTextBox1.TabIndex = 10;
   this.richTextBox1.Text = "";
   //
   //label1
   //
   this.label1.ForeColor = System.Drawing.Color.Red;
   this.label1.Location = new System.Drawing.Point(9, 12);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(96, 16);
   this.label1.TabIndex = 1;
   this.label1.Text = "郵件伺服器位置";
   //
   //label2
   //
   this.label2.ForeColor = System.Drawing.Color.Red;
   this.label2.Location = new System.Drawing.Point(32, 37);
   this.label2.Name = "label2";
   this.label2.Size = new System.Drawing.Size(72, 16);
   this.label2.TabIndex = 2;
   this.label2.Text = "寄件者信箱";
   //
   //label3
   //
   this.label3.ForeColor = System.Drawing.SystemColors.ActiveCaption;
   this.label3.Location = new System.Drawing.Point(32, 63);
   this.label3.Name = "label3";
   this.label3.Size = new System.Drawing.Size(88, 16);
   this.label3.TabIndex = 3;
   this.label3.Text = "收件者信箱";
   //
   //contextMenu1
   //
   this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {this.menuItem1, this.menuItem2, this.menuItem3, this.menuItem4, this.menuItem5, this.menuItem6, this.menuItem7});
   //
   //menuItem4
   //
   this.menuItem4.Index = 3;
   this.menuItem4.Text = "複製";
   this.menuItem4.Click += new System.EventHandler(this.MenuItem4Click);
   //
   //menuItem5
   //
   this.menuItem5.Index = 4;
   this.menuItem5.Text = "貼上";
   this.menuItem5.Click += new System.EventHandler(this.MenuItem5Click);
   //
   //menuItem6
   //
   this.menuItem6.Index = 5;
   this.menuItem6.Text = "-";
   //
   //menuItem1
   //
   this.menuItem1.Index = 0;
   this.menuItem1.Text = "復原";
   this.menuItem1.Click += new System.EventHandler(this.MenuItem1Click);
   //
   //menuItem2
   //
   this.menuItem2.Index = 1;
   this.menuItem2.Text = "-";
   //
   //menuItem3
   //
   this.menuItem3.Index = 2;
   this.menuItem3.Text = "剪下";
   this.menuItem3.Click += new System.EventHandler(this.MenuItem3Click);
   //
   //textBox4
   //
   this.textBox4.Location = new System.Drawing.Point(104, 83);
   this.textBox4.Name = "textBox4";
   this.textBox4.Size = new System.Drawing.Size(280, 22);
   this.textBox4.TabIndex = 9;
   this.textBox4.Text = "";
   //
   //menuItem7
   //
   this.menuItem7.Index = 6;
   this.menuItem7.Text = "全選";
   this.menuItem7.Click += new System.EventHandler(this.MenuItem7Click);
   //
   //button1
   //
   this.button1.BackColor = System.Drawing.Color.Gray;
   this.button1.Cursor = System.Windows.Forms.Cursors.Hand;
   this.button1.Font = new System.Drawing.Font("新細明體", 9.75, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)136));
   this.button1.ForeColor = System.Drawing.Color.White;
   this.button1.Location = new System.Drawing.Point(392, 320);
   this.button1.Name = "button1";
   this.button1.Size = new System.Drawing.Size(224, 32);
   this.button1.TabIndex = 0;
   this.button1.Text = "立刻傳送郵件...";
   this.button1.Click += new System.EventHandler(this.Button1Click);
   //
   //button2
   //
   this.button2.BackColor = System.Drawing.Color.Red;
   this.button2.Cursor = System.Windows.Forms.Cursors.Hand;
   this.button2.ForeColor = System.Drawing.Color.White;
   this.button2.Location = new System.Drawing.Point(528, 80);
   this.button2.Name = "button2";
   this.button2.Size = new System.Drawing.Size(80, 24);
   this.button2.TabIndex = 11;
   this.button2.Text = "重寫";
   this.button2.Click += new System.EventHandler(this.Button2Click);
   //
   //MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.BackColor = System.Drawing.Color.Wheat;
   this.ClientSize = new System.Drawing.Size(624, 358);
   this.Controls.Add(this.button2);
   this.Controls.Add(this.richTextBox1);
   this.Controls.Add(this.textBox4);
   this.Controls.Add(this.textBox3);
   this.Controls.Add(this.textBox2);
   this.Controls.Add(this.textBox1);
   this.Controls.Add(this.label5);
   this.Controls.Add(this.label4);
   this.Controls.Add(this.label3);
   this.Controls.Add(this.label2);
   this.Controls.Add(this.label1);
   this.Controls.Add(this.button1);
   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
   this.MaximizeBox = false;
   this.Name = "MainForm";
   this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   this.Text = "寄信程式 .NET版";
   this.ResumeLayout(false);
  }
#endregion
  private void Button1Click(object sender, System.EventArgs e)
  {
   MailMessage oMail = new MailMessage();
   // 指定SMTP-Server
   SmtpMail.SmtpServer = textBox1.text;
   // 寄件者信箱
   oMail.From = textBox2.text;
   // 收件者信箱
   oMail.To = textBox3.text;
   // 信件主旨
   oMail.Subject = textBox4.text;
   // 信件內容
   oMail.Body = richTextBox1.Text;
   // 附加檔案
   // .Attachments.Add(New MailAttachment("檔案名稱"))
   try {
    SmtpMail.Send(oMail);
    MessageBox.show("傳送完成！");
   } catch (Exception oEx) {
    MessageBox.show("傳送失敗原因：" + oEx.Message.ToString);
   }
  }
  private void Button2Click(object sender, System.EventArgs e)
  {
   richTextBox1.Clear();
  }
  private void MenuItem1Click(object sender, System.EventArgs e)
  {
   richTextBox1.Undo();
  }
  private void MenuItem3Click(object sender, System.EventArgs e)
  {
   richTextBox1.Cut();
  }
  private void MenuItem4Click(object sender, System.EventArgs e)
  {
   richTextBox1.Copy();
  }
  private void MenuItem5Click(object sender, System.EventArgs e)
  {
   richTextBox1.Paste();
  }
  private void MenuItem7Click(object sender, System.EventArgs e)
  {
   richTextBox1.SelectAll();
  }
 }
}


/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: Administrator
 * 建立日期: 2004/8/6
 * 建立時間: 上午 12:35
 * 功    能: 電腦名稱之IP查詢
 * 修改日期: 上午 12:35
 */
using System;
using System.Windows.Forms;
using System.Net;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.TextBox textBox1;
  private System.Windows.Forms.TextBox textBox2;
  private System.Windows.Forms.Label label2;
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.label2 = new System.Windows.Forms.Label();
   this.textBox2 = new System.Windows.Forms.TextBox();
   this.textBox1 = new System.Windows.Forms.TextBox();
   this.button1 = new System.Windows.Forms.Button();
   this.label1 = new System.Windows.Forms.Label();
   this.SuspendLayout();
   //
   // label2
   //
   this.label2.AutoSize = true;
   this.label2.Location = new System.Drawing.Point(8, 40);
   this.label2.Name = "label2";
   this.label2.Size = new System.Drawing.Size(77, 18);
   this.label2.TabIndex = 1;
   this.label2.Text = "電腦IP位址：";
   //
   // textBox2
   //
   this.textBox2.Location = new System.Drawing.Point(104, 40);
   this.textBox2.Name = "textBox2";
   this.textBox2.Size = new System.Drawing.Size(136, 22);
   this.textBox2.TabIndex = 3;
   this.textBox2.Text = "";
   //
   // textBox1
   //
   this.textBox1.Location = new System.Drawing.Point(104, 12);
   this.textBox1.Name = "textBox1";
   this.textBox1.Size = new System.Drawing.Size(136, 22);
   this.textBox1.TabIndex = 2;
   this.textBox1.Text = "";
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(168, 72);
   this.button1.Name = "button1";
   this.button1.TabIndex = 4;
   this.button1.Text = "查詢IP";
   this.button1.Click += new System.EventHandler(this.Button1Click);
   //
   // label1
   //
   this.label1.AutoSize = true;
   this.label1.Location = new System.Drawing.Point(8, 16);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(91, 18);
   this.label1.TabIndex = 0;
   this.label1.Text = "輸入電腦名稱：";
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(248, 102);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.textBox2);
   this.Controls.Add(this.textBox1);
   this.Controls.Add(this.label2);
   this.Controls.Add(this.label1);
   this.Name = "MainForm";
   this.Text = "電腦名稱之IP查詢";
   this.ResumeLayout(false);
  }
  #endregion
  void Button1Click(object sender, System.EventArgs e)
  {
   try{
   IPHostEntry ipHost = Dns.GetHostByName(textBox1.Text);
   IPAddress[] ipAddr = ipHost.AddressList;
   for(int x = 0; x < ipAddr.Length; x++)
    {
    textBox2.Text= ipAddr[x].ToString();
    }
   }catch(System.Net.Sockets.SocketException){
            MessageBox.Show("電腦名稱不存在.");
         }
  }

 }
}


Use P/Invoke to Develop a .NET Base Class Library for Serial Device Communications

This article assumes you're familiar with C# and RS232 communications
3
Download the code for this article: NetSerialComm.exe (89KB)
SUMMARY Out-of-the-box, the only way of coding RS232 serial communications applications in the .NET environment is to import the outdated and somewhat limited MSComm ActiveX control. This article describes the development of a lean, multithreaded, and modern RS232 base class library in C# managed code. The library uses Platform Invocation Services to interact with the Win32 API directly. Application programmers can use the library from any .NET language through inheritance; the article explores examples written in C# and Visual Basic .NET.
he Microsoft𦲷 .NET Framework Class Library (FCL) provides reasonably comprehensive coverage of the functionality of the underlying Win32𦲷 API, greatly contributing to the sophistication of the C# and Visual Basic𦲷 .NET languages. However, RS232 serial communications is one area that is conspicuously absent from the library. To be fair, most people probably now regard these ports as legacy baggage. These days, you interact with serial modems via software layers such as TAPI or PPP. Other devices that once used these ports are now migrating to USB. Nevertheless, the need for device drivers for specialized RS232 devices such as GPS receivers, barcode and swipe card readers, programmable controllers, and device programmers will continue for the foreseeable future. (For RS232 port specs, see the sidebar "Hardware Specs".)
Platform Invocation Services (P/Invoke) is the .NET technology that enables managed code in the common language runtime (CLR) to make calls into unmanaged DLLs, including those that implement the Win32 API. In this article, I will wrap the API functions provided for RS232 communications in CLR managed classes using C#. The resultant base class library will make it relatively easy to develop drivers for specific devices using any .NET language. Full source code for the library and examples is available for download from the link at the top of this article.

Design Principles
There are at least four design options that you should consider when encapsulating the Win32 serial communications functions in managed classes:
  1. Use P/Invoke to wrap the API functions, constants, and structure definitions as static members of a managed class. While I use this approach internally, I do not expose this class to application programmers.
  2. 2.Write a stream handler. This is a generalized, extensible abstraction used by the framework for file, console, and network communications. At first sight, this is attractive, but on closer examination it is better suited to traditional modem communications than to the command-response syntaxes of modern serial devices.
  3. 3.Build a direct replacement for the MSComm OLE Control Extension (OCX). In other words, create a class that encapsulates the API file handle and provides a number of generalized methods and events (Open, Close, Read, Write, and so on). You could reuse this functionality by instantiating an object of the library class within the application class—that is, by aggregation, COM-style.
  4. 4.Write a base class from which the application code inherits. This is a truly object-oriented approach that exploits the wonderful .NET trick of language-independent run-time inheritance. The generalized methods are inherited into the application object and virtual methods are used rather than events. The application object provides a public interface in terms appropriate to the actual RS232 device (for example, a GPS receiver driver might have public properties for latitude and longitude).
I will employ the fourth approach. The library will contain two base classes declared as abstract (they can't be instantiated), but I will use them as base classes for building application-specific classes through inheritance. Figure 1 illustrates the inheritance hierarchy.
Figure 1 Inheritance Hierarchy
Figure 1 Inheritance Hierarchy
The first library class, CommBase, makes no assumptions about data formatting and provides facilities for opening and closing the communications port, sending and receiving bytes of data, and interacting with the control inputs and outputs.
The second library class, CommLine, inherits from CommBase and makes two assumptions: that the coding of the bytes sent and received is ASCII and that a reserved ASCII control code will mark the termination of variable-length lines of data, enabling transmission and reception of strings. Of course, this model is extensible; you could write alternative versions of CommLine for Unicode communications, for example.

Using the Base Classes
 Two example applications, BaseTerm and LineTerm, are available for download. These are general-purpose terminal emulators allowing experimentation with just about any serial device, including a modem. I will take a brief look from a user perspective at BaseTerm, then analyze the source code for LineTerm in detail.
Figure 2 BaseTerm
Figure 2 BaseTerm
BaseTerm (see Figure 2) is a full Windows𦲷 Forms-based application that inherits from CommBase to provide a byte-oriented diagnostic terminal. The Settings button brings up a form to enable editing of the full range of communications settings (see Figure 3). The menus on this form enable the user to save and load settings to XML-structured files, as well as a number of presets for common flow control scenarios. Tooltips explain the use of the individual settings. Once saved to XML, you can specify the file on the command line when you start the program again. Once the link is online, typed characters get sent to the remote device immediately. Keyboard keys send the appropriate ASCII byte, and if you want you can send non-keyboard codes using an escape facility.
Figure 3 Comm Settings
Figure 3 Comm Settings
To start an escape, type the open angle bracket (<) character. Then, type either an ASCII control code name or a decimal number between 0 and 255. To terminate the escape, type the > character, which will cause the appropriate ASCII code to be sent immediately. The < character can be sent by typing it twice. You can view a list of valid ASCII control code names in the "Xon Code" dropdown on the settings dialog, and sites like http://www.asciitable.com provide additional useful information. The larger text box on the terminal window displays all received bytes in either ASCII or hexadecimal without further interpretation.
You can use display settings to break received lines either after reception of a specific ASCII character or after a fixed number of characters. The Status button displays a report of the status of the transmission and reception queues.
LineTerm uses CommLine as its base class and illustrates how to use the library in source code. You will need to run it from the Visual Studio𦲷 IDE because there is no user interface for settings. In Visual Studio .NET, create a new Visual Basic console application. Remove the supplied default module from the project. Copy LineTerm.vb, CommBase.dll, and CommBase.xml into the project directory (the XML file provides IntelliSense𦲷 information for the library). Use Add Existing Item in the project explorer to import LineTerm.vb and Add Reference to set a reference to CommBase.dll. You should now be able to build and run the project.
Figure 4 shows the complete source code for this example. In the first line, I import the namespace for the library. Then I create a new class, LineTerm, that inherits from CommLine. This provides the public methods Open and Close (actually inherited from CommBase), and the protected method Send, which I make public as SendCommand. In my new class, I override a number of virtual methods from the base classes. The CommSettings method is invoked by Open to configure the communications port; it must return an initialized CommBaseSettings object.
I actually use CommLineSettings here, which is fine because it inherits from CommBaseSettings. In the last two lines of this function, I first pass the object to the Setup method, which is inherited from CommLine, and then return it to CommBase. All the settings are public members and can be set directly, but there is also a helper method, SetStandard, which automatically configures the most common settings for CommBase. You will probably need to edit the parameters to this function and the line terminator and filter members to suit the device you have available for testing.
The Main method for the application simply creates an instance of my class, invokes the Open method, and provides a console harness for sending strings and displaying received strings. There are two methods of doing this: blocking and non-blocking. Using SendCommand starts non-blocking communications. This function returns immediately, then sometime later the send will complete and the OnTxDone override will report this. Later still, when the remote device has transmitted a complete response line, the OnRxLine override will display it on the console. During this time, the Main routine waits for user input, but it could have been getting on with other work. If you comment out SendCommand and enable TransactCommand instead, the same action will be performed using blocking communications. Here the Main routine will block at this line until the response is available. You will still see the message from OnTxDone, but instead of the RECEIVED message from OnRxLine you will see the RESPONSE message from TransactCommand.
Figure 5 Flow Control for GPS
Figure 5 Flow Control for GPS
In a real application, such as a driver for a GPS receiver, you would not simply make the Send or Transact methods public in the same way as I did in this example. Instead, you would provide public methods and properties exposing the functionality of the device (for example, properties like Speed and Altitude, or an event like PositionChanged). These methods should assemble the necessary command, use the Transact method, and then parse the response to extract the return value. Figure 5 illustrates the flow control for such a device driver.

Sending
 In serial communications, as in so much of life, sending messages is much easier than receiving them. For reception, you are at the whim of the remote device, whereas for transmission, you remain in control of the timing. However, at typical speeds of between 2 and 20,000 baud compared to computer speeds in the gigahertz range, you do not want to be cooling your heels waiting for transmission operations to complete. The Win32 API treats serial communications as a special case of file operations and uses a technique that is known as overlapped I/O to provide non-blocking operations.
The CommBase class provides the public method Open, which uses the Win32 API function CreateFile to open a serial port and store the resulting operating system handle as a private member variable:
hPort = Win32Com.CreateFile(cs.port,
   Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero,
   Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED,
   IntPtr.Zero);
The first parameter is the port name as a string, usually COM1: or COM2:, but in theory the name could be anything, so I have used a string rather than a number. I haven't found any way to determine a list of valid port names, so I have chosen to let the caller attempt to open any port, accepting the fact that this may fail. Failure may also occur if the port exists but is already in use by another application, in which case Open returns false. I use FILE_FLAG_OVERLAPPED to specify that all operations on this file handle will be non-blocking, and the rest of the parameters are boilerplate for serial communications.
  Win32Com is a helper class used as a container for static definitions of the API functions, structures, and constants that I will be using via P/Invoke. CreateFile is declared as follows in C#:
[DllImport("kernel32.dll", SetLastError=true)]
internal static extern IntPtr CreateFile(String lpFileName,
   UInt32 dwDesiredAccess, UInt32 dwShareMode,
   IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition,
   UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);
The various constants are also defined here. For example:
internal const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000;

Since there is currently very little tool support for P/Invoke, I have had to handcraft these definitions. The key resources include the Win32 API documentation and the header files provided for use with C++. (The excellent file search facilities in Visual Studio .NET are invaluable for finding definitions in the header files. I use these for documentation purposes only; you don't need them to compile the library.) A full discussion of interop marshaling, the process by which managed data types are translated into the unmanaged C definitions used by the API, is beyond the scope of this article. However, you can get an idea of what is going on under the hood from another piece of code in the Open method:
wo.Offset = 0;
wo.OffsetHigh = 0;
if (checkSends)
    wo.hEvent = writeEvent.Handle;
else
    wo.hEvent = IntPtr.Zero;
ptrUWO = Marshal.AllocHGlobal(Marshal.SizeOf(wo));
Marshal.StructureToPtr(wo, ptrUWO, true);

Here, wo is a local variable of type Win32Com.OVERLAPPED, and ptrUWO is a private class variable of type IntPtr. Marshal is a static object in System.Runtime.InteropServices that provides access to the interop marshaler. In this code, I am doing manually what the marshaler normally does automatically when an external function is called. The first step is to allocate an appropriately sized block of unmanaged memory, then copy the contents of the managed structure into it, remapping the memory layout as required. After the function call, the marshaler would normally use Marshal.PtrToStructure to perform the reverse copy, then Marshal.FreeHGlobal to release the memory. I perform this operation manually because of the special way the API uses the OVERLAPPED structure. I will specify it in a WriteFile call, but then the operating system will continue to use it after the call returns.
Some time later, I will call GetOverlappedResult, specifying the same structure again. If I left this up to automatic marshaling, the risk would be that the unmanaged memory would be reallocated between the two calls. In this case, unmarshaling is not necessary since the fields do not need to be accessed again. The memory must, however, be deallocated when the port is closed:
if (ptrUWO != IntPtr.Zero) Marshal.FreeHGlobal(ptrUWO);
With this groundwork in place, actually sending an array of bytes is quite straightforward:
if (!Win32Com.WriteFile(hPort, tosend, (uint)writeCount,
   out sent, ptrUWO))
if (Marshal.GetLastWin32Error != Win32Com.ERROR_IO_PENDING)
   ThrowException("Unexpected failure");

The tosend parameter is a pointer to an array of bytes; writeCount is the number of bytes in the array; the sent parameter will return the number of bytes actually sent; and ptrUWO is a pointer to the unmanaged version of OVERLAPPED, as already created. Normally, the function will return false and the error code will be ERROR_IO_PENDING. This is a pseudo-error which indicates that the operation has been queued because it could not be completed immediately. Any other error code means that the operation could not be queued. With buffered serial hardware and short send strings, it is possible that the operation will be completed immediately, in which case the function will return true.
Before sending new data, the result of any previous Send should be checked, enabling the detection of error conditions or timeouts. (Strangely, the API treats a pending operation as an error, but a timeout as perfectly normal—the only way of detecting it is that fewer bytes are sent than were queued. Ironing out this kind of anomaly is one of the hidden pleasures of writing a wrapper library!) Although I could allow multiple pending sends, each with its own OVERLAPPED structure, it would add a lot of complexity. Instead, I have blocked a subsequent Send until the previous one completes. If this blocking is a problem, it can be disabled by setting the checkAllSends member to false, in which case the OVERLAPPED structure is reused and there is no guarantee that errors or timeouts will be caught.

Receiving
 As you might guess, receiving data is simply a matter of calling the API ReadFile function. As previously mentioned, the difficult part is not so much receiving, but knowing when to receive. To avoid forcing application programmers to continually poll for data, some form of callback mechanism is required. Virtual methods called from a worker thread can perform this function. CommBase invokes a virtual method on reception of each byte. This method is overridden in CommLine to buffer up the bytes and call a different virtual method when a line terminator is received.
To make this work, I create a second thread of execution using the following code in the Open method:
rxThread = new Thread(new ThreadStart(this.ReceiveThread));
rxThread.Name = "ComBaseRx";
rxThread.Priority = ThreadPriority.AboveNormal;
rxThread.Start;
Thread.Sleep(1);
This starts up a new thread running the code in the private method ReceiveThread. The need for the final line surprised me; I assumed that the new, higher priority thread would preempt the original thread at the Start command. For some reason it does not and this created problems because the worker thread was not always ready when it was first needed. As a second attempt, I used Sleep(0) which the documentation suggests should allow preemption without wasting time (most of a whole millisecond, for goodness sake!), but again this did not work in practice.
ReceiveThread is an infinite loop of code broken only on an exception. I terminate the thread on closing the port using the following line:
rxThread.Abort;
This throws a ThreadAbortException in the thread, causing it to terminate via the catch clause, which is used for tidying up. A finally clause could also be used, but in this case it makes is no difference because the only exit route is through an exception.
Figure 6 shows a simplified version of ReceiveThread. SetCommMask indicates that I want to be notified when a new byte arrives. WaitCommEvent may return true, in which case there is already one or more bytes waiting. If it returns false with error code ERROR_IO_PENDING, I can suspend the thread until a byte arrives. The OVERLAPPED structure that was passed to WaitCommEvent includes the handle to an AutoResetEvent, which will be signaled when the byte arrives. When I execute the AutoResetEvent's WaitOne method, execution is suspended until the event is signaled.
Whether WaitCommEvent returns true immediately or signals completion later, the eventMask variable will contain a bitmask identifying which of the conditions requested in SetCommMask actually occurred (in the real code, I specify some other housekeeping conditions as well).
Notice that I use the same manual marshaling trick for eventMask as previously discussed for OVERLAPPED. I suspect this is not actually necessary and that automatic marshaling might work, but the exact behavior is not documented so it's better to be safe than sorry. Replacing the unmarshaled pointer with the managed variable as a reference parameter seems to work, but it may just be luck that the memory has not been reused.
Depending on timing, more than one character may be waiting, so the queue is drained one character at a time using ReadFile repeatedly and calling the virtual function OnRxChar with each character. When I get ERROR_IO_PENDING, I call CancelIo because I don't want to wait here; I want to loop back and wait at WaitCommEvent.
Error handling and exceptions need to be carefully considered when using worker threads. Any unhandled exceptions that occur in ReceiveThread, any of the virtual methods called from it, and any methods or events called or fired from any of these will propagate up and be handled by the catch clause. If the exception is not ThreadAbortException, it is stored in a private member of CommBase and the thread is then terminated. The next time the application code invokes a method on the primary thread, the exception is raised again and the port is closed. This makes good use of the inner exception mechanism since a generic "Receive Thread Fault" is raised, containing a reference to the original stored exception. ThrowException is provided as a helper method for use in derived classes; it adjusts its behavior according to which thread it is called on.

Settings and Other Details
 I read all the configurable settings from a helper object of class CommBaseSettings. Open acquires this object by calling the virtual method CommSettings and then copies the values into the API structures. CommBaseSettings also provides methods for saving and restoring settings to XML configuration files and for applying common settings scenarios in bulk. I provide documentation for the settings in the form of IntelliSense help. This design provides an extensible settings infrastructure since derived classes can provide their own settings class that inherits from CommBaseSettings. I have inherited CommLineSettings in this way to add additional settings required by CommLine.
There are three API functions for configuring communications protocols: SetupComm, SetCommState, and SetCommTimeouts. SetupComm requests sizes for the reception and transmission queues. Normally you can just set these to zero and the operating system decides, but it may be worth adjusting the requested size for some file transfer and similar applications. There is no guarantee that the system will honor this request; in Windows XP, there appears to be a dynamic transmission queue and only the reception queue length is honored.
SetCommState supplies the settings for baud rate, word format, and handshake settings in a structure called the device control block (DCB).
SetCommTimeouts provides three reception and two transmission timeout values in a COMMTIMEOUTS structure. The reception timeouts are not useful in the design I have chosen because individual characters are processed asynchronously. If a reception timeout is required, then it needs to be implemented at a higher level (for example, CommLine provides a timeout for its Transact method). The transmission timeouts are useful, however, for multibyte sends. The number of bytes in the send is multiplied by the sendTimeoutMultiplier and then sendTimeoutConstant is added to this to give the total time allowed in milliseconds.
Once the port is opened and configured, Open invokes a virtual method AfterOpen, which may be overridden to check the status of the connection to the remote device and possibly also to configure it. If this returns false, the port will be closed again and Open itself will return false. There is also a BeforeClose method for shutting down the remote device if necessary.
CommBase provides two overloaded versions of Send, one taking a byte array and the other taking a single byte. CommLine provides a third version of Send, taking a string. All of these ultimately use the byte array version after appropriate data conversion. There is also a SendImmediate method taking a single byte. This sends the byte ahead of any other bytes in the transmission queue and may be useful for implementing custom flow control schemes. There are also properties providing direct control of the Request to Send (RTS) and Data Terminal Ready (DTR) output pins and the ability to put the TX output into a break condition. The input pins—Clear-to-Send (CTS), Data Set Ready (DSR), Received Line Signal Detector (RLSD), and Ring Detect—can be read directly using GetModemStatus and the virtual function OnStatusChange is called when the state of any of these input and output pins changes.
GetQueueStatus returns a QueueStatus object, giving the size and content of the transmission and reception queues and what, if any, flow control condition is currently blocking transmission.

Conclusion
 I've used Platform Invocation Services to address one of the gaps in the functionality of the FCL. This turned out to be a nontrivial but perfectly feasible exercise. Much of the difficulty arises because full tool support and documentation for P/Invoke is not yet in place.
Finally, I have a confession to make. As part of this project, I wrote and tested a complete wrapper for the Win32 Waitable Events API before stumbling on the ManualResetEvent and AutoResetEvent framework classes that already encapsulated all the functionality I needed. Remember: you just might be spending all your free time writing brand new classes from scratch when just what you needed already existed. Check your local hardware store before reinventing the wheel. On this principle, I hope that the base classes developed here will help other programmers bring RS232 device communications into the .NET world.
For related articles see:
 House of COM: ating Native Code to the .NET CLR
Serial Communications Overview
RS232 standard


使用 C# .NET 撰寫事件記錄檔
底下連結的文章示範如何使用 Microsoft .NET Framework 將您自己的項目加入到作業系統的事件記錄檔。
http://support.microsoft.com/default.aspx?scid=kb;EN-US;307024


XML 和 Data Grid (資料瀏覽)
employees.xml 內容如下：
<?xml version="1.0" encoding="utf-8"?>
<fullrecord>
  <employee>
    <firstname>Sylvie</firstname>
    <lastname>Aronson</lastname>
    <salary>25.64</salary>
    <gender>Female</gender>
  </employee>
  <employee>
    <firstname>Bertrand</firstname>
    <lastname>Yamaguchi</lastname>
    <salary>16.38</salary>
    <gender>Male</gender>
  </employee>
    <firstname>Anselme</firstname>
    <lastname>Bean</lastname>
    <salary>22.82</salary>
    <gender>Male</gender>
  <employee>
    <firstname>Mauricette</firstname>
    <lastname>Thomas</lastname>
    <salary>18.35</salary>
    <gender>Female</gender>
  </employee>
  <employee>
    <firstname>Hermine</firstname>
    <lastname>Gray</lastname>
    <salary>12.75</salary>
    <gender>Female</gender>
  </employee>
</fullrecord>

程式內容：

/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/9
 * 建立時間: 上午 10:40
 * 功    能:
 * 修改日期: 2004/8/9 上午 10:40
 */
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace IntroXML1
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.DataGrid dataGrid1;
        private DataSet dsEmployees;
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }

        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new MainForm());
        }

        #region Windows Forms Designer generated code
        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent() {
            this.dataGrid1 = new System.Windows.Forms.DataGrid();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
            this.SuspendLayout();
            //
            // dataGrid1
            //
            this.dataGrid1.DataMember = "";
            this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid1.Location = new System.Drawing.Point(8, 8);
            this.dataGrid1.Name = "dataGrid1";
            this.dataGrid1.Size = new System.Drawing.Size(440, 208);
            this.dataGrid1.TabIndex = 0;
            //
            // MainForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
            this.ClientSize = new System.Drawing.Size(456, 230);
            this.Controls.Add(this.dataGrid1);
            this.Name = "MainForm";
            this.Text = "MainForm";
            this.Load += new System.EventHandler(this.MainFormLoad);
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
            this.ResumeLayout(false);
        }
        #endregion
        void MainFormLoad(object sender, System.EventArgs e)
        {
            this.dsEmployees = new DataSet("employees");
            this.dsEmployees.ReadXml("employees.xml");
            this.dataGrid1.DataSource = this.dsEmployees;
            this.dataGrid1.DataMember = "employee";
        }

    }
}


XML 和 comboBox (新增資料到comboBox ，並存到XML檔中)
ISFlavors.xml 檔內容：

<?xml version="1.0" encoding="utf-8"?>
<flavors>
  <flavor>French Vanilla</flavor>
</flavors>

完整程式碼：

/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/9
 * 建立時間: 上午 11:05
 * 功    能:
 * 修改日期: 2004/8/9 上午 11:05
 */
using System;
using System.Windows.Forms;
using System.Xml;
using System.Text;

namespace DefaultNamespace
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.ComboBox comboBox1;
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }

        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new MainForm());
        }

        #region Windows Forms Designer generated code
        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent() {
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // comboBox1
            //
            this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBox1.Location = new System.Drawing.Point(16, 40);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(120, 20);
            this.comboBox1.Sorted = true;
            this.comboBox1.TabIndex = 0;
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(240, 40);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(104, 22);
            this.textBox1.TabIndex = 2;
            this.textBox1.Text = "textBox1";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(144, 40);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(88, 24);
            this.button1.TabIndex = 1;
            this.button1.Text = "新增";
            this.button1.Click += new System.EventHandler(this.Button1Click);
            //
            // MainForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
            this.ClientSize = new System.Drawing.Size(368, 134);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.comboBox1);
            this.Name = "MainForm";
            this.Text = "MainForm";
            this.Closing += new System.ComponentModel.CancelEventHandler(this.MainFormClosing);
            this.Load += new System.EventHandler(this.MainFormLoad);
            this.ResumeLayout(false);
        }
        #endregion
        void Button1Click(object sender, System.EventArgs e)
        {
            string NewItem = this.textBox1.Text;

            // If there is no flavor to add, do nothing
            if( NewItem.Equals("") == true )
                return;

            // Since there is an item to add, prepare to add it
            // First make sure the item is not already in the list
            if( this.comboBox1.FindStringExact(NewItem) > 0 )
            {
                MessageBox.Show(NewItem + " exists already in the list and will not be added.");
                return;
            }

            // Since the item is not yet in the list, add it...
            this.comboBox1.Items.Add(NewItem);
            // After adding the item to the combo box, remove it from the text box
            this.textBox1.Text = "";
            // And give focus to the text box in case the user wants to add another item
            this.textBox1.Focus();
        }

        void MainFormLoad(object sender, System.EventArgs e)
        {
             // Declare a variable of type  XmlTextReader
             XmlTextReader xtr  = null;
             // Declare a string that holds the name of the file
             string fileName = "ISFlavors.xml";

             try {
                 // Initialize the XmlTextReader variable with the name of the file
                 xtr = new XmlTextReader(fileName);
                 xtr.WhitespaceHandling = WhitespaceHandling.None;

                 // Scan the XML file
                 while (xtr.Read())
                 {
                   // every time you find an element, find out what type it is
                   switch (xtr.NodeType)
                   {
                    case XmlNodeType.Text:
                    // If you find text, put it in the combo box' list
                    this.comboBox1.Items.Add(xtr.Value);
                    break;
                   }
                 }

                 // For this example, select the first item
                 this.comboBox1.SelectedIndex = 0;
             }
             finally
             {
                 // Close the XmlTextReader
                 if (xtr != null)
                      xtr.Close();
             }
        }

        void MainFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            XmlTextWriter xtw = null;
            string fileName   = "ISFlavors.xml";

             try {
                 xtw = new XmlTextWriter(fileName, Encoding.UTF8);
                 xtw.Formatting = Formatting.Indented;

                 xtw.WriteStartDocument();
                 xtw.WriteStartElement("flavors");

                 for(int i = 0; i < this.comboBox1.Items.Count; i++)
                 {
                   xtw.WriteElementString("flavor", (string)this.comboBox1.Items[i]);
                 }

                 xtw.WriteEndElement();
                 xtw.WriteEndDocument();
             }
             finally
             {
                 if (xtw != null)
                   xtw.Close();
             }

        }

    }
}


TreeView

讀取 XML 檔，設定 TreeView

http://www.hkln.net/doc/csharp/eg/controls.htm

本節示範讀取一個 OPML 檔案，然後跟據內容設定 TreeView 的架構和文字。OPML 是 XML 的一種應用，主要用來表示樹形的結構，詳情請參考 http://www.opml.org/。

以下是一個 OPML 檔的例子：

<?xml version="1.0"?>
<opml version="1.0">
<head>
<title>OPML sample</title>
</head>

<body>
<outline text="n0">
 <outline text="n0.0"/>
</outline>
<outline text="n1">
 <outline text="n1.0"/>
 <outline text="n1.1">
  <outline text="n1.1.0"/>
 </outline>
</outline>
</body>
</opml>

它的樹形結構如下：

假設這個檔案儲存在 C:\opml.xml，您可以用以下程式讀取它：

System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load("c:/opml.xml");
populateTreeControl(xd.SelectSingleNode("//opml/body"), tvNav.Nodes);

其中的 populateTreeControl 是個函數，內容如下：

private void populateTreeControl(
    System.Xml.XmlNode document,
    System.Windows.Forms.TreeNodeCollection nodes)
{
    foreach (System.Xml.XmlNode node in document.SelectNodes("outline"))
    {
        string text = node.Attributes["text"].Value;
        TreeNode new_child = new TreeNode(text);
        nodes.Add(new_child);
        populateTreeControl(node, new_child.Nodes);
    }
}

它透過遞迴來依照 XML 結構設定 TreeView。

由子到父

當按下 TreeView 上某一點，就顯示它的所有父點：

protected void tv_NodeMouseClick(object sender, System.EventArgs e)
{
    TreeNode tn = tv.SelectedNode.Parent;
    while (tn != null)
    {
        MessageBox.Show(tn.FullPath);
        tn = tn.Parent;
    }
}

由父到子

當按下 TreeView 上某一點，就顯示它的所有子點：

protected void tv_NodeMouseClick(object sender, System.EventArgs e)
{
    iterateChildNodes(tv.SelectedNode);
}

private void iterateChildNodes(TreeNode tn)
{
    foreach (TreeNode tnChild in tn.Nodes)
    {
        MessageBox.Show(tnChild.FullPath);
        if (tnChild.Nodes.Count != 0)  iterateChildNodes(tnChild);
    }
}

用程式加入控制項

using System;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
    static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        TextBox tb = new TextBox();
        tb.Left = 10;
        tb.Top = 20;
        this.Controls.Add(tb);
    }
}

設定控制項的事件處理者

加入兩個 TextBox 控制項，把它們設定使用同一個事件處理者，當焦點進入 TextBox 時，就顯示它的內容：

using System;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
    static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        TextBox tb;

        tb = new TextBox();
        tb.Left = 20;	tb.Top = 20;
        tb.Name = "Name";	tb.Text = "Tom";
        tb.Enter += new EventHandler(tb_Enter);

        this.Controls.Add(tb);

        tb = new TextBox();
        tb.Left = 20;	tb.Top = 50;
        tb.Name = "Age";	tb.Text = "18";
        tb.Enter += new EventHandler(tb_Enter);

        this.Controls.Add(tb);
    }

    private void tb_Enter(Object sender, System.EventArgs e)
    {
        TextBox tn;
        tn = (TextBox)sender;
        MessageBox.Show(tn.Text);
    }
}


客戶端執行 Office 應用程式使用後，沒有消失離開處理
當你從Visual Basic .NET or Visual C# .NET 自動化呼叫任一個 Microsoft Office application，即使我們呼叫了 Quit 這一個方法，Office 應用程式並沒有消失離開，請參考底下連結的說明文件。

PRB: Office Application Does Not Quit After Automation from Visual Studio .NET Client
 http://support.microsoft.com/?id=317109


簡單C#與EXCEL整合的應用程式
1.轉OLB檔為NET使用的DLL檔
    TlbImp.exe  excel.olb excel.dll

Type Library Importer (Tlbimp.exe)使用說明：

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpgrftypelibraryimportertlbimpexe.asp

2.開發工具->加入「參考」
3.程式碼如下：
using System;
using System.Windows.Forms;
using System.Reflection; // For Missing.Value and BindingFlags
using System.Runtime.InteropServices; // For COMException
using Excel;

namespace MyFormProject
{

 class MainForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button;
  private System.Windows.Forms.Button button2;
  public static int Excel1()
{
Excel.Application exc = new
Excel.Application();
exc.Visible = true;
Workbooks workbooks = exc.Workbooks;
_Workbook workbook =
workbooks.Add(XlWBATemplate.xlWBATWorksheet);
//Sheets sheets =
workbook.Worksheets;
return
0;
}
public MainForm()
{
InitializeComponent();
}
// THIS
METHOD IS MAINTAINED BY THE FORM DESIGNER
// DO NOT EDIT IT
MANUALLY! YOUR CHANGES ARE LIKELY TO BE LOST
void
InitializeComponent() {
this.button2 = new
System.Windows.Forms.Button();
this.button = new
System.Windows.Forms.Button();
this.SuspendLayout();
//
//
button2
//
this.button2.Location = new
System.Drawing.Point(24, 56);
this.button2.Name =
"button2";
this.button2.TabIndex = 1;
this.button2.Text = "結束程式";
this.button2.Click += new
System.EventHandler(this.Button2Click);
//
//
button
//
this.button.Location = new
System.Drawing.Point(24, 24);
this.button.Name =
"button";
this.button.TabIndex = 0;
this.button.Text = "開啟Excel程式";
this.button.Click += new
System.EventHandler(this.ButtonClick);
//
//
MainForm
//
this.AutoScaleBaseSize = new
System.Drawing.Size(5, 15);
this.ClientSize = new
System.Drawing.Size(292, 273);
this.Controls.Add(this.button2);
this.Controls.Add(this.button);
this.Name =
"MainForm";
this.Text = "This is my form";
this.ResumeLayout(false);
}

  [STAThread]
  public static void Main(string[] args)
  {
   System.Windows.Forms.Application.Run(new MainForm());
   //Important because Excel is an Application too:
   // without System.Windows.Forms ambiguous reference error
  }
void Button2Click(object sender,
System.EventArgs e)
{
this.Close();
}
void ButtonClick(object sender,
System.EventArgs e)
{
Excel1();
}
}
}


C#填資料到 EXCEL中
透過自動化 Excel 的方式，使用陣列來填入或取出某一範圍中的資料
底下連結的文章示範了如何在 Visual C# .NET 中透過自動化Excel 的方式，使用陣列來填入或取出某一多欄位範圍中的資料。
 http://support.microsoft.com/?id=302096


透過 C# .NET來處理 Execl 觸發的事件
底下連結的文章逐步說明如何在Visual C# .NET 所開發的自動化客戶端上處理Excel 觸發的事件。
 http://support.microsoft.com/?id=302815


AxImp轉換COM 為NET視覺元件
(AxImp.exe:.NET framework SDK安裝後有提供！)
AxImp.exe使用方式：
Windows Forms ActiveX Control Importer (Aximp.exe)
 http://msdn.microsoft.com/library/en-us/cptools/html/cpgrfWindowsFormsActiveXControlImporterAximpexe.asp
批次檔執行範例
如下：
@echo 「AxImp轉換COM」為NET可視覺的元件製作
aximp c:\windows\system32\wmp.dll /out:Interop.wmp.dll
pause
完成後，可在工具面版按右鍵
-->選擇configuresidebar(引用項目設定)-->選擇存放元件分類位置-->新增元件-->自訂-->選擇Interop.wmp.dll-->確定
備註1：開發工具加入COM為「參考( References )」時，為NET非視覺元件使用方式。
備註2：引用 ActiveX 元件..兩種玩法 (AxImp.exe 和 註冊到GAC)


/*
* 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
* 作    者:
* 建立日期: 2004/8/25
* 建立時間: 下午 10:57
* 功    能: 收音機(轉換COM為.NET視覺化元件方式)
* 修改日期: 2004/8/25 下午 10:57
*/
using System;
using System.Windows.Forms;

namespace DefaultNamespace
{
/// <summary>
/// Description of MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBox1;
private mdobler.XPCommonControls.XPGradientPanel xPGradientPanel1;
private AxWMPLib.AxWindowsMediaPlayer axWindowsMediaPlayer1;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();

//
// TODO: Add constructor code after the InitializeComponent() call.
//
}

[STAThread]
public static void Main(string[] args)
{
Application.Run(new MainForm());
}

#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent() {
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.axWindowsMediaPlayer1 = new AxWMPLib.AxWindowsMediaPlayer();
this.xPGradientPanel1 = new mdobler.XPCommonControls.XPGradientPanel();
this.listBox1 = new System.Windows.Forms.ListBox();
((System.ComponentModel.ISupportInitialize)(this.axWindowsMediaPlayer1)).BeginInit();
this.xPGradientPanel1.SuspendLayout();
this.SuspendLayout();
//
// axWindowsMediaPlayer1
//
this.axWindowsMediaPlayer1.ContainingControl = this;
this.axWindowsMediaPlayer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axWindowsMediaPlayer1.Enabled = true;
this.axWindowsMediaPlayer1.Location = new System.Drawing.Point(216, 0);
this.axWindowsMediaPlayer1.Name = "axWindowsMediaPlayer1";
this.axWindowsMediaPlayer1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWindowsMediaPlayer1.OcxState")));
this.axWindowsMediaPlayer1.Size = new System.Drawing.Size(336, 246);
this.axWindowsMediaPlayer1.TabIndex = 0;
 //
// xPGradientPanel1
//
this.xPGradientPanel1.Controls.Add(this.axWindowsMediaPlayer1);
this.xPGradientPanel1.Controls.Add(this.listBox1);
this.xPGradientPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.xPGradientPanel1.Location = new System.Drawing.Point(0, 0);
this.xPGradientPanel1.Name = "xPGradientPanel1";
this.xPGradientPanel1.Size = new System.Drawing.Size(552, 246);
this.xPGradientPanel1.TabIndex = 1;
//
// listBox1
//
this.listBox1.Dock = System.Windows.Forms.DockStyle.Left;
this.listBox1.ItemHeight = 12;
this.listBox1.Items.AddRange(new object[] {
"mms://live.media.hinet.net/UFO_Music1 ",
"mms://live.media.hinet.net/kissradio ",
"mms://live.media.hinet.net/vot "});
this.listBox1.Location = new System.Drawing.Point(0, 0);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(216, 244);
this.listBox1.TabIndex = 1;
this.listBox1.Click += new System.EventHandler(this.listBox1Click);
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
this.ClientSize = new System.Drawing.Size(552, 246);
this.Controls.Add(this.xPGradientPanel1);
this.Name = "MainForm";
this.Text = "MainForm";
((System.ComponentModel.ISupportInitialize)(this.axWindowsMediaPlayer1)).EndInit();
this.xPGradientPanel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion

void listBox1Click(object sender, System.EventArgs e)
{
axWindowsMediaPlayer1.URL=listBox1.SelectedItem.ToString();
}
}
}


Windows MediaPlayer操作範例-收音機製作
(Windows MediaPlayer採用非視覺方式製作-加入「參考」方式)
程式碼如下：
/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/25
 * 建立時間: 下午 08:05
 * 功    能:
 * 修改日期: 2004/8/25 下午 08:05
 */
using System;
using System.Windows.Forms;
using System.ComponentModel;
using WMPLib;
namespace DefaultNamespace
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public class MainForm : System.Windows.Forms.Form
 {
  private ColorButton.ColorButton colorButton2;
  private ColorButton.ColorButton colorButton1;
  private System.Windows.Forms.ListBox listBox1;
  private WMPLib.WindowsMediaPlayer Paly=new WindowsMediaPlayer();
  private System.ComponentModel.Container components = null;

  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();

   //
   // TODO: Add constructor code after the InitializeComponent() call.
   //
  }

  [STAThread]
  public static void Main(string[] args)
  {
   Application.Run(new MainForm());
  }
  /// <summary>
  /// 元件記憶體釋放
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
     if (components != null)
     {
      components.Dispose();
     }
   }
   base.Dispose( disposing );
  }

  #region Windows Forms Designer generated code
  /// <summary>
  /// This method is required for Windows Forms designer support.
  /// Do not change the method contents inside the source code editor. The Forms designer might
  /// not be able to load this method if it was changed manually.
  /// </summary>
  private void InitializeComponent() {
   this.listBox1 = new System.Windows.Forms.ListBox();
   this.colorButton1 = new ColorButton.ColorButton();
   this.colorButton2 = new ColorButton.ColorButton();
   this.SuspendLayout();
   //
   // listBox1
   //
   this.listBox1.ItemHeight = 12;
   this.listBox1.Items.AddRange(new object[] {
      "mms://live.media.hinet.net/UFO_Music1",
      "mms://live.media.hinet.net/kissradio ",
      "mms://live.media.hinet.net/vot "});
   this.listBox1.Location = new System.Drawing.Point(8, 8);
   this.listBox1.Name = "listBox1";
   this.listBox1.Size = new System.Drawing.Size(272, 64);
   this.listBox1.TabIndex = 1;
   this.listBox1.Click += new System.EventHandler(this.listBox1Click);
   //
   // colorButton1
   //
   this.colorButton1.Active = true;
   this.colorButton1.ButtonStyle = ColorButton.ColorButton.ButtonStyles.Rectangle;
   this.colorButton1.Font = new System.Drawing.Font("Verdana", 10F, System.Drawing.FontStyle.Bold);
   this.colorButton1.GradientStyle = ColorButton.ColorButton.GradientStyles.Vertical;
   this.colorButton1.HoverBorderColor = System.Drawing.Color.MediumVioletRed;
   this.colorButton1.HoverColorA = System.Drawing.Color.MediumVioletRed;
   this.colorButton1.HoverColorB = System.Drawing.Color.White;
   this.colorButton1.Location = new System.Drawing.Point(8, 80);
   this.colorButton1.Name = "colorButton1";
   this.colorButton1.NormalBorderColor = System.Drawing.Color.Green;
   this.colorButton1.NormalColorA = System.Drawing.Color.Green;
   this.colorButton1.NormalColorB = System.Drawing.Color.Honeydew;
   this.colorButton1.Size = new System.Drawing.Size(64, 32);
   this.colorButton1.SmoothingQuality = ColorButton.ColorButton.SmoothingQualities.AntiAlias;
   this.colorButton1.TabIndex = 2;
   this.colorButton1.Text = "播放";
   this.colorButton1.Click += new System.EventHandler(this.ColorButton1Click);
   //
   // colorButton2
   //
   this.colorButton2.Active = true;
   this.colorButton2.ButtonStyle = ColorButton.ColorButton.ButtonStyles.Rectangle;
   this.colorButton2.Font = new System.Drawing.Font("Verdana", 10F, System.Drawing.FontStyle.Bold);
   this.colorButton2.GradientStyle = ColorButton.ColorButton.GradientStyles.Vertical;
   this.colorButton2.HoverBorderColor = System.Drawing.Color.MediumVioletRed;
   this.colorButton2.HoverColorA = System.Drawing.Color.MediumVioletRed;
   this.colorButton2.HoverColorB = System.Drawing.Color.White;
   this.colorButton2.Location = new System.Drawing.Point(80, 80);
   this.colorButton2.Name = "colorButton2";
   this.colorButton2.NormalBorderColor = System.Drawing.Color.Green;
   this.colorButton2.NormalColorA = System.Drawing.Color.Green;
   this.colorButton2.NormalColorB = System.Drawing.Color.Honeydew;
   this.colorButton2.Size = new System.Drawing.Size(64, 32);
   this.colorButton2.SmoothingQuality = ColorButton.ColorButton.SmoothingQualities.AntiAlias;
   this.colorButton2.TabIndex = 3;
   this.colorButton2.Text = "停止";
   this.colorButton2.Click += new System.EventHandler(this.ColorButton2Click);
   //
   // MainForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
   this.ClientSize = new System.Drawing.Size(296, 126);
   this.Controls.Add(this.colorButton2);
   this.Controls.Add(this.colorButton1);
   this.Controls.Add(this.listBox1);
   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
   this.MaximizeBox = false;
   this.Name = "MainForm";
   this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   this.Text = "簡易收音機";
   this.ResumeLayout(false);
  }
  #endregion

  void listBox1Click(object sender, System.EventArgs e)
  {
    Paly.URL=listBox1.SelectedItem.ToString();
  }

  void ColorButton1Click(object sender, System.EventArgs e)
  {
      if (listBox1.SelectedItem.ToString().Length>0)
   {
    Paly.controls.play();
   }
  }

  void ColorButton2Click(object sender, System.EventArgs e)
  {
   Paly.controls.stop();
  }

 }
}


繁簡轉換 COM 元件取得與註冊：
1.下載Hokoy.WordKit.dll檔，並註冊，才能執行本程式：
 http://www.hokoy.com/Works/Program/HokoyWordKit.aspx
2.拷貝Hokoy.WordKit.dll到c:\windows\system32資料夾
3.註冊 RegSvr32 Hokoy.WordKit.dll
4.專案加入「參考」->「COM」書籤->選擇「Hokoy Library」->確定

程式碼如下：
/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者:
 * 建立日期: 2004/8/15
 * 建立時間: 上午 11:49
 * 功    能:
 * 修改日期: 2004/8/15 上午 11:49
 */
using System;
using System.Windows.Forms;
using Hokoy;
namespace DefaultNamespace
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        private mdobler.XPCommonControls.XPGradientPanel xPGradientPanel1;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button button12;
        private System.Windows.Forms.Button button7;
        private System.Windows.Forms.Button button6;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.MenuItem menuItem3;
        private System.Windows.Forms.MenuItem menuItem2;
        private System.Windows.Forms.MenuItem menuItem1;
        private System.Windows.Forms.Button button8;
        private System.Windows.Forms.Button button11;
        private System.Windows.Forms.MenuItem menuItem5;
        private System.Windows.Forms.MenuItem menuItem4;
        private System.Windows.Forms.Button button10;
        private System.Windows.Forms.ContextMenu contextMenu1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.CheckBox checkBox1;
        private System.Windows.Forms.RichTextBox richTextBox2;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button9;
        private Hokoy.WordKitClass source;
        private System.Object OK;
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }

        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new MainForm());
        }

        #region Windows Forms Designer generated code
        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent() {
            this.source =new WordKitClass();
            this.OK =new Object();
            this.button9 = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.contextMenu1 = new System.Windows.Forms.ContextMenu();
            this.button10 = new System.Windows.Forms.Button();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.menuItem5 = new System.Windows.Forms.MenuItem();
            this.button11 = new System.Windows.Forms.Button();
            this.button8 = new System.Windows.Forms.Button();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.button6 = new System.Windows.Forms.Button();
            this.button7 = new System.Windows.Forms.Button();
            this.button12 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.xPGradientPanel1 = new mdobler.XPCommonControls.XPGradientPanel();
            this.SuspendLayout();
            //
            // button9
            //
            this.button9.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button9.Location = new System.Drawing.Point(464, 184);
            this.button9.Name = "button9";
            this.button9.Size = new System.Drawing.Size(184, 24);
            this.button9.TabIndex = 12;
            this.button9.Text = "繁體->Unicode";
            this.button9.Click += new System.EventHandler(this.Button9Click);
            //
            // button1
            //
            this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button1.Location = new System.Drawing.Point(464, 24);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(184, 24);
            this.button1.TabIndex = 1;
            this.button1.Text = "繁體->簡體";
            this.button1.Click += new System.EventHandler(this.Button1Click);
            //
            // richTextBox2
            //
            this.richTextBox2.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(192)));
            this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.richTextBox2.Font = new System.Drawing.Font("新細明體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(136)));
            this.richTextBox2.ForeColor = System.Drawing.Color.Navy;
            this.richTextBox2.Location = new System.Drawing.Point(8, 193);
            this.richTextBox2.Name = "richTextBox2";
            this.richTextBox2.Size = new System.Drawing.Size(448, 151);
            this.richTextBox2.TabIndex = 2;
            this.richTextBox2.Text = "";
            //
            // checkBox1
            //
            this.checkBox1.Appearance = System.Windows.Forms.Appearance.Button;
            this.checkBox1.Checked = true;
            this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
            this.checkBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.checkBox1.Font = new System.Drawing.Font("新細明體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
            this.checkBox1.ForeColor = System.Drawing.Color.Blue;
            this.checkBox1.Location = new System.Drawing.Point(464, 280);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(56, 24);
            this.checkBox1.TabIndex = 16;
            this.checkBox1.Text = "自動換行";
            this.checkBox1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.checkBox1.CheckedChanged += new System.EventHandler(this.CheckBox1CheckedChanged);
            //
            // richTextBox1
            //
            this.richTextBox1.ContextMenu = this.contextMenu1;
            this.richTextBox1.Font = new System.Drawing.Font("新細明體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(136)));
            this.richTextBox1.Location = new System.Drawing.Point(8, 24);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(448, 144);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label1.Font = new System.Drawing.Font("新細明體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(136)));
            this.label1.Location = new System.Drawing.Point(8, 2);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(34, 22);
            this.label1.TabIndex = 3;
            this.label1.Text = "來源";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label2.Font = new System.Drawing.Font("新細明體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(136)));
            this.label2.Location = new System.Drawing.Point(8, 170);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(60, 22);
            this.label2.TabIndex = 4;
            this.label2.Text = "轉換結果";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // contextMenu1
            //
            this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                        this.menuItem1,
                        this.menuItem2,
                        this.menuItem3,
                        this.menuItem4,
                        this.menuItem5});
            //
            // button10
            //
            this.button10.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button10.Location = new System.Drawing.Point(464, 216);
            this.button10.Name = "button10";
            this.button10.Size = new System.Drawing.Size(184, 24);
            this.button10.TabIndex = 13;
            this.button10.Text = "Unicode->簡體";
            this.button10.Click += new System.EventHandler(this.Button10Click);
            //
            // menuItem4
            //
            this.menuItem4.Index = 3;
            this.menuItem4.Text = "-";
            //
            // menuItem5
            //
            this.menuItem5.Index = 4;
            this.menuItem5.Text = "全      選";
            this.menuItem5.Click += new System.EventHandler(this.MenuItem5Click);
            //
            // button11
            //
            this.button11.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button11.Location = new System.Drawing.Point(464, 248);
            this.button11.Name = "button11";
            this.button11.Size = new System.Drawing.Size(184, 24);
            this.button11.TabIndex = 14;
            this.button11.Text = "Unicode->繁體";
            this.button11.Click += new System.EventHandler(this.Button11Click);
            //
            // button8
            //
            this.button8.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button8.Location = new System.Drawing.Point(464, 152);
            this.button8.Name = "button8";
            this.button8.Size = new System.Drawing.Size(184, 24);
            this.button8.TabIndex = 11;
            this.button8.Text = "簡體->Unicode";
            this.button8.Click += new System.EventHandler(this.Button8Click);
            //
            // menuItem1
            //
            this.menuItem1.Index = 0;
            this.menuItem1.Text = "剪      下";
            this.menuItem1.Click += new System.EventHandler(this.MenuItem1Click);
            //
            // menuItem2
            //
            this.menuItem2.Index = 1;
            this.menuItem2.Text = "複      製";
            this.menuItem2.Click += new System.EventHandler(this.MenuItem2Click);
            //
            // menuItem3
            //
            this.menuItem3.Index = 2;
            this.menuItem3.Text = "貼      上";
            this.menuItem3.Click += new System.EventHandler(this.MenuItem3Click);
            //
            // button4
            //
            this.button4.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button4.Location = new System.Drawing.Point(464, 120);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(184, 24);
            this.button4.TabIndex = 7;
            this.button4.Text = "Unicode繁體字->Unicode簡體字";
            this.button4.Click += new System.EventHandler(this.Button4Click);
            //
            // button5
            //
            this.button5.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button5.Location = new System.Drawing.Point(560, 296);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(88, 48);
            this.button5.TabIndex = 8;
            this.button5.Text = "複製結果";
            this.button5.Click += new System.EventHandler(this.Button5Click);
            //
            // button6
            //
            this.button6.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button6.Location = new System.Drawing.Point(120, 168);
            this.button6.Name = "button6";
            this.button6.Size = new System.Drawing.Size(248, 24);
            this.button6.TabIndex = 9;
            this.button6.Text = "上下互換";
            this.button6.Click += new System.EventHandler(this.Button6Click);
            //
            // button7
            //
            this.button7.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button7.Location = new System.Drawing.Point(352, 0);
            this.button7.Name = "button7";
            this.button7.Size = new System.Drawing.Size(104, 24);
            this.button7.TabIndex = 10;
            this.button7.Text = "來源內容清空";
            this.button7.Click += new System.EventHandler(this.Button7Click);
            //
            // button12
            //
            this.button12.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button12.Location = new System.Drawing.Point(232, 0);
            this.button12.Name = "button12";
            this.button12.Size = new System.Drawing.Size(112, 24);
            this.button12.TabIndex = 15;
            this.button12.Text = "從剪貼簿貼上";
            this.button12.Click += new System.EventHandler(this.Button12Click);
            //
            // button2
            //
            this.button2.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button2.Location = new System.Drawing.Point(464, 56);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(184, 24);
            this.button2.TabIndex = 5;
            this.button2.Text = "簡體->繁體";
            this.button2.Click += new System.EventHandler(this.Button2Click);
            //
            // button3
            //
            this.button3.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button3.Location = new System.Drawing.Point(464, 88);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(184, 24);
            this.button3.TabIndex = 6;
            this.button3.Text = "Unicode簡體字->Unicode繁體字";
            this.button3.Click += new System.EventHandler(this.Button3Click);
            //
            // xPGradientPanel1
            //
            this.xPGradientPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.xPGradientPanel1.Location = new System.Drawing.Point(0, 0);
            this.xPGradientPanel1.Name = "xPGradientPanel1";
            this.xPGradientPanel1.Size = new System.Drawing.Size(656, 352);
            this.xPGradientPanel1.TabIndex = 17;
            //
            // MainForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
            this.ClientSize = new System.Drawing.Size(656, 352);
            this.Controls.Add(this.richTextBox2);
            this.Controls.Add(this.checkBox1);
            this.Controls.Add(this.button12);
            this.Controls.Add(this.button11);
            this.Controls.Add(this.button10);
            this.Controls.Add(this.button9);
            this.Controls.Add(this.button8);
            this.Controls.Add(this.button7);
            this.Controls.Add(this.button6);
            this.Controls.Add(this.button5);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.xPGradientPanel1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "MainForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "簡繁體轉換";
            this.ResumeLayout(false);
        }
        #endregion

        //繁體轉簡體
        void Button1Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.Big5toGB(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //簡體轉繁體
        void Button2Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.GBtoBig5(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //Unicode簡體字->Unicode繁體字
        void Button3Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.SCtoTC(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //Unicode繁體字->Unicode簡體字
        void Button4Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.TCtoSC(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //複製結果
        void Button5Click(object sender, System.EventArgs e)
        {
            richTextBox2.SelectAll();
            richTextBox2.Copy();
        }

        void MenuItem1Click(object sender, System.EventArgs e)
        {
            richTextBox1.Cut();
        }

        void MenuItem2Click(object sender, System.EventArgs e)
        {
            richTextBox1.Copy();
        }

        void MenuItem3Click(object sender, System.EventArgs e)
        {
            richTextBox1.Paste();
        }

        void MenuItem5Click(object sender, System.EventArgs e)
        {
            richTextBox1.SelectAll();
        }

        void Button7Click(object sender, System.EventArgs e)
        {
            richTextBox1.Clear();
        }

        void Button6Click(object sender, System.EventArgs e)
        {
            string tmp;
            tmp=richTextBox1.Text;
            richTextBox1.Text=richTextBox2.Text;
            richTextBox2.Text=tmp;
        }
        //簡體->Unicode
        void Button8Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.GBtoUnicode(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //繁體->Unicode
        void Button9Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.Big5toUnicode(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //Unicode->簡體
        void Button10Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.UnicodetoGB(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }
        //Unicode->繁體
        void Button11Click(object sender, System.EventArgs e)
        {
            if (richTextBox1.Text.Length>0)
            {
             OK=source.UnicodetoBig5(richTextBox1.Text);
             richTextBox2.Text =OK.ToString();
            }
        }

        void Button12Click(object sender, System.EventArgs e)
        {
         richTextBox1.Paste();
        }

        void CheckBox1CheckedChanged(object sender, System.EventArgs e)
        {
            if (checkBox1.Checked==true)
            {
             richTextBox1.WordWrap =true;
             richTextBox2.WordWrap =true;
             checkBox1.Text="自動換行";
            }else{
             richTextBox1.WordWrap =false;
             richTextBox2.WordWrap =false;
             checkBox1.Text="不換行";
            }
        }

    }
}


使用ADOX建立MDB資料庫
1.加入參考-->COM->選擇「Microsoft ADO Ext. 2.8 for DDL and Security 」
2.如下程式碼：

/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2004/8/28
 * Time: 下午 11:27
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;
using ADOX;
namespace DefaultNamespace
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }

        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new MainForm());
        }

        #region Windows Forms Designer generated code
        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent() {
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // saveFileDialog1
            //
            this.saveFileDialog1.DefaultExt = "*.mdb";
            this.saveFileDialog1.Filter = "MDB檔|*.mdb";
            this.saveFileDialog1.Title = "新增MDB檔";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(176, 136);
            this.button1.Name = "button1";
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.Click += new System.EventHandler(this.Button1Click);
            //
            // MainForm
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.button1);
            this.Name = "MainForm";
            this.Text = "MainForm";
            this.ResumeLayout(false);
        }
        #endregion
        void Button1Click(object sender, System.EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
             string MDBFilePath=saveFileDialog1.FileName;
                 ADOX.CatalogClass catNewMDB;
             catNewMDB = new ADOX.CatalogClass();
             catNewMDB.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MDBFilePath);
            }
        }

    }
}


用 C# 做類別元件
1.建立新類別檔：

   (1)檔案選單->建立新檔案->合併->選取C#類別(樹狀結構)->
   (2)選取右邊 Class Library-->設定專案名稱 myclass-->點選[建立]按鈕

2.新檔：myclass.cs

3.設定名稱空間(namespace)：(在其他專案使用此元件時，都與此有關)
   把namespace MyLibrary 改為 namespace myclass

4.新類別為myComponent ：
   public class myComponent //新類別(不可與名稱空間同名稱)
  {
  }

5.加入方法(method)：(加入返回值)
  public long Add (long val1, long val2) //方法
  {
    return val1 + val2;
  }
6.加入屬性：(包含get/set)

  private bool Test = false;
  public bool Extra //屬性
  {
    get
    {
     return Test;
    }
    set
    {
     Test = Extra;
    }
  }

7. 儲存專案
8. 編譯，在SharpDevelop Projects\myclass\bin\Debug資料夾產生myclass.dll檔
/*
 * 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
 * 作    者: 縱橫程式設計領域討論
 * 建立日期: 2004/8/7
 * 建立時間: 上午 12:04
 * 功    能: 用 C# 做元件
 * 修改日期: 2004/8/7 上午 12:04
 */
using System;
namespace myclass
{
 /// <summary>
 /// Description of myComponent.
 /// </summary>
 public class myComponent //新類別
 {
  public long Add (long val1, long val2) //方法
  {
    return val1 + val2;
  }

  private bool Test = false;
  public bool Extra //屬性
  {
    get
    {
     return Test;
    }
    set
    {
     Test = Extra;
    }
  }
 }
}


C# 自製類別元件DLL的使用
1.建立新專案：

   (1)檔案選單->建立新檔案->合併->選取C#類別(樹狀結構)

   (2)選取右邊 Console Application-->設定專案名稱 myclass_Test-->點選[建立]按鈕

2.新增引用檔：
  專案書籤->參考-->滑鼠右鍵-->新增參考-->選擇myclass.dll檔

3.設定名稱空間(namespace)：
   把namespace DefaultNamespace 改為 namespace myclass
4.如下程式碼：

/*
* 由 SharpDevelop .NET 免費開發工具 建立的 C# .NET 程式.
* 作    者:
* 建立日期: 2004/8/7
* 建立時間: 上午 01:25
* 功    能: C# 自製元件的使用
* 修改日期: 2004/8/7 上午 01:25
*/
using System;
using myclass;
namespace myclass
{
class MainClass
{
  public static void Main(string[] args)
  {
  myComponent mc = new myComponent(); //新建元件
   long ir=mc.Add(10,10);
   mc.Extra=false;
   Console.WriteLine(ir.ToString());   //答案 20
  }
}
}


Resourcer for .NET
Resourcer is an editor for .resources binaries and .resX XML file formats used with the .NET platform. The program allows the integration of bitmaps, icons and text strings into resource packages. Resourcer allows editing of name/string pairs, import of various kinds of data formats (bitmaps, icons, etc) and merging of resources from different sources.

Resourcer.zip - .NET Resourcer, Version 4.1.0.0
 http://www.aisto.com/roeder/dotnet/Download.aspx?File=Resourcer
另一套 Resource .NET 1.7 來至 http://www.tiantian.cn/dotnet/
http://www.tiantian.cn/dotnet/ResourceNet.zip
Resource Editor .NET(source code)
http://www.codeproject.com/cs/miscctrl/resource_editor.asp

  • Download source files - 23 Kb
  • Download demo project - 228 Kb

Sample Image - MainScreen.jpg


Reflector for .NET
Reflector is a class browser for .NET components. It supports assembly and namespace views, type and member search, XML documentation, call and callee graphs, IL, Visual Basic, Delphi and C# disassembler, dependency trees, base type and derived type hierarchies and resource viewers.

Reflector.zip - .NET Reflector, Version 4.0.17.0

 http://www.aisto.com/roeder/dotnet/Download.aspx?File=Reflector

建議使用此工具，不用＃D 內建的 Assembly scout 查詢 .Net FrameWork 內部函數，較易讓 #D 無反應狀態。
Anakrino
  • http://www.saurik.com/net/exemplar/
  • http://test.saurik.net/anakrino/


Java 語言轉換助理
Visual Studio .NET 整合了 JLCA (Java Language Conversion
Assistant，Java 語言轉換助理) 這套工具，可以幫助我們進行
Java-To-.NET 的轉換

請參考蔡學庸先生的專欄文章:
 http://www.microsoft.com/taiwan/msdn/columns/DoNet/jlca.htm

通通轉向c#語法...


其他輔助工具
Name | Link
CLR SPY | http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=C7B955C7-231A-406C-9FA5-AD09EF3BB37F
DUMPBIN | http://blogs.msdn.com/csano/archive/2004/04/19/116565.aspx
PINVOKE.NET Add-In for Visual Studio | http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=75122f62-5459-4364-b9ba-7b5e6a4754fe
SWIG C++->C# Interop Automation Tool | http://www.swig.org/


微軟 C# 手冊
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/CSharpSpecStart.asp


MSDN - ECMA Standardization
 http://msdn.microsoft.com/net/ecma/


Java vs C# 語法對照表
http://www.javacamp.org/javavscsharp/

http://www.25hoursaday.com/CsharpVsJava.html

java 與 c# 的 語法對照表 對已經會java 想學c# 應該是很有幫助的


.NET Framework 關係架構圖


Delphi型別與 C# 型別對照表
Delphi 型別 | C# 型別
ansistring | string
boolean | bool
byte | byte
char | char
comp | double
currency | double
double | double
extended | double
int64 | long
integer | int
longint | long
longword | long
olevariant | object
pchar | string
real | double
real48 | double
shortint | short
single | float
smallint | int
string | string
variant | object
widechar | string
widestring | string
word | short
textfile | System.IO.FileInfo
tdate | System.DateTime
tdatetime | System.DateTime
tfiletime | System.DateTime
hresult | long
pointer | object
file | System.IO.File
plongint | long
pinteger | int
pcardinal | double
pword | double
pdword | double
psmallint | short
pbyte | byte
pshortint | short
pint64 | long
plongword | long
psingle | float
pdouble | double
pdate | System.DateTime
pdispatch | object
ppdispatch | object
perror | object
pwordbool | bool
punknown | object
ppunknown | object
ppwidechar | string
ppchar | string
ppansichar | string
pansichar | string
pextended | double
pcomp | double
pcurrency | double
pvariant | object
polevariant | object
ppointer | object
pboolean | bool
pdatetime | System.DateTime
thandle | long
tresult | long
cardinal | double
tbytearray | byte[]
twordarray | int[]
dword | double
pstring | string
pwidestring | string
tsystemtime | System.DateTime
longbool | bool
wordbool | bool
hmodule | long
tlargeinteger | int
plargeinteger | int
uint | int
pwidechar | string
toleenum | long
pbytearray | byte[]
pwordarray | int[]
pansistring | string
ptextbuf | string


Delphi運算子與C#運算子對照表
Delphi | C#
* | *
/ | /
\ | /
Mod | %
Div | \
+ | +
- | -
< | <
<= | <=
> | >
>= | >=
<> | !=
= | ==
Not | !
Xor | ^
Shl | <<
Shr | >>
Or | ||
And | &&
In | (UNSUPPORT)
As | (type cast)
Is | is
@ | (UNSUPPORT)
^(pointer) | (UNSUPPORT)


Delphi statements to C#
Delphi | C# | Supported
library/package/unit/program | class | Yes
uses | using | Yes
interface/dispinterface | interface | Yes
initialization | public void initialization() | Yes
finalization | public void finalization() | Yes
const | const | Yes
resourcestring res = string | const string res = string | Yes
type |  | Yes
array of | [] | Yes
record ... end | struct | Yes
set ... of | enums | Yes
File ... of | System.IO.File | Yes
procedure/function | method | Yes
constructor/destructor | constructor/method | Yes
object ... end | class | Yes
public/protected/private/published | public | Yes
class of ... | object | Yes
class ... end | class | Yes
overload/virtual/dynamic/message/export/deprecated |  | Yes
property | class's property | Yes
:= | = | Yes
do while for repeat | do while for | Yes
if ... then ... else ... | if ... else ... | Yes
case ... of ... | switch ... | Yes
with |  | Yes
try ... except ... finally | try ... catch... | Yes
Raise | throw | Yes
asm ... end |  | No
requires |  | No
contains |  | No
exports |  | No
resident |  | No
inline |  | No
inherited |  | No
case ... of |  | No
function/procedure IDENTIFIER = IDENTIFIER; |  | No
Conditional Compiler Statement($IFDEF $ELSE $ENDIF}) | #if #else #endif | No


Classses Routines
Delphi | C# | Supported
activateclassgroup |  | No
allocatehwnd |  | No
bintohex |  | No
checksynchronize |  | No
collectionsequal |  | No
countgenerations |  | No
createvclcomobjectproc |  | No
currentgroup |  | No
deallocatehwnd |  | No
equalrect | == | Yes
extractstrings |  | No
findclass |  | No
findglobalcomponent |  | No
getclass |  | No
groupdescendantswith |  | No
hextobin |  | No
identtoint |  | No
initinheritedcomponent |  | No
inttoident |  | No
invalidpoint |  | No
isuniqueglobalcomponentname |  | No
linestart |  | No
objectbinarytotext |  | No
objectresourcetotext |  | No
objecttexttobinary |  | No
objecttexttoresource |  | No
point | new System.Drawing.Point | Yes
pointsequal | == | Yes
readcomponentres |  | No
readcomponentresex |  | No
readcomponentresfile |  | No
rect | new System.Drawing.Rectangle | Yes
registerclass |  | No
registerclassalias |  | No
registerclasses |  | No
registercomponents |  | No
registerintegerconsts |  | No
registernoicon |  | No
registernonactivex |  | No
smallpoint | new System.Drawing.Point | Yes
startclassgroup |  | No
teststreamformat |  | No
unregisterclass |  | No
unregisterclasses |  | No
unregisterintegerconsts |  | No
unregistermoduleclasses |  | No
wakemainthread |  | No
writecomponentresfile |  | No


Delphi Routines

  • Classes Routines
  • System Routines
  • SysUtils Routines
  • DateUtils Routines
  • Forms Routines
  • StrUtils Routines
  • Math Routines
  • Types Routines
  • Windows Routines
  • Variant Routines
http://www.netcoole.com/delphi2cs/Delphi2CSfeatures.htm


實例講解.NET中資源檔案的創建與使用

一、資源檔案

資源檔案顧名思義就是存放資源的檔案。資源檔案在程式設計中有著自身獨特的優勢，他獨立於源程式，這樣資源檔案就可以被多個程式使用。同時在程式設計的時候，有時出於安全或者其他方面因素的考慮，把重要東西存放在資源檔案中，也可以達到保密、安全的效果。那麼Visual C#所使用的資源檔案中到底存放哪些東西呢？在用Visual C#創建資源檔案大致可以存放三種類型的資料資源，分別是位元組陣列、各種物件和字串。本文將結合一個程式例子來具體說明用Visual C#是如何創建資源檔案的。

二、創建資源檔案所用的類

在.Net FrameWork SDK中的一個名字叫System.Resources名稱空間，在此名稱空間中為應用程式提供了許多創建、存儲和使用資源檔案的類和介面。其中有一個類叫ResourceWriter，Visual C#就是通過調用這個類來實現創建、存儲資源檔案的。

三、創建資源檔案的方法

首先要繼承一個ResourceWriter類，然後調用ResourceWriter類的一個方法Generate ( )，就可以產生一個資源檔案了。具體語句如下：

ResourceWriter rw = new ResourceWriter ( "My.resources" ) ;

rw.Generate ( ) ;

此時在磁碟的中就會產生一個名稱為"My.resources"的資源檔案，但此時的資源檔案沒有任何內容，下面我們就來看看如何往資源檔案中添加資源。

四、往資源檔案中添加資源的方法
在ResourceWriter類中提供了一個AddResource ( )方法，這個方法的作用就是往資源檔案中添加資源的。在Visual C#中對不同的資源有著不同的加入方式。

（1）.加入位元組陣列，語法格式為：

public void AddResource ( string , byte [ ] ) ;

註釋：其中string是在使用資源檔案的時候，此位元組陣列在程式中的的唯一標識符

（2）.加入對象，語法格式為：

public void AddResource ( string , object );

註釋：其中string是在使用資源檔案的時候，此物件在程式中的唯一標識符。如：
Image image1 = Image.FromFile ("abc1.jpg") ;

Image image2 = Image.FromFile ( "abc2.jpg" ) ;

rw.AddResource ( "abc1" , image1 ) ;

rw.AddResource ( "abc2" , image2 ) ;

（3）.加入字串，具體語法如下：

public void AddResource ( string1 , string2) ;

註釋：其中string1是在使用資源檔案的時候，此字串在程式中的唯一標識符在本文的程式中，是如此使用的：

rw.AddResource ( "MyStr" , "從資源檔案中讀取字串！" );

至此我們已經創建了一個資源檔案，並且在資源檔案中加入了若干個資源，當然在這之後，還應該注意，保存此資源檔案，並關閉資源檔案，具體如下：

rw.Close ( ) ;

五、示例創建資源檔案

在這裡創建一個什麼樣的專案好呢？有些朋友可能會用.net創建一個"控制台應用程式"，其實沒必要，直接用記事本創建一個CS檔案就可以了，假如名稱為：CreatResources.cs。編譯命令：csc CreatResources.cs；執行：CreatResources。這時會產生一個叫做My.resources的資源檔案。先放到這裡，等下再用。

using System ;

using System.Drawing ;

using System.Resources ;

class CreatResource

{

public static void Main ( )

{

ResourceWriter rw = new ResourceWriter ( "My.resources" ) ;

Image image1 = Image.FromFile ("abc1.jpg") ;

Image image2 = Image.FromFile ( "abc2.jpg" ) ;

rw.AddResource ( "abc1" , image1 ) ;

rw.AddResource ( "abc2" , image2 ) ;

Icon ic = new Icon("CDDRIVE.ICO");

rw.AddResource( "abc3",ic);

rw.AddResource( "abc4","這是從資源檔案中讀出的字元");

rw.Generate ( ) ;

rw.Close ( ) ;

}

}

六、將生成的資源檔案添加測試專案中的方法
創建一個"Windows應用程式"測試專案，將My.resources資源檔案添加到該專案中，步驟如下：

1，在資源管理器裡選中檔案

2，按住鼠標左鍵，拖到專案檔案上，鬆開鼠標左鍵。

3，在拖放的檔案上點鼠標右鍵，選"屬性"

4，在生成操作裡選擇"嵌入的資源"。

七、如何在程式中管理資源檔案中的資源

在.Net FrameWork SDK這提供了一個關於資源檔案創建和使用的名稱空間--System.Resources。在這個名稱空間中有一個Class為ResourceManager，這個Class的主要作用就是管理並使用資源檔案。Visual C＃是通過這個類來管理並使用嵌入程式中的資源檔案中的資源。下列程式碼就是定義一個ResourceManager類來管理嵌入程式資源檔案中的資源：

ResourceManager rm = new ResourceManager ( " Res.My " , Assembly.GetExecutingAssembly ( ) ) ;

注意：ResourceManager rm = new ResourceManager ( " Res.My " , Assembly.GetExecutingAssembly ( ) ) ;語句中，構造函數的第一個參數Res.My 由兩部分構成，Res表示測試專案的命名空間，My表示資源檔案名My.resources的根名稱，即點號有前部分My。

八、如何在程式中使用資源檔案中的資源

在上一篇文章中，我們已經瞭解到在創建資源檔案的時候，使用了AddResource ( )方法來加入資源，他的語法中的第一個參數是用戶可以定義的字串，這個字串就是資源在資源檔案的唯一標識，在程式設計中，就是通過這個唯一標識符來使用某個資源的。那麼如何在程式中通過這個標識符來得到所需資源？這就要使用到ResourceManager類中的GetObject（）和GetString（）方法。這二個方法作用是獲得指定的資源。下面是這二個方法的語法：

object GetSting（String）

object GetObject（String）

其中的"String"就是資源在資源檔案中的那個唯一標識符。細心的讀者可能已經注意到，這二個方法的返回值都是一個Object類型的變數，也就是一個參考類型的變數，而在程式中的字串或者圖像等，是一個實值類型變數。這就需要進行轉換，而這種轉換就是上面所說的裝箱和出箱。下列程式碼是從資源檔案中提取字串、圖像和圖示資源：

提取字串資源：

String s = ( ( String ) rm.GetString ( "MyStr" ) ) ;

提取圖示資源：

Icon icoDemo = ( ( Icon ) rm.GetObject ( "demo.ico" ) ) ;

提取圖像資源：

Image a = ( ( Image ) ( rm.GetObject ( "ok-off.png" ) ) ) ;

九、測試專案源程式碼
using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

// 加入以下兩個命名空間。

using System.Resources;

using System.Reflection;

namespace Res

{

///

/// Form1 的摘要說明。

///

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.PictureBox pictureBox1;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.Button button3;

private System.Windows.Forms.Label label1;

private System.Windows.Forms.Button button4;

///

/// 必需的設計器變數。

///

private System.ComponentModel.Container components = null;

public Form1()

{

//

// Windows 表單設計器支持所必需的

//

InitializeComponent();

//

// TODO: 在 InitializeComponent 調用後添加任何構造函數程式碼

//

}

///

/// 清理所有正在使用的資源。

///

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows 表單設計器生成的程式碼

///

/// 設計器支持所需的方法 - 不要使用程式碼編輯器修改

/// 此方法的內容。

///

private void InitializeComponent()

{

this.pictureBox1 = new System.Windows.Forms.PictureBox();

this.button1 = new System.Windows.Forms.Button();

this.button2 = new System.Windows.Forms.Button();

this.button3 = new System.Windows.Forms.Button();

this.label1 = new System.Windows.Forms.Label();

this.button4 = new System.Windows.Forms.Button();

this.SuspendLayout();

//

// pictureBox1

//

this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.pictureBox1.Location = new System.Drawing.Point(8, 8);

this.pictureBox1.Name = "pictureBox1";

this.pictureBox1.Size = new System.Drawing.Size(256, 240);

this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;

this.pictureBox1.TabIndex = 0;

this.pictureBox1.TabStop = false;

//

// button1

//

this.button1.Location = new System.Drawing.Point(280, 8);

this.button1.Name = "button1";

this.button1.Size = new System.Drawing.Size(88, 24);

this.button1.TabIndex = 1;

this.button1.Text = "圖片1";

this.button1.Click += new System.EventHandler(this.button1_Click);

//

// button2

//

this.button2.Location = new System.Drawing.Point(280, 48);

this.button2.Name = "button2";

this.button2.Size = new System.Drawing.Size(88, 24);

this.button2.TabIndex = 2;

this.button2.Text = "圖片2";

this.button2.Click += new System.EventHandler(this.button2_Click);

//

// button3

//

this.button3.Location = new System.Drawing.Point(280, 128);

this.button3.Name = "button3";

this.button3.Size = new System.Drawing.Size(88, 24);

this.button3.TabIndex = 2;

this.button3.Text = "文字";

this.button3.Click += new System.EventHandler(this.button3_Click);

//

// label1

//

this.label1.Location = new System.Drawing.Point(8, 264);

this.label1.Name = "label1";

this.label1.Size = new System.Drawing.Size(360, 16);

this.label1.TabIndex = 4;

this.label1.Text = "label1";

//

// button4

//

this.button4.Location = new System.Drawing.Point(280, 88);

this.button4.Name = "button4";

this.button4.Size = new System.Drawing.Size(88, 24);

this.button4.TabIndex = 2;

this.button4.Text = "圖示";

this.button4.Click += new System.EventHandler(this.button4_Click);

//

// Form1

//

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

this.ClientSize = new System.Drawing.Size(376, 285);

this.Controls.Add(this.label1);

this.Controls.Add(this.button2);

this.Controls.Add(this.button1);

this.Controls.Add(this.pictureBox1);

this.Controls.Add(this.button3);

this.Controls.Add(this.button4);

this.Name = "Form1";

this.Text = "Form1";

this.ResumeLayout(false);

}

#endregion

///

/// 應用程式的主入口點。

///

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private void button1_Click(object sender, System.EventArgs e)

{

System.Resources.ResourceManager rm = new ResourceManager("Res.My",Assembly.GetExecutingAssembly());

this.pictureBox1.Image = (Bitmap)rm.GetObject("abc1");

}

private void button2_Click(object sender, System.EventArgs e)

{

System.Resources.ResourceManager rm = new ResourceManager("Res.My",Assembly.GetExecutingAssembly());

this.pictureBox1.Image = (Bitmap)rm.GetObject("abc2");

}

private void button4_Click(object sender, System.EventArgs e)

{

System.Resources.ResourceManager rm = new ResourceManager("Res.My",Assembly.GetExecutingAssembly());

this.Icon = (Icon)rm.GetObject("abc3");

}

private void button3_Click(object sender, System.EventArgs e)

{

System.Resources.ResourceManager rm = new ResourceManager("Res.My",Assembly.GetExecutingAssembly());

this.label1.Text = rm.GetString("abc4");

}

}

}

十、結果圖

十一、源程式碼下載網址
http://lizanhong.myshow.cn/

十二、感謝

這篇文章的大部分文字版權屬於王天所有，本來這篇文章沒必要寫的，因為王天網友已經寫得很清楚了，但是我根據王天的文章操作一遍之後發現有有些問題沒說清楚，所以我重新整理了一下。

十三、參考

http://www8.ccidnet.com/tech/guide/2002/01/22/92_3940.html

http://www.socent.com/dotnet/message.asp?id=218


C# 2.0 specification
C# 2.0 specification 下載
http://www.javaworld.com.tw/jute/user/download/30989/SpecificationVer2.rar


1.泛型

先這個Stack類的實現。Stack類將它的資料存放在一個object陣列中，而它的兩個方法，Push和Pop，分別使用object來接受和返回資料：

public class Stack
{
object[] items;
int count;
public void Push(object item) {...}
public object Pop() {...}
}

它的缺點是，你可以向堆疊中壓入任何類型的值，然而，重新取回一個值得時候，必須將Pop方法返回的值顯式地轉換滛合適的類型，書寫這些轉換變更要提防運行時類型檢查錯誤是很乏味的。而且裝箱和拆箱操作增加了執行的負擔，因滛它帶來了動態記憶體分配和運行時類型檢查。
Stack類的另外一個問題是無法強制堆疊中的資料的種類。確實，一個Customer實例可以被壓入棧中，而在取回它的時候會意外地轉換成一個錯誤的類型：

Stack stack = new Stack();
stack.Push(new Customer());
string s = (string)stack.Pop(); //InvalidCastException

這段代碼從技術上來說是正確的，並且不會發生編譯期間錯誤。滛題知道這段代碼運行的時候才會出現，這時會陻出一個InvalidCastException異常。

泛型提供了一個技巧來建立帶有類型參數（type parameters）的類型。下面的例子聲明瞭一個帶有類型參數T的泛型Stack類。類型參數由類名字後面的定界符“<”和“>”指定。通過某種類型建立的Stack<T>的實例 可以無需轉換地接受該種類型的資料，這強過於與object相互裝換。類型參數T扮演一個占位符的角色，直到使用時指定了一個實際的類型。注意T相當於內部陣列的資料類型、Push方法接受的參數類型和Pop方法的返回值類型：

public class Stack<T>
{
T[] items;
int count;
public void Push(T item) {...}
public T Pop() {...}
}

使用泛型類Stack<T>時，需要指定實際的類型來替代T。下面的例子中，指定int作滛參數類型T：

Stack<int> stack = new Stack<int>();
stack.Push(3);
int x = stack.Pop();

Stack<int>類型稱滛已構造類型（constructed type）。在Stack<int>類型中出現的所有T被替換滛類型參數int。當一個Stack<int>的實例被創建時，items陣列的本地存貯是int[]而不是object[]，這提供了一個實質的存貯，效率要高過非泛型的Stack。同樣，Stack<int>中的Push和Pop方法只操作int值，如果向堆疊中壓入其他類型的值將會得到編譯期間的錯誤，而且取回一個值時不必將它顯示轉換滛原類型。

泛型可以提供強類型，這意味著例如向一個Customer物件的堆疊上壓入一個int將會𠖳生錯誤。這是因滛Stack<int>只能操作int值，而Stack<Customer>也只能操作Customer物件。下面例子中的最後兩行會導致編譯器報錯：

Stack<Customer> stack = new Stack<Customer>();
stack.Push(new Customer());
Customer c = stack.Pop();
stack.Push(3); // 類型不匹配錯誤
int x = stack.Pop(); // 類型不匹配錯誤

泛型類型的聲明允許任意數目的類型參數。上面的Stack<T>例子只有一個類型參數，但一個泛型的Dictionary類可能有兩個類型參數，一個是鍵的類型另一個是值的類型：

public class Dictionary<K,V>
{
public void Add(K key, V value) {...}
public V this[K key] {...}
}

使用Dictionary<K,V>時，需要提供兩個類型參數：

Dictionary<string,Customer> dict = new Dictionary<string,Customer>();
dict.Add("Peter", new Customer());
Customer c = dict["Peter"];

結語：泛型允許類、結構、介面、委託和方法通過它們所存貯和操作的資料的類型來參數化。泛型是很有用的，因滛它提供了更滛強大的編譯期間類型檢查，需要更少的資料類型之間的顯式轉換，並且減少了對裝箱操作的需要和運行時的類型檢查。


2.改進的委託 &anoymouse method

委託（delegate）是C# 1.0的難點之一。大部分人認滛委託很麻煩。原因是語法太奇怪了。看看這個經典的代碼行：

button1.Click += new EventHandler(button1_Click);
void button1_Click(Object sender, EventArgs e) {
   // Do something, the button was clicked...
}

對於大多數人來說，構造EventHandler物件就只是滛了得到button1_Click 方法的位址，這是一個大家並不關心的細節。也許大家更願意採用下列方式編寫上述代碼：

button1.Click += button1_Click;

很幸運的是，幸運的是，微軟C# 2.0編譯器改進了委託語法。首先C# 2.0允許你不需要構造委託物件包裝就可以指定回叫方法名。

class AClass {
  static void CallbackWithoutNewingADelegateObject()
{
         ThreadPool.QueueUserWorkItem(SomeAsyncTask, 5);
  }

  static void SomeAsyncTask(Object o) {
         Console.WriteLine(o);
  }
}

ThreadPool類的靜態QueueUserWorkItem方法需要一個引用SomeAsyncTask方法的WaitCallback委託物件引用，C# 2.0 編譯器能夠察覺這種情況，因此它允許省略構造WaitCallback委託物件的代碼，從而使得代碼更加易於閱讀和理解，而編譯的時候，IL編譯器確實new了一個委託物件。現在，你可以這樣編寫代碼了

// Add to invocation list
button1.Click += button1_Click;

// Remove from invocation list
button.Click -= button1_Click;

C# 2.0 還允許使用內聯（in-line）的方式來編寫代碼，（通常是委託代碼），這在C#中稱滛匿名方法。

一個匿名方法由關鍵字delegate和一個可選的參數列表組成，並將語句放入“{”和“}”限定符中。下面的例子使用了匿名方法對函數進行了“內聯（in-lian）”。匿名方法被作滛一個Function委託類型傳遞。

上面的ThreadPool的例子可以寫成這個樣子：

class AClass {
  static void CallbackWithoutNewingADelegateObject() {
         ThreadPool.QueueUserWorkItem(
         delegate(Object obj) { Console.WriteLine(obj); },
         5);
  }
}

QueueUserWorkItem 方法的第一個“參數”是一個代碼塊！C# 編譯器發現期望引用委託物件的地方都使用了委託關鍵字，編譯器就會自動地在類（此處滛AClass）中 定義一個新方法。通過ILASM可以看到這個方法的命名有點像__AnonymousMethod$00000002。匿名方法的原型必須匹配WaitCallback 委託的原型：返回void並帶有一個Object參數。注意，匿名方法是私有的(private)！

上面的匿名方法是靜態的；因滛定義它的方法CallbackWithoutNewingADelegateObject也是靜態的。這就意味著有可能訪問類中的任何靜態域或者靜態方法。如果CallbackWithoutNewingADelegateObject方法不是靜態的，編譯器將生成一個非靜態的匿名方法，當然，該方法的代碼能夠訪問任何非靜態的域和非靜態的方法：

class AClass {
   String m_name;    // An instance field

   // An instance method
   void CallbackWithoutNewingADelegateObject() {
      ThreadPool.QueueUserWorkItem(
         // The callback code can reference instance members.
         delegate(Object obj) { Console.WriteLine(m_name+ ": " +
                                                  obj); },
         5);
   }
}

現在Button_click可以進一步簡化成這個樣子：

button1.Click += delegate(Object sender, EventArgs e)
                 { MessageBox.Show("The Button was clicked!"); };

但是C# 2.0還允許進一步簡化代碼，因滛在此例中，回叫代碼一點也不涉及回叫方法的參數、發送器等等。如果你的回叫代碼不在乎參數， C# 允許上述代碼縮短成這樣：

button1.Click += delegate
                 { MessageBox.Show("The Button was clicked!"); };

前面例子中的匿名方法沒有使用提供給委託的參數，因此可以省略參數列表。要想訪問參數，你名方法應該包含一個參數列表：

addButton.Click += delegate(object sender, EventArgs e) {
MessageBox.Show(((Button)sender).Text);
};

在匿名方法和EventHandler委託類型（Click事件的類型）之間發生了一個隱式的轉換。這個隱式的轉換是可行的，因滛這個委託的參數列表和返回值類型和匿名方法是相容的。精確的相容規則如下：

• 當下面條例中有一條滛真時，則委託的參數列表和匿名方法是相容的：
o 匿名方法沒有參數列表且委託沒有輸出（out）參數。
o 匿名方法的參數列表在參數數目、類型和修飾符上與委託參數精確匹配。
• 當下面的條例中有一條滛真時，委託的返回值與匿名方法相容：
o 委託的返回值類型是void且匿名方法沒有return語句或其return語句不帶任何運算式。
o 委託的返回值類型不是void但和匿名方法的return語句關聯的運算式的值可以被顯式地轉換滛委託的返回值類型。

只有參數列表和返回值類型都相容的時候，才會發生匿名類型向委託類型的隱式轉換。

如果回叫代碼訪問任何一個參數，那樌你必須在委託關鍵字之後包括插入語、參數類型和變數名。返回類型仍然可從委託的類型推斷出，並且，如果返回類型不滛空，你必須在回叫代碼中有一個返回語句。

有時你可能希望回叫代碼訪問定義方法中存在的局部參數或者變數。下面是一個不錯的例子：

class AClass {
   static void UsingLocalVariablesInTheCallbackCode(Int32 numToDo) {

      // Some local variables
      Int32[] squares = new Int32[numToDo];
      AutoResetEvent done = new AutoResetEvent(false);

      // Do a bunch of tasks on other threads
      for (Int32 n = 0; n < squares.Length; n++) {
         ThreadPool.QueueUserWorkItem(
            delegate(Object obj) {
               Int32 num = (Int32) obj;

               // This task would normally more time consuming
               squares[num] = num * num;

               // If last task, let main thread continue running
               if (Interlocked.Decrement(ref numToDo) == 0)
                  done.Set();
            }, n);
      }

      // Wait for all the other threads to finish
      done.WaitOne();

      // Show the results
      for (Int32 n = 0; n < squares.Length; n++)
         Console.WriteLine("Index {0}, Square={1}", n, squares[n]);
   }
}

想像一下，在C# 1.0 中，委託代碼被獨立定義在一個方法中，要訪問
這些變數的值是多樌困難的事情。

Ref:
http://www.developer.com/net/csharp/article.php/10918_3103031_1


3. 疊代器

C#中的foreach語句用於疊代一個可枚舉（enumerable）的集合中的元素。為了實現可枚舉，一個集合必須要有一個無參的、返回枚舉器（enumerator）的GetEnumerator方法。通常，枚舉器是很難實現的，因此簡化枚舉器的任務意義重大。

疊代器（iterator）是一塊可以產生（yields）值的有序序列的語句塊。疊代器通過出現的一個或多個yield語句來區別於一般的語句塊：

•yield return語句產生本次疊代的下一個值。
• yield break語句指出本次疊代完成。

只要一個函數成員的返回值是一個枚舉器介面（enumerator interfaces）或一個可枚舉介面（enumerable interfaces），我們就可以使用疊代器：

• 所謂枚舉器藉口是指System.Collections.IEnumerator和從System.Collections.Generic.IEnumerator<T>構造的類型。
•所謂可枚舉介面是指System.Collections.IEnumerable和從System.Collections.Generic.IEnumerable<T>構造的類型。

理解疊代器並不是一種成員，而是實現一個功能成員是很重要的。一個通過疊代器實現的成員可以用一個或使用或不使用疊代器的成員覆蓋或重寫。

下面的Stack<T>類使用疊代器實現了它的GetEnumerator方法。其中的疊代器按照從頂端到底端的順序枚舉了棧中的元素。

using System.Collections.Generic;
public class Stack<T>: IEnumerable<T>
{
         T[] items;
         int count;
         public void Push(T data) {...}
         public T Pop() {...}
         public IEnumerator<T> GetEnumerator() {
         for (int i = count – 1; i >= 0; --i) {
                           yield return items[i];
                  }
         }
}

GetEnumerator方法的出現使得Stack<T>成為一個可枚舉類型，這允許Stack<T>的實例使用foreach語句。下面的例子將值0至9壓入一個整數堆疊，然後使用foreach迴圈按照從頂端到底端的順序顯示每一個值。

using System;
class Test
{
         static void Main() {
                  Stack<int> stack = new Stack<int>();
                  for (int i = 0; i < 10; i++) stack.Push(i);
                  foreach (int i in stack) Console.Write("{0} ", i);
                  Console.WriteLine();
         }
}

這個例子的輸出為：9 8 7 6 5 4 3 2 1 0

語句隱式地調用了集合的無參的GetEnumerator方法來得到一個枚舉器。一個集合類中只能定義一個這樣的無參的GetEnumerator方法，不過通常可以通過很多途徑來實現枚舉，包括使用參數來控制枚舉。在這些情況下，一個集合可以使用疊代器來實現能夠返回可枚舉介面的屬性和方法。例如，Stack<T>可以引入兩個新的屬性——IEnumerable<T>類型的TopToBottom和BottomToTop：

using System.Collections.Generic;
public class Stack<T>: IEnumerable<T>
{
         T[] items;
         int count;
         public void Push(T data) {...}
         public T Pop() {...}
         public IEnumerator<T> GetEnumerator() {
                  for (int i = count – 1; i >= 0; --i) {
                           yield return items[i];
                  }
         }
         public IEnumerable<T> TopToBottom {
                  get {
                           return this;
                  }
         }
         public IEnumerable<T> BottomToTop {
                  get {
                           for (int i = 0; i < count; i++) {
                                    yield return items[i];
                           }
                  }
         }
}

TopToBottom屬性的get訪問器只返回this，因為堆疊本身就是一個可枚舉類型。BottomToTop屬性使用C#疊代器返回了一個可枚舉介面。下面的例子顯示了如何使用這兩個屬性來以任意順序枚舉棧中的元素：

using System;
class Test
{
         static void Main() {
                  Stack<int> stack = new Stack<int>();
                  for (int i = 0; i < 10; i++) stack.Push(i);
                  foreach (int i in stack.TopToBottom) Console.Write("{0} ", i);
                  Console.WriteLine();
                  foreach (int i in stack.BottomToTop) Console.Write("{0} ", i);
                  Console.WriteLine();
         }
}
         當然，這些屬性還可以用在foreach語句的外面。下面的例子將調用屬性的結果傳遞給一個獨立的Print方法。這個例子還展示了一個疊代器被用作一個帶參的FromToBy方法的方法體：
using System;
using System.Collections.Generic;
class Test
{
         static void Print(IEnumerable<int> collection) {
                  foreach (int i in collection) Console.Write("{0} ", i);
                  Console.WriteLine();
         }
         static IEnumerable<int> FromToBy(int from, int to, int by) {
                  for (int i = from; i <= to; i += by) {
                           yield return i;
                  }
         }
         static void Main() {
                  Stack<int> stack = new Stack<int>();
                  for (int i = 0; i < 10; i++) stack.Push(i);
                  Print(stack.TopToBottom);
                  Print(stack.BottomToTop);
                  Print(FromToBy(10, 20, 2));
         }
}

這個例子的輸出為：
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
10 12 14 16 18 20

泛型和非泛型的可枚舉介面都只有一個單獨的成員，一個無參的GetEnumerator方法，它返回一個枚舉器介面。一個可枚舉介面很像一個枚舉器工廠（enumerator factory）。每當調用了一個正確地實現了可枚舉介面的類的GetEnumerator方法時，都會產生一個獨立的枚舉器。

using System;
using System.Collections.Generic;
class Test
{
         static IEnumerable<int> FromTo(int from, int to) {
                  while (from <= to) yield return from++;
         }
         static void Main() {
                  IEnumerable<int> e = FromTo(1, 10);
                  foreach (int x in e) {
                           foreach (int y in e) {
                                    Console.Write("{0,3} ", x * y);
                           }
                           Console.WriteLine();
                  }
         }
}

上面的程式碼列印了一個從1到10的簡單乘法表。注意FromTo方法只調用了一次用來產生可枚舉介面e。而e.GetEnumerator()被調用了多次（通過foreach語句）來產生多個相同的枚舉器。這些枚舉器都封裝了FromTo宣告中指定的程式碼。注意，疊代其程式碼改變了from參數。不過，枚舉器是獨立的，因為對於from參數和to參數，每個枚舉器擁有它自己的一份拷貝。在實現可枚舉類和枚舉器類時，枚舉器之間的過渡狀態（一個不穩定狀態）是必須消除的眾多細微瑕疵之一。C#中的疊代器的設計可以幫助消除這些問題，並且可以用一種簡單的本能的方式來實現健壯的可枚舉類和枚舉器類。

迭代器是能夠增量地計算和產生一系列值得方法。迭代器使得一個類能夠很容易地解釋foreach語句將如何迭代他的每一個元素。


4.不完全類型
儘管在一個單獨的檔案中維護一個類型的所有程式碼是一項很好的設計實踐，但有些時候，當一個類變得非常大，這就成了一種不切實際的約束。而且，程式員經常使用程式碼生成器來生成一個應用程式的初始結構，然後修改產生的程式碼。不幸的是，當以後需要再次發佈原程式碼的時候，現存的修正會被重寫。

不完全類型允許類、結構和介面被分成多個小塊兒並存貯在不同的源檔案中使其容易開發和維護。另外，不完全類型可以分離機器產生的程式碼和用戶書寫的部分，這使得用工具來加強產生的程式碼變得容易。

要在多個部分中定義一個類型的時候，我們使用一個新的修飾符——partial。下面的例子在兩個部分中實現了一個不完全類。這兩個部分可能在不同的源檔案中，例如第一部分可能是機器通過資料庫影射工具產生的，而第二部分是手動創作的：

public partial class Customer
{
         private int id;
         private string name;
         private string address;
         private List<Order> orders;
         public Customer() {
                  ...
         }
}

public partial class Customer
{
         public void SubmitOrder(Order order) {
                  orders.Add(order);
         }
         public bool HasOutstandingOrders() {
                  return orders.Count > 0;
         }
}

當上面的兩部分編譯到一起時，產生的程式碼就好像這個類被寫在一個單元中一樣：

public class Customer
{
         private int id;
         private string name;
         private string address;
         private List<Order> orders;
         public Customer() {
                  ...
         }
         public void SubmitOrder(Order order) {
                  orders.Add(order);
         }
         public bool HasOutstandingOrders() {
                  return orders.Count > 0;
         }
}

不完全類型的所有部分必須放到一起編譯，才能在編譯期間將它們合併。需要特別注意的是，不完全類型並不允許擴展


NET資源站點匯總

名稱：快速入門
位址：http://chs.gotdotnet.com/quickstart/
描述：本站點是微軟.NET技術的快速入門網站，我們不必再安裝.NET Framework中的快速入門示例程式，直接在網上查看此示例即看。
****************************************************
名稱：微軟官方.NET指導站點
位址：http://www.gotdotnet.com/
描述：上面的站點是本站的一個子站點，本站點提供微軟.NET官方信息，並且有大量的用戶源程式碼、元件下載，微軟.NET開發組的人員也經常在此站點發表一些指導性文章。
****************************************************
名稱：SourceForge
位址：http://www.sourceforge.net
描述：世界上最大的Open Source專案在線網站，上面已經有.NET的各種大型Open Source專案上千件，包括SharpDevelop、NDoc、Mono等都是在此站點發佈最新源程式碼信息。
****************************************************
名稱：CodeProject
位址：http://www.codeproject.com
描述：很多非官方的中小型示例源代及文章，相當全面，基本上我們想要的各種方面的資料都可以在此處查找。
****************************************************
名稱：Fabrice's weblog
位址：http://dotnetweblogs.com/FMARGUERIE/Story/4139.aspx
描述：這是一個WebLog形式的在線日誌網站，定期更新，包括.NET相關的工具、混淆器、反編譯器等各種信息，十分值得收藏。
****************************************************
名稱：
位址：http://www.aspalliance.com/aldotnet/examples/translate.aspx
描述：c#翻譯為vb.net，提供一個文字框，將你的C#源程式碼貼進去，就可以幫你翻譯成VB.NET語法。
****************************************************
名稱：CSharpHelp
位址：http://www.csharphelp.com
描述： 專業的C#語言在線幫助網站，主要提供C#語言方面的技術文章。專業性很強。
****************************************************
名稱：DotNet247
位址：http://www.dotnet247.com
描述：最好的索引網站，分別按照門類及命名空間的索引，也提供了Microsoft KB知識庫。
****************************************************
名稱：ASP.NET
位址：http://www.asp.net
描述：微軟.NET webform的老巢，資料和實例程式碼都非常難得。
****************************************************
名稱：微軟.NET Winform
位址：http://www.windowsforms.net/
描述：微軟.NET Winform的老巢。
****************************************************
名稱：微軟 KnowledgeBase
位址：http://support.microsoft.com/
描述：微軟知識庫，開發的時候遇到的怪問題，可能會在這裡找到答案。
****************************************************
名稱：MSDN
位址：http://msdn.microsoft.com/
描述：這個就不用多說了吧，雖然出了中文MSDN，但是資料還是不夠全，英文的就什麼都有了。
****************************************************
名稱：HotScripts
位址：http://www.hotscripts.com/
描述：Welcome to HotScripts.com, the net's largest PHP, CGI, Perl, JavaScript and ASP script collection and resource web portal. We currently have 24,004 scripts across 11 different programming languages and 1,240 categories, as well as links to books, articles, as well as programming tips and tutorials.
****************************************************
名稱：ASPAlliance
位址：http://www.aspalliance.com/
描述：提供相當豐富的文章和示例程式碼，思路匱乏的時候可以找找思路
****************************************************
名稱：CSDN文檔中心
位址：http://dev.csdn.net/
描述：中文的，資料還算豐富，可以作為國內首選。
****************************************************
名稱：DOTNET中華網
位址：http://www.aspxcn.com/
描述：2002-2003年的時候這個站點很不錯的，不過現在好像管理不得力，有點疲軟，資料更新也不過及時，論壇裡人也不夠熱心了，因為希望它好起來，所以列出來。資料都比較老，不過有些D版的東西還可以。提供很多學習程式碼。
****************************************************
名稱：中國DotNet俱樂部
位址：http://www.chinaspx.com/
描述：有點公司背景的網站，很健壯，資料更新及時，比較豐富。論壇解答也不錯。
****************************************************
名稱：【孟憲會之精彩世界】
位址：http://dotnet.aspx.cc/
描述：MS-MVP的個人站點，包括了他所有的經驗文章，還是很值得一看的。
****************************************************
名稱：dotNET Tools.org
位址：http://www.dotnettools.org
描述：ccboy，也就是CSDN的小氣的神的站點，裡面有很多關於.NET等的好東東。
****************************************************
名稱：博客堂
位址：http://blog.joycode.com/
描述：半官方性質的MS-MVP彙集blog，大家可以在這裡接觸到最新的技術，瞭解發展趨勢，對技術的探索等等，優秀的文章。
****************************************************
名稱：DotNetBips.com - Applying .NET
位址：http://www.dotnetbips.com/
描述：該站點的文章，涉及到了整個.NET，從底層的IL到語言到架構，文章很多，質量還不錯。
****************************************************
名稱：C# Frequently Asked Questions
位址：http://blogs.msdn.com/csharpfaq/
描述：The C# team posts answers to common questions
****************************************************
名稱：正則陳述式
位址：http://www.regexplib.com/
描述: 正則陳述式學習站點
****************************************************
名稱：WINDOW FORMS FAQ
位址：http://www.syncfusion.com/FAQ/WinForms/
描述：常見的forms faq問題，很多問題都可以在這裡找到答案。
****************************************************
名稱：ASP.NET 常用類庫說明
位址：http://www.123aspx.com/rotor/default.aspx
描述：不用多說，看標題就知道是關於asp.net的名稱空間的
****************************************************
名稱：ASP.NET System.Web.Mail
位址：http://www.systemwebmail.com/faq/3.8.aspx
描述：郵件發送常見問題解決方法
****************************************************
名稱：VB.NET & C# 比較
位址：http://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.html
描述：VB.NET跟C#語法區別
****************************************************
名稱：VB.NET架構師　BLOG
位址：http://panopticoncentral.net/
描述：不用多說，想瞭解VB.NET的朋友不可不去的站點(PS，不知道我有沒有記錯是不是這個位址）
****************************************************
名稱：索克論壇
位址：http://www.sorke.com/bbs/Boards.asp
描述：我想應該是國內最好的第三方.NET元件的下載基


 題目一：有1、2、3、4個數字，能組成多少個互不相同且無重複數字的三位數？都是多少？
1.程式分析：可填在百位、十位、個位的數字都是1、2、3、4。
            組成所有的排列後再去掉不滿足條件的排列。
2.程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main()
{
int i,j,k;
for(i=1;i<5;i++)
//使用三層迴圈
{
for(j=1;j<5;j++)
{
for(k=1;k<5;k++)
{
if (i!=k&&i!=j&&j!=k)
//確定i、j、k三位數互不相同
Console.WriteLine("{0},{1},{2}",i,j,k);
}
}
}
}
}
}
結果：
1,2,3
1,2,4
1,3,2
1,3,4
1,4,2
1,4,3
2,1,3
2,1,4
2,3,1
2,3,4
2,4,1
2,4,3
3,1,2
3,1,4
3,2,1
3,2,4
3,4,1
3,4,2
4,1,2
4,1,3
4,2,1
4,2,3
4,3,1
4,3,2
請按任意鍵繼續 . . .


題目二：企業發放的獎金根據利潤提成。利潤(I)低於或等於10萬元時，獎金可提10%；
       利潤高於10萬元，低於20萬元時，低於10萬元的部分按10%提成，高於10萬元的部分，可提成7.5%；
       20萬到40萬之間時，高於20萬元的部分，可提成5%；40萬到60萬之間時高於
        40萬元的部分，可提成3%；60萬到100萬之間時，高於60萬元的部分，可提成1.5%，高於
        100萬元時，超過100萬元的部分按1%提成，從鍵盤輸入當月利潤I，求應發放獎金總數？
1.程式分析：請利用數軸來分界，定位。注意定義時需把獎金定義為長整數型。

2.程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main()
{
long
i;
double
bonus1,bonus2,bonus4,bonus6,bonus10,bonus;
string
inputstr;
Console.WriteLine("輸入當月利潤：");
inputstr=Console.ReadLine();
i=int.Parse(inputstr);
bonus1=100000*0.1;
bonus2=bonus1+100000*0.75;
bonus4=bonus2+200000*0.5;
bonus6=bonus4+200000*0.3;
bonus10=bonus6+400000*0.15;
if(i<=100000)
bonus=i*0.1;
else
if(i<=200000)
bonus=bonus1+(i-100000)*0.075;
else
if(i<=400000)
bonus=bonus2+(i-200000)*0.05;
else
if(i<=600000)
bonus=bonus4+(i-400000)*0.03;
else
if(i<=1000000)
bonus=bonus6+(i-600000)*0.015;
else
bonus=bonus10+(i-1000000)*0.01;
Console.WriteLine("應發放獎金總數={0:C}",bonus);
}
}
}
結果：
輸入當月利潤：
20000
應發放獎金總數=NT$2,000.00
請按任意鍵繼續 . . .


題目三：一個整數，它加上100後是一個完全平方數，再加上168又是一個完全平方數，請問該數是多少？
1.程式分析：在10萬以內或100以內判斷，先將該數加上100後再開方，再將該數加上268後再開方，
            如果開方後的結果滿足如下條件，即是結果。
2.程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main()
{
long
i;
double x,y;
for
(i=1;i<100;i++)   //100以內判斷
{
x=Math.Sqrt(i+100);
//x為加上100後的結果
y=Math.Sqrt(i+268);
//y為加上268後的結果
if(x*x==i+100&&y*y==i+268)
//如果一個數的平方根的平方等於該數，這說明此數是完全平方數
Console.WriteLine("{0}",i);
}
}
}
}
結果：
8
14
18
21
29
30
31
34
42
43
55
56
57
58
59
61
62
64
65
68
69
73
74
76
77
78
79
84
95
96
99
請按任意鍵繼續 . . .


題目四：輸入某年某月某日，判斷這一天是這一年的第幾天？
1.程式分析：以3月5日為例，應該先把前兩個月的加起來，然後再加上5天即本年的第幾天，
            特殊情況，閏年且輸入月份大於3時需考慮多加一天。
2.程式碼：
using System;
namespace DefaultNamespace
{
 class MainClass
 {
  public static void Main()
  {
   int day,month,year,sum,leap;
   string Cday,Cmonth,Cyear;
   sum=0;
Console.WriteLine("輸入年：");
Cyear=Console.ReadLine();
year=int.Parse(Cyear);

Console.WriteLine("輸入月：");
Cmonth=Console.ReadLine();
month=int.Parse(Cmonth);

Console.WriteLine("輸入日：");
Cday=Console.ReadLine();
day=int.Parse(Cday);

switch(month)
//先計算某月以前月份的總天數
{
case
1:sum=0;break;
case
2:sum=31;break;
case
3:sum=59;break;
case
4:sum=90;break;
case
5:sum=120;break;
case
6:sum=151;break;
case
7:sum=181;break;
case
8:sum=212;break;
case
9:sum=243;break;
case
10:sum=273;break;
case
11:sum=304;break;
case
12:sum=334;break;
default:Console.WriteLine("輸入資料錯誤！");break;
}

   sum=sum+day; //再加上某天的天數
if(year%400==0||(year%4==0&&year%100!=0))
//判斷是不是閏年
leap=1;
else
leap=0;

   if(leap==1&&month>2) //如果是閏年且月份大於2,總天數應該加一天
     sum++;
Console.WriteLine("它是
{0}年的第{1}天",year,sum);
}
}
}
結果：
輸入年：
2004
輸入月：
3
輸入日：
5
它是 2004年的第65天
請按任意鍵繼續 . . .


題目五：輸入三個整數x,y,z，請把這三個數由小到大輸出。
1.程式分析：我們想辦法把最小的數放到x上，先將x與y進行比較，如果x>y則將x與y的值進行交換，
             然後再用x與z進行比較，如果x>z則將x與z的值進行交換，這樣能使x最小。
2.程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main()
{
int
x,y,z,t;
string
sx,sy,sz;
Console.WriteLine("輸入x：");
sx=Console.ReadLine();
x=int.Parse(sx);

Console.WriteLine("輸入y：");
sy=Console.ReadLine();
y=int.Parse(sy);

Console.WriteLine("輸入z：");
sz=Console.ReadLine();
z=int.Parse(sz);

if
(x>y) //交換x,y的值
{
t=x;
x=y;
y=t;
}

if(x>z)
//交換x,z的值
{
t=z;
z=x;
x=t;
}

if(y>z)
//交換z,y的值
{
t=y;
y=z;
z=t;
}
Console.WriteLine("由小到大排列：{0},{1},{2}",x,y,z);
}
}
}
結果：
輸入x：
3
輸入y：
2
輸入z：
1
由小到大排列：1,2,3
請按任意鍵繼續 . . .


題目六：求巴斯卡三角形，列印出十行。
程式碼：
using System;
namespace DefaultNamespace
{
class
MainClass
{
public static void
Main()
{
int
i,j;
int[,] a=new
int[10,10];
for(i=0;i<10;i++)
{
a[i,0]=1;
a[i,i]=1;
}

     for(i=2;i<10;i++)
      for(j=1;j<i;j++)
       a[i,j]=a[i-1,j-1]+a[i-1,j];
for(i=0;i<10;i++)
{
for(j=0;j<=i;j++)
Console.Write(" {0}
",a[i,j]);
Console.Write("\n");
}
}
}
}
結果：
 1
 1  1
 1  2  1
 1  3  3  1
 1  4  6  4  1
 1  5  10  10  5  1
 1  6  15  20  15  6  1
 1  7  21  35  35  21  7  1
 1  8  28  56  70  56  28  8  1
 1  9  36  84  126  126  84  36  9  1
請按任意鍵繼續 . . .


書       名：SharpDevelop Bible
製       作：Qoo1234
討論網站： 縱橫程式設計領域討論
博客網站： CSharp研究室
相關資料：Delphi K.Top討論區
主要內容：
         1. 認識SharpDevelop 開發工具
         2. NET FrameWork 簡介
         3. NET Class Library(BCL) 應用
         4. C# 程式語言
         5. C# 與 資料庫
         6. C# 與 GDI+
         7. C# 與 多媒體應用
         8. C# 與 網際網路應用
         9. C# 與 XML
         10.C# 與 Win32API 應用(NET 2.0 前使用的方式)
         11.C# 類別元件製作
                         ...等等
備   註：英文文章，僅供參考之用。
使用軟體：
.NET Framework SDK Version 1.1
SharpDevelop 1.0 RC3
===============================================================