Initial winforms content migrated (#18)

* Merge winforms framework content to working branch (#14)

* Breadcrumb / TOC / Move net5 to net folder (#15)

* change path from net5 to net

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Mess with bread/toc

* Add .net 5 winforms placeholder article (#16)

* added some metadata and adjusted net5 placeholder

* corrections

* corrections

* corrections

* Test1

* Swapping landing page vs concept

* fix links

* Fix links

* Fix desc
This commit is contained in:
Andy De George
2020-09-01 16:26:21 -07:00
committed by GitHub
parent 1a27c9b107
commit c0ba284473
1557 changed files with 129980 additions and 13 deletions
@@ -0,0 +1,61 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{267B4A3D-A09F-4067-A39A-F3BE7108AC65}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>AccessHTMLDOMControlCSharp</RootNamespace>
<AssemblyName>AccessHTMLDOMControlCSharp</AssemblyName>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>.\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>.\bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="UserControl1.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="UserControl1.Designer.cs">
<DependentUpon>UserControl1.cs</DependentUpon>
</Compile>
<Compile Include="Configuration\AssemblyInfo.cs" />
<EmbeddedResource Include="Configuration\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.cs</LastGenOutput>
</EmbeddedResource>
<Compile Include="Configuration\Resources.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Configuration\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.cs</LastGenOutput>
</None>
<Compile Include="Configuration\Settings.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Service Include="{94E38DFF-614B-4cbd-B67C-F211BB35CE8B}" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" />
</Project>
@@ -0,0 +1,31 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AccessHTMLDOMControlCSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MS")]
[assembly: AssemblyProduct("AccessHTMLDOMControlCSharp")]
[assembly: AssemblyCopyright("Copyright @ MS 2004")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
/// Setting ComVisible to false makes the types in this assembly not visible
/// to COM componenets. If you need to access a type in this assembly from
/// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
@@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.41021.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace AccessHTMLDOMControlCSharp.Configuration
{
using System;
using System.IO;
using System.Resources;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the Strongly Typed Resource Builder
// class via a tool like ResGen or Visual Studio.NET.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
class Resources
{
private static System.Resources.ResourceManager _resMgr;
private static System.Globalization.CultureInfo _resCulture;
/*FamANDAssem*/
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static System.Resources.ResourceManager ResourceManager
{
get
{
if ((_resMgr == null))
{
System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly);
_resMgr = temp;
}
return _resMgr;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static System.Globalization.CultureInfo Culture
{
get
{
return _resCulture;
}
set
{
_resCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,42 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.41021.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace AccessHTMLDOMControlCSharp.Configuration
{
public partial class Settings : System.Configuration.ApplicationSettingsBase
{
private static Settings m_Value;
private static object m_SyncObject = new object();
public static Settings Value
{
get
{
if ((Settings.m_Value == null))
{
System.Threading.Monitor.Enter(Settings.m_SyncObject);
if ((Settings.m_Value == null))
{
try
{
Settings.m_Value = new Settings();
}
finally
{
System.Threading.Monitor.Exit(Settings.m_SyncObject);
}
}
}
return Settings.m_Value;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='iso-8859-1'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,44 @@
namespace AccessHTMLDOMControlCSharp
{
partial class UserControl1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component 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.SuspendLayout();
//
// UserControl1
//
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(435, 401);
this.Load += new System.EventHandler(this.UserControl1_Load);
this.ResumeLayout(false);
}
#endregion
}
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace AccessHTMLDOMControlCSharp
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
//<SNIPPET1>
HtmlDocument doc = null;
private void UserControl1_Load(object sender, EventArgs e)
{
if (this.Site != null)
{
doc = (HtmlDocument)this.Site.GetService(typeof(HtmlDocument));
}
}
//</SNIPPET1>
}
}
@@ -0,0 +1,236 @@
//<Snippet1>
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.IO;
namespace MyApplication
{
// A simple form that represents a window in our application
public class AppForm2 : System.Windows.Forms.Form
{
public AppForm2()
{
this.Size = new System.Drawing.Size(300, 300);
this.Text = "AppForm2";
}
}
// A simple form that represents a window in our application
public class AppForm1 : System.Windows.Forms.Form
{
public AppForm1()
{
this.Size = new System.Drawing.Size(300, 300);
this.Text = "AppForm1";
}
}
//<Snippet2>
// The class that handles the creation of the application windows
class MyApplicationContext : ApplicationContext
{
private int _formCount;
private AppForm1 _form1;
private AppForm2 _form2;
private Rectangle _form1Position;
private Rectangle _form2Position;
private FileStream _userData;
//<Snippet5>
private MyApplicationContext()
{
_formCount = 0;
// Handle the ApplicationExit event to know when the application is exiting.
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
try
{
// Create a file that the application will store user specific data in.
_userData = new FileStream(Application.UserAppDataPath + "\\appdata.txt", FileMode.OpenOrCreate);
}
catch (IOException e)
{
// Inform the user that an error occurred.
MessageBox.Show("An error occurred while attempting to show the application." +
"The error is:" + e.ToString());
// Exit the current thread instead of showing the windows.
ExitThread();
}
// Create both application forms and handle the Closed event
// to know when both forms are closed.
_form1 = new AppForm1();
_form1.Closed += new EventHandler(OnFormClosed);
_form1.Closing += new CancelEventHandler(OnFormClosing);
_formCount++;
_form2 = new AppForm2();
_form2.Closed += new EventHandler(OnFormClosed);
_form2.Closing += new CancelEventHandler(OnFormClosing);
_formCount++;
// Get the form positions based upon the user specific data.
if (ReadFormDataFromFile())
{
// If the data was read from the file, set the form
// positions manually.
_form1.StartPosition = FormStartPosition.Manual;
_form2.StartPosition = FormStartPosition.Manual;
_form1.Bounds = _form1Position;
_form2.Bounds = _form2Position;
}
// Show both forms.
_form1.Show();
_form2.Show();
}
private void OnApplicationExit(object sender, EventArgs e)
{
// When the application is exiting, write the application data to the
// user file and close it.
WriteFormDataToFile();
try
{
// Ignore any errors that might occur while closing the file handle.
_userData.Close();
}
catch { }
}
//</Snippet5>
private void OnFormClosing(object sender, CancelEventArgs e)
{
// When a form is closing, remember the form position so it
// can be saved in the user data file.
if (sender is AppForm1)
_form1Position = ((Form)sender).Bounds;
else if (sender is AppForm2)
_form2Position = ((Form)sender).Bounds;
}
//<Snippet3>
private void OnFormClosed(object sender, EventArgs e)
{
// When a form is closed, decrement the count of open forms.
// When the count gets to 0, exit the app by calling
// ExitThread().
_formCount--;
if (_formCount == 0)
{
ExitThread();
}
}
//</Snippet3>
private bool WriteFormDataToFile()
{
// Write the form positions to the file.
UTF8Encoding encoding = new UTF8Encoding();
RectangleConverter rectConv = new RectangleConverter();
string form1pos = rectConv.ConvertToString(_form1Position);
string form2pos = rectConv.ConvertToString(_form2Position);
byte[] dataToWrite = encoding.GetBytes("~" + form1pos + "~" + form2pos);
try
{
// Set the write position to the start of the file and write
_userData.Seek(0, SeekOrigin.Begin);
_userData.Write(dataToWrite, 0, dataToWrite.Length);
_userData.Flush();
_userData.SetLength(dataToWrite.Length);
return true;
}
catch
{
// An error occurred while attempting to write, return false.
return false;
}
}
private bool ReadFormDataFromFile()
{
// Read the form positions from the file.
UTF8Encoding encoding = new UTF8Encoding();
string data;
if (_userData.Length != 0)
{
byte[] dataToRead = new byte[_userData.Length];
try
{
// Set the read position to the start of the file and read.
_userData.Seek(0, SeekOrigin.Begin);
_userData.Read(dataToRead, 0, dataToRead.Length);
}
catch (IOException e)
{
string errorInfo = e.ToString();
// An error occurred while attempt to read, return false.
return false;
}
// Parse out the data to get the window rectangles
data = encoding.GetString(dataToRead);
try
{
// Convert the string data to rectangles
RectangleConverter rectConv = new RectangleConverter();
string form1pos = data.Substring(1, data.IndexOf("~", 1) - 1);
_form1Position = (Rectangle)rectConv.ConvertFromString(form1pos);
string form2pos = data.Substring(data.IndexOf("~", 1) + 1);
_form2Position = (Rectangle)rectConv.ConvertFromString(form2pos);
return true;
}
catch
{
// Error occurred while attempting to convert the rectangle data.
// Return false to use default values.
return false;
}
}
else
{
// No data in the file, return false to use default values.
return false;
}
}
//<Snippet4>
[STAThread]
static void Main(string[] args)
{
// Create the MyApplicationContext, that derives from ApplicationContext,
// that manages when the application should exit.
MyApplicationContext context = new MyApplicationContext();
// Run the application with the specific context. It will exit when
// all forms are closed.
Application.Run(context);
}
//</Snippet4>
}
//</Snippet2>
}
//</Snippet1>
@@ -0,0 +1,75 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{37FC2D7B-9F35-4D66-8CD2-C76F7E242552}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ApplicationSettingsArchitectureCS</RootNamespace>
<AssemblyName>ApplicationSettingsArchitectureCS</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DummyClass.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,44 @@
//<SNIPPET1>
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace ApplicationSettingsArchitectureCS
{
[SettingsProvider("SqlSettingsProvider")]
class CustomSettings : ApplicationSettingsBase
{
// Implementation goes here.
}
}
//</SNIPPET1>
namespace ApplicationSettingsArchitectureCS
{
public abstract class DummySettingsBase
{
public abstract string ApplicationName
{
get;
set;
}
}
public class DummySettings : DummySettingsBase
{
//<SNIPPET2>
public override string ApplicationName
{
get
{
return (System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
}
set
{
// Do nothing.
}
}
//</SNIPPET2>
}
}
@@ -0,0 +1,39 @@
namespace ApplicationSettingsArchitectureCS
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ApplicationSettingsArchitectureCS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ApplicationSettingsArchitectureCS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ApplicationSettingsArchitectureCS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ApplicationSettingsArchitectureCS")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2005")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("36af196a-a168-42a6-a697-3ae9594bb79b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ApplicationSettingsArchitectureCS.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ApplicationSettingsArchitectureCS.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ApplicationSettingsArchitectureCS.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,79 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5C6D141F-0E63-486F-AEB3-E6766F89B6CB}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AppSettingsArchitectureProject</RootNamespace>
<AssemblyName>AppSettingsArchitectureProject</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="MyAppSettings.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<SubType>Designer</SubType>
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,87 @@
namespace AppSettingsArchitectureProject
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.button1 = new System.Windows.Forms.Button();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(72, 61);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
this.statusStrip1.Location = new System.Drawing.Point(0, 251);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(292, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(109, 17);
this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
}
}
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace AppSettingsArchitectureProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
//<SNIPPET3>
//Make sure to hook up this event handler in the constructor!
//this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mus.Save();
}
//</SNIPPET3>
private void button1_Click(object sender, EventArgs e)
{
mus.BackgroundColor = Color.Black;
}
//<SNIPPET2>
MyUserSettings mus;
private void Form1_Load(object sender, EventArgs e)
{
mus = new MyUserSettings();
mus.BackgroundColor = Color.AliceBlue;
this.DataBindings.Add(new Binding("BackColor", mus, "BackgroundColor"));
}
//</SNIPPET2>
}
}
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="statusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
@@ -0,0 +1,22 @@
//<SNIPPET1>
using System;
using System.Configuration;
using System.Drawing;
public class MyUserSettings : ApplicationSettingsBase
{
[UserScopedSetting()]
[DefaultSettingValue("white")]
public Color BackgroundColor
{
get
{
return ((Color)this["BackgroundColor"]);
}
set
{
this["BackgroundColor"] = (Color)value;
}
}
}
//</SNIPPET1>
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace AppSettingsArchitectureProject
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AppSettingsArchitectureProject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AppSettingsArchitectureProject")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2005")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("37cc6737-2577-424e-b0c9-b1b02d9c6333")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AppSettingsArchitectureProject.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AppSettingsArchitectureProject.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AppSettingsArchitectureProject.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,58 @@
namespace DisplayWebBrowserCode
{
partial class CodeForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(0, 0);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(776, 651);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// CodeForm
//
this.ClientSize = new System.Drawing.Size(776, 651);
this.Controls.Add(this.richTextBox1);
this.Name = "CodeForm";
this.Text = "HTML Source Code Window";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
}
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DisplayWebBrowserCode
{
partial class CodeForm : Form
{
public CodeForm()
{
InitializeComponent();
}
//<SNIPPET1>
public string Code
{
get
{
if (richTextBox1.Text != null)
{
return (richTextBox1.Text);
}
else
{
return ("");
}
}
set
{
richTextBox1.Text = value;
}
}
//</SNIPPET1>
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,76 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.41025</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A1758485-65E5-4E5D-B57A-50F9B2838D3D}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>DisplayWebBrowserCode</RootNamespace>
<AssemblyName>DisplayWebBrowserCode</AssemblyName>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="CodeForm.Designer.cs">
<DependentUpon>CodeForm.cs</DependentUpon>
</Compile>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="CodeForm.resx">
<DependentUpon>CodeForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.cs</LastGenOutput>
</EmbeddedResource>
<Compile Include="Properties\Resources.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSHARP.Targets" />
</Project>
@@ -0,0 +1,67 @@
namespace DisplayWebBrowserCode
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.webBrowser1 = new System.Windows.Forms.WebBrowser();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// webBrowser1
//
this.webBrowser1.Location = new System.Drawing.Point(12, 250);
this.webBrowser1.Name = "webBrowser1";
this.webBrowser1.Size = new System.Drawing.Size(744, 382);
this.webBrowser1.Url = new System.Uri("http://www.msn.com/");
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(768, 644);
this.Controls.Add(this.button1);
this.Controls.Add(this.webBrowser1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser webBrowser1;
private System.Windows.Forms.Button button1;
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace DisplayWebBrowserCode
{
partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//<SNIPPET2>
private void button1_Click(object sender, EventArgs e)
{
HtmlElement elem;
if (webBrowser1.Document != null)
{
CodeForm cf = new CodeForm();
HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("HTML");
if (elems.Count == 1)
{
elem = elems[0];
cf.Code = elem.OuterHtml;
cf.Show();
}
}
}
//</SNIPPET2>
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DisplayWebBrowserCode
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DisplayWebBrowserCode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MS")]
[assembly: AssemblyProduct("DisplayWebBrowserCode")]
[assembly: AssemblyCopyright("Copyright @ MS 2004")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6b24619b-1c02-4b9b-a282-7aaa133b26a9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.41025.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace DisplayWebBrowserCode.Properties
{
using System;
using System.IO;
using System.Resources;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the Strongly Typed Resource Builder
// class via a tool like ResGen or Visual Studio.NET.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
class Resources
{
private static System.Resources.ResourceManager _resMgr;
private static System.Globalization.CultureInfo _resCulture;
/*FamANDAssem*/
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static System.Resources.ResourceManager ResourceManager
{
get
{
if ((_resMgr == null))
{
System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly);
_resMgr = temp;
}
return _resMgr;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static System.Globalization.CultureInfo Culture
{
get
{
return _resCulture;
}
set
{
_resCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,42 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.41025.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace DisplayWebBrowserCode.Properties
{
public partial class Settings : System.Configuration.ApplicationSettingsBase
{
private static Settings m_Value;
private static object m_SyncObject = new object();
public static Settings Value
{
get
{
if ((Settings.m_Value == null))
{
System.Threading.Monitor.Enter(Settings.m_SyncObject);
if ((Settings.m_Value == null))
{
try
{
Settings.m_Value = new Settings();
}
finally
{
System.Threading.Monitor.Exit(Settings.m_SyncObject);
}
}
}
return Settings.m_Value;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='iso-8859-1'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,324 @@
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
public class LinesCurvesAndShapes : Form
{
// 0195df81-66be-452d-bb53-5a582ebfdc09
// Vector Graphics Overview
Pen myPen = Pens.Black;
SolidBrush mySolidBrush = (SolidBrush)Brushes.Red;
GraphicsPath myGraphicsPath = new GraphicsPath();
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new LinesCurvesAndShapes());
}
public void Method11(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet11>
myGraphics.DrawRectangle(myPen, 20, 10, 100, 50);
// </snippet11>
}
// 08d2cc9a-dc9d-4eed-bcbb-2c8e2ca5d3ae
// Open and Closed Curves in GDI+
public void Method21(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet21>
myGraphics.FillPie(mySolidBrush, 0, 0, 140, 70, 0, 120);
myGraphics.DrawArc(myPen, 0, 0, 140, 70, 0, 120);
// </snippet21>
}
public void Method22(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet22>
Point[] myPointArray =
{
new Point(0, 0),
new Point(60, 20),
new Point(40, 50)
};
myGraphics.DrawClosedCurve(myPen, myPointArray);
myGraphics.FillClosedCurve(mySolidBrush, myPointArray);
// </snippet22>
}
public void Method23(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet23>
SolidBrush mySolidBrush = new SolidBrush(Color.Aqua);
GraphicsPath myGraphicsPath = new GraphicsPath();
Point[] myPointArray =
{
new Point(15, 20),
new Point(20, 40),
new Point(50, 30)
};
FontFamily myFontFamily = new FontFamily("Times New Roman");
PointF myPointF = new PointF(50, 20);
StringFormat myStringFormat = new StringFormat();
myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180);
myGraphicsPath.AddCurve(myPointArray);
myGraphicsPath.AddString("a string in a path", myFontFamily,
0, 24, myPointF, myStringFormat);
myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110);
myGraphics.FillPath(mySolidBrush, myGraphicsPath);
myGraphics.DrawPath(myPen, myGraphicsPath);
// </snippet23>
}
// 09b3797a-6294-422d-9adf-a5a0a7695c0c
// Cardinal Splines in GDI+
public void Method31(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
Point[] myPointArray =
{
new Point(10, 10),
new Point(50, 40),
new Point(123, 200)
};
// <snippet31>
myGraphics.DrawCurve(myPen, myPointArray, 1.5f);
// </snippet31>
}
// 30b25aae-e3eb-4479-bdb8-187cf651fc84
// Pens, Lines, and Rectangles in GDI+
public void Method41(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet41>
myGraphics.DrawLine(myPen, 4, 2, 12, 6);
// </snippet41>
}
public void Method42(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet42>
Point myStartPoint = new Point(4, 2);
Point myEndPoint = new Point(12, 6);
myGraphics.DrawLine(myPen, myStartPoint, myEndPoint);
// </snippet42>
}
public void Method43(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet43>
Pen myPen = new Pen(Color.Blue, 2);
myGraphics.DrawLine(myPen, 0, 0, 60, 30);
// </snippet43>
}
public void Method44(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet44>
myPen.DashStyle = DashStyle.Dash;
myGraphics.DrawLine(myPen, 100, 50, 300, 80);
// </snippet44>
}
public void Method45(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet45>
myGraphics.DrawRectangle(myPen, 100, 50, 80, 40);
// </snippet45>
}
public void Method46(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet46>
Rectangle myRectangle = new Rectangle(100, 50, 80, 40);
myGraphics.DrawRectangle(myPen, myRectangle);
// </snippet46>
}
// 34f35133-a835-4ca4-81f6-0dfedee8b683
// Ellipses and Arcs in GDI+
public void Method51(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet51>
myGraphics.DrawEllipse(myPen, 100, 50, 80, 40);
// </snippet51>
}
public void Method52(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet52>
Rectangle myRectangle = new Rectangle(100, 50, 80, 40);
myGraphics.DrawEllipse(myPen, myRectangle);
// </snippet52>
}
public void Method53(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet53>
myGraphics.DrawArc(myPen, 100, 50, 140, 70, 30, 180);
// </snippet53>
}
// 52184f9b-16dd-4bbd-85be-029112644ceb
// Regions in GDI+
public void Method61(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
Region myRegion = new Region(this.ClientRectangle);
// <snippet61>
myGraphics.FillRegion(mySolidBrush, myRegion);
// </snippet61>
}
// 5774ce1e-87d4-4bc7-88c4-4862052781b8
// Bézier Splines in GDI+
public void Method71(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet71>
myGraphics.DrawBezier(myPen, 0, 0, 40, 20, 80, 150, 100, 10);
// </snippet71>
}
// 810da1a4-c136-4abf-88df-68e49efdd8d4
// Antialiasing with Lines and Curves
public void Method81(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet81>
myGraphics.SmoothingMode = SmoothingMode.AntiAlias;
myGraphics.DrawLine(myPen, 0, 0, 12, 8);
// </snippet81>
}
// 8b5f71d9-d2f0-4540-9c41-740f90fd4c26
// Restricting the Drawing Surface in GDI+
public void Method91(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
Region myRegion = new Region(this.ClientRectangle);
// <snippet91>
myGraphics.Clip = myRegion;
myGraphics.DrawLine(myPen, 0, 0, 200, 200);
// </snippet91>
}
// a5500dec-666c-41fd-9da3-2169dd89c5eb
// Graphics Paths in GDI+
public void Method101(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet101>
myGraphicsPath.AddLine(0, 0, 30, 20);
myGraphicsPath.AddEllipse(20, 20, 20, 40);
myGraphicsPath.AddBezier(30, 60, 70, 60, 50, 30, 100, 10);
myGraphics.DrawPath(myPen, myGraphicsPath);
// </snippet101>
}
public void Method102()
{
GraphicsPath graphicsPath1 = new GraphicsPath();
GraphicsPath graphicsPath2 = new GraphicsPath();
// <snippet102>
myGraphicsPath.AddPath(graphicsPath1, false);
myGraphicsPath.AddPath(graphicsPath2, false);
// </snippet102>
}
public void Method103(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet103>
GraphicsPath myGraphicsPath = new GraphicsPath();
Point[] myPointArray =
{
new Point(5, 30),
new Point(20, 40),
new Point(50, 30)
};
FontFamily myFontFamily = new FontFamily("Times New Roman");
PointF myPointF = new PointF(50, 20);
StringFormat myStringFormat = new StringFormat();
myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180);
myGraphicsPath.StartFigure();
myGraphicsPath.AddCurve(myPointArray);
myGraphicsPath.AddString("a string in a path", myFontFamily,
0, 24, myPointF, myStringFormat);
myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110);
myGraphics.DrawPath(myPen, myGraphicsPath);
// </snippet103>
}
// a72213d2-d69a-4c2b-a75c-be7b20390c13
// Polygons in GDI+
public void Method111(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet111>
Point[] myPointArray =
{
new Point(0, 0),
new Point(50, 30),
new Point(30, 60)
};
myGraphics.DrawPolygon(myPen, myPointArray);
// </snippet111>
}
// e863e2a7-0294-4130-99b6-f1ea3201e7cd
// Brushes and Filled Shapes in GDI+
public void Method121(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet121>
SolidBrush mySolidBrush = new SolidBrush(Color.Red);
myGraphics.FillEllipse(mySolidBrush, 0, 0, 60, 40);
// </snippet121>
}
public void Method122()
{
// <snippet122>
HatchBrush myHatchBrush =
new HatchBrush(HatchStyle.Vertical, Color.Blue, Color.Green);
// </snippet122>
}
public void Method123(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
// <snippet123>
Image myImage = Image.FromFile("MyTexture.bmp");
TextureBrush myTextureBrush = new TextureBrush(myImage);
myGraphics.FillEllipse(myTextureBrush, 0, 0, 100, 50);
// </snippet123>
}
public void Method124(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
Rectangle myRectangle = new Rectangle(new Point(10, 10), new Size(40, 50));
// <snippet124>
LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush(
myRectangle,
Color.Blue,
Color.Green,
LinearGradientMode.Horizontal);
myGraphics.FillEllipse(myLinearGradientBrush, myRectangle);
// </snippet124>
}
}
@@ -0,0 +1,61 @@
namespace ManagedDOMStyles
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.webBrowser1 = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
//
// webBrowser1
//
this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser1.Location = new System.Drawing.Point(0, 0);
this.webBrowser1.Name = "webBrowser1";
this.webBrowser1.Size = new System.Drawing.Size(742, 318);
this.webBrowser1.Url = new System.Uri("c:\\userfiles\\jayallen\\ManagedDOMStyles\\test.htm", System.UriKind.Absolute);
this.webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(742, 318);
this.Controls.Add(this.webBrowser1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser webBrowser1;
}
}
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;
namespace ManagedDOMStyles
{
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
//<SNIPPET2>
StyleGenerator sg = null;
HtmlElement elem = null;
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
sg = new StyleGenerator();
webBrowser1.Document.MouseOver += new HtmlElementEventHandler(Document_MouseOver);
webBrowser1.Document.MouseLeave += new HtmlElementEventHandler(Document_MouseLeave);
}
void Document_MouseOver(object sender, HtmlElementEventArgs e)
{
elem = webBrowser1.Document.GetElementFromPoint(e.MousePosition);
if (elem.TagName.Equals("DIV"))
{
sg.ParseStyleString(elem.Style);
sg.SetStyle("font-style", "italic");
elem.Style = sg.GetStyleString();
}
}
void Document_MouseLeave(object sender, HtmlElementEventArgs e)
{
if (elem != null)
{
sg.RemoveStyle("font-style");
elem.Style = sg.GetStyleString();
// Reset, since we may mouse over a new DIV element next time.
sg.Clear();
}
}
//</SNIPPET2>
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,71 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50304</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6531B7A2-E512-4AC0-A5BF-4A41259FE13D}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ManagedDOMStyles</RootNamespace>
<AssemblyName>ManagedDOMStyles</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="StyleGenerator.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ManagedDOMStyles
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
@@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ManagedDOMStyles")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MS")]
[assembly: AssemblyProduct("ManagedDOMStyles")]
[assembly: AssemblyCopyright("Copyright © MS 2005")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("401692d3-2767-47ab-a9d5-9213495a5054")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,74 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.50304.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Resources.get_ResourceManager():System.Resources.ResourceManager")]
[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Resources.get_Culture():System.Globalization.CultureInfo")]
[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Resources.set_Culture(System.Globalization.CultureInfo):Void")]
namespace ManagedDOMStyles.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ManagedDOMStyles.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,31 @@
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version:2.0.50304.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
[assembly: global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "ManagedDOMStyles.Properties.Settings.get_Default():ManagedDOMStyles.Properties.Settings")]
namespace ManagedDOMStyles.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = new Settings();
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,113 @@
//<SNIPPET1>
using System;
using System.Collections.Generic;
using System.Text;
namespace ManagedDOMStyles
{
public class StyleGenerator
{
private Dictionary<string, string> styleDB;
public StyleGenerator()
{
styleDB = new Dictionary<string, string>();
}
public bool ContainsStyle(string name)
{
return(styleDB.ContainsKey(name));
}
public string SetStyle(string name, string value)
{
string oldValue = "";
if (!(name.Length > 0))
{
throw (new ArgumentException("Parameter name cannot be zero-length."));
}
if (!(value.Length > 0))
{
throw (new ArgumentException("Parameter value cannot be zero-length."));
}
if (styleDB.ContainsKey(name))
{
oldValue = styleDB[name];
}
styleDB[name] = value;
return (oldValue);
}
public string GetStyle(string name)
{
if (!(name.Length > 0))
{
throw (new ArgumentException("Parameter name cannot be zero-length."));
}
if (styleDB.ContainsKey(name))
{
return (styleDB[name]);
}
else
{
return ("");
}
}
public void RemoveStyle(string name)
{
if (styleDB.ContainsKey(name))
{
styleDB.Remove(name);
}
}
public string GetStyleString()
{
if (styleDB.Count > 0)
{
StringBuilder styleString = new StringBuilder("");
foreach (string key in styleDB.Keys)
{
styleString.Append(String.Format("{0}:{1};", (object)key, (object)styleDB[key]));
}
return (styleString.ToString());
}
else
{
return ("");
}
}
public void ParseStyleString(string styles)
{
if (styles.Length > 0)
{
string[] stylePairs = styles.Split(new char[] { ';' });
foreach(string stylePair in stylePairs)
{
if (stylePairs.Length > 0)
{
string[] styleNameValue = stylePair.Split(new char[] { ':' });
if (styleNameValue.Length == 2)
{
styleDB[styleNameValue[0]] = styleNameValue[1];
}
}
}
}
}
public void Clear()
{
styleDB.Clear();
}
}
}
//</SNIPPET1>
@@ -0,0 +1,100 @@
namespace MaskedTextBoxDataCSharp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing && (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.firstName = new System.Windows.Forms.TextBox();
this.lastName = new System.Windows.Forms.TextBox();
this.phoneMask = new System.Windows.Forms.MaskedTextBox();
this.previousButton = new System.Windows.Forms.Button();
this.nextButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// firstName
//
this.firstName.Location = new System.Drawing.Point(13, 14);
this.firstName.Name = "firstName";
this.firstName.Size = new System.Drawing.Size(184, 20);
this.firstName.TabIndex = 0;
//
// lastName
//
this.lastName.Location = new System.Drawing.Point(204, 14);
this.lastName.Name = "lastName";
this.lastName.Size = new System.Drawing.Size(184, 20);
this.lastName.TabIndex = 1;
//
// phoneMask
//
this.phoneMask.Location = new System.Drawing.Point(441, 14);
this.phoneMask.Mask = "(009) 000-0000 x9999";
this.phoneMask.Name = "phoneMask";
this.phoneMask.Size = new System.Drawing.Size(169, 20);
this.phoneMask.TabIndex = 2;
//
// previousButton
//
this.previousButton.Location = new System.Drawing.Point(630, 14);
this.previousButton.Name = "previousButton";
this.previousButton.TabIndex = 3;
this.previousButton.Text = "Previous";
this.previousButton.Click += new System.EventHandler(this.previousButton_Click);
//
// nextButton
//
this.nextButton.Location = new System.Drawing.Point(723, 14);
this.nextButton.Name = "nextButton";
this.nextButton.TabIndex = 4;
this.nextButton.Text = "Next";
this.nextButton.Click += new System.EventHandler(this.nextButton_Click);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(887, 46);
this.Controls.Add(this.nextButton);
this.Controls.Add(this.previousButton);
this.Controls.Add(this.phoneMask);
this.Controls.Add(this.lastName);
this.Controls.Add(this.firstName);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox firstName;
private System.Windows.Forms.TextBox lastName;
private System.Windows.Forms.MaskedTextBox phoneMask;
private System.Windows.Forms.Button previousButton;
private System.Windows.Forms.Button nextButton;
}
}
@@ -0,0 +1,23 @@
#region Using directives
using System;
using System.Collections.Generic;
using System.Windows.Forms;
#endregion
namespace MaskedTextBoxDataCSharp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
@@ -0,0 +1,118 @@
//<SNIPPET1>
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
#endregion
namespace MaskedTextBoxDataCSharp
{
partial class Form1 : Form
{
Binding currentBinding, phoneBinding;
DataSet employeesTable = new DataSet();
SqlConnection sc;
SqlDataAdapter dataConnect;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DoMaskBinding();
}
private void DoMaskBinding()
{
try
{
sc = new SqlConnection("Data Source=localhost;Initial Catalog=NORTHWIND;Integrated Security=SSPI");
sc.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
dataConnect = new SqlDataAdapter("SELECT * FROM Employees", sc);
dataConnect.Fill(employeesTable, "Employees");
// Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects
// before adding them to the control - otherwise, we won't get a Format event on the
// initial load.
try
{
currentBinding = new Binding("Text", employeesTable, "Employees.FirstName");
firstName.DataBindings.Add(currentBinding);
currentBinding = new Binding("Text", employeesTable, "Employees.LastName");
lastName.DataBindings.Add(currentBinding);
phoneBinding =new Binding("Text", employeesTable, "Employees.HomePhone");
// We must add the event handlers before we bind, or the Format event will not get called
// for the first record.
phoneBinding.Format += new ConvertEventHandler(phoneBinding_Format);
phoneBinding.Parse += new ConvertEventHandler(phoneBinding_Parse);
phoneMask.DataBindings.Add(phoneBinding);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void phoneBinding_Format(Object sender, ConvertEventArgs e)
{
String ext;
DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current;
if (currentRow["Extension"] == null)
{
ext = "";
} else
{
ext = currentRow["Extension"].ToString();
}
e.Value = e.Value.ToString().Trim() + " x" + ext;
}
private void phoneBinding_Parse(Object sender, ConvertEventArgs e)
{
String phoneNumberAndExt = e.Value.ToString();
int extIndex = phoneNumberAndExt.IndexOf("x");
String ext = phoneNumberAndExt.Substring(extIndex).Trim();
String phoneNumber = phoneNumberAndExt.Substring(0, extIndex).Trim();
//Get the current binding object, and set the new extension manually.
DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current;
// Remove the "x" from the extension.
currentRow["Extension"] = ext.Substring(1);
//Return the phone number.
e.Value = phoneNumber;
}
private void previousButton_Click(object sender, EventArgs e)
{
BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position - 1;
}
private void nextButton_Click(object sender, EventArgs e)
{
BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position + 1;
}
}
}
//</SNIPPET1>
@@ -0,0 +1,2 @@
all:
csc /t:library /out:mydll.dll Form1.Designer.cs Program.cs form1.cs
@@ -0,0 +1,632 @@
// <snippet1>
// <snippet2>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
// </snippet2>
// This sample demonstrates the use of various attributes for
// authoring a control.
namespace AttributesDemoControlLibrary
{
// This is the event handler delegate for the ThresholdExceeded event.
public delegate void ThresholdExceededEventHandler(ThresholdExceededEventArgs e);
// <snippet3>
// <snippet20>
// This control demonstrates a simple logging capability.
[ComplexBindingProperties("DataSource", "DataMember")]
[DefaultBindingProperty("TitleText")]
[DefaultEvent("ThresholdExceeded")]
[DefaultProperty("Threshold")]
[HelpKeywordAttribute(typeof(UserControl))]
[ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")]
public class AttributesDemoControl : UserControl
{
// </snippet20>
// This backs the Threshold property.
private object thresholdValue;
// The default fore color value for DataGridView cells that
// contain values that exceed the threshold.
private static Color defaultAlertForeColorValue = Color.White;
// The default back color value for DataGridView cells that
// contain values that exceed the threshold.
private static Color defaultAlertBackColorValue = Color.Red;
// The ambient color value.
private static Color ambientColorValue = Color.Empty;
// The fore color value for DataGridView cells that
// contain values that exceed the threshold.
private Color alertForeColorValue = defaultAlertForeColorValue;
// The back color value for DataGridView cells that
// contain values that exceed the threshold.
private Color alertBackColorValue = defaultAlertBackColorValue;
// Child controls that comprise this UserControl.
private TableLayoutPanel tableLayoutPanel1;
private DataGridView dataGridView1;
private Label label1;
// Required for designer support.
private System.ComponentModel.IContainer components = null;
// Default constructor.
public AttributesDemoControl()
{
InitializeComponent();
}
// <snippet21>
[Category("Appearance")]
[Description("The title of the log data.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Localizable(true)]
[HelpKeywordAttribute("AttributesDemoControlLibrary.AttributesDemoControl.TitleText")]
public string TitleText
{
get
{
return this.label1.Text;
}
set
{
this.label1.Text = value;
}
}
// </snippet21>
// <snippet22>
// The inherited Text property is hidden at design time and
// raises an exception at run time. This enforces a requirement
// that client code uses the TitleText property instead.
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override string Text
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
// </snippet22>
// <snippet23>
[AmbientValue(typeof(Color), "Empty")]
[Category("Appearance")]
[DefaultValue(typeof(Color), "White")]
[Description("The color used for painting alert text.")]
public Color AlertForeColor
{
get
{
if (this.alertForeColorValue == Color.Empty &&
this.Parent != null)
{
return Parent.ForeColor;
}
return this.alertForeColorValue;
}
set
{
this.alertForeColorValue = value;
}
}
// This method is used by designers to enable resetting the
// property to its default value.
public void ResetAlertForeColor()
{
this.AlertForeColor = AttributesDemoControl.defaultAlertForeColorValue;
}
// This method indicates to designers whether the property
// value is different from the ambient value, in which case
// the designer should persist the value.
private bool ShouldSerializeAlertForeColor()
{
return (this.alertForeColorValue != AttributesDemoControl.ambientColorValue);
}
// </snippet23>
// <snippet24>
[AmbientValue(typeof(Color), "Empty")]
[Category("Appearance")]
[DefaultValue(typeof(Color), "Red")]
[Description("The background color for painting alert text.")]
public Color AlertBackColor
{
get
{
if (this.alertBackColorValue == Color.Empty &&
this.Parent != null)
{
return Parent.BackColor;
}
return this.alertBackColorValue;
}
set
{
this.alertBackColorValue = value;
}
}
// This method is used by designers to enable resetting the
// property to its default value.
public void ResetAlertBackColor()
{
this.AlertBackColor = AttributesDemoControl.defaultAlertBackColorValue;
}
// This method indicates to designers whether the property
// value is different from the ambient value, in which case
// the designer should persist the value.
private bool ShouldSerializeAlertBackColor()
{
return (this.alertBackColorValue != AttributesDemoControl.ambientColorValue);
}
// </snippet24>
// <snippet25>
[Category("Data")]
[Description("Indicates the source of data for the control.")]
[RefreshProperties(RefreshProperties.Repaint)]
[AttributeProvider(typeof(IListSource))]
public object DataSource
{
get
{
return this.dataGridView1.DataSource;
}
set
{
this.dataGridView1.DataSource = value;
}
}
// </snippet25>
// <snippet26>
[Category("Data")]
[Description("Indicates a sub-list of the data source to show in the control.")]
public string DataMember
{
get
{
return this.dataGridView1.DataMember;
}
set
{
this.dataGridView1.DataMember = value;
}
}
// </snippet26>
// <snippet27>
// This property would normally have its BrowsableAttribute
// set to false, but this code demonstrates using
// ReadOnlyAttribute, so BrowsableAttribute is true to show
// it in any attached PropertyGrid control.
[Browsable(true)]
[Category("Behavior")]
[Description("The timestamp of the latest entry.")]
[ReadOnly(true)]
public DateTime CurrentLogTime
{
get
{
int lastRowIndex =
this.dataGridView1.Rows.GetLastRow(
DataGridViewElementStates.Visible);
if (lastRowIndex > -1)
{
DataGridViewRow lastRow = this.dataGridView1.Rows[lastRowIndex];
DataGridViewCell lastCell = lastRow.Cells["EntryTime"];
return ((DateTime)lastCell.Value);
}
else
{
return DateTime.MinValue;
}
}
set
{
}
}
// </snippet27>
// <snippet28>
[Category("Behavior")]
[Description("The value above which the ThresholdExceeded event will be raised.")]
public object Threshold
{
get
{
return this.thresholdValue;
}
set
{
this.thresholdValue = value;
}
}
// </snippet28>
// <snippet29>
// This property exists only to demonstrate the
// PasswordPropertyText attribute. When this control
// is attached to a PropertyGrid control, the returned
// string will be displayed with obscuring characters
// such as asterisks. This property has no other effect.
[Category("Security")]
[Description("Demonstrates PasswordPropertyTextAttribute.")]
[PasswordPropertyText(true)]
public string Password
{
get
{
return "This is a demo password.";
}
}
// </snippet29>
// <snippet30>
// This property exists only to demonstrate the
// DisplayName attribute. When this control
// is attached to a PropertyGrid control, the
// property will be appear as "RenamedProperty"
// instead of "MisnamedProperty".
[Description("Demonstrates DisplayNameAttribute.")]
[DisplayName("RenamedProperty")]
public bool MisnamedProperty
{
get
{
return true;
}
}
// </snippet30>
// This is the declaration for the ThresholdExceeded event.
public event ThresholdExceededEventHandler ThresholdExceeded;
#region Implementation
// <snippet31>
// This is the event handler for the DataGridView control's
// CellFormatting event. Handling this event allows the
// AttributesDemoControl to examine the incoming log entries
// from the data source as they arrive.
//
// If the cell for which this event is raised holds the
// log entry's timestamp, the cell value is formatted with
// the full date/time pattern.
//
// Otherwise, the cell's value is assumed to hold the log
// entry value. If the value exceeds the threshold value,
// the cell is painted with the colors specified by the
// AlertForeColor and AlertBackColor properties, after which
// the ThresholdExceeded is raised. For this comparison to
// succeed, the log entry's type must implement the IComparable
// interface.
private void dataGridView1_CellFormatting(
object sender,
DataGridViewCellFormattingEventArgs e)
{
try
{
if (e.Value != null)
{
if (e.Value is DateTime)
{
// Display the log entry time with the
// full date/time pattern (long time).
e.CellStyle.Format = "F";
}
else
{
// Scroll to the most recent entry.
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
DataGridViewCell cell = row.Cells[e.ColumnIndex];
this.dataGridView1.FirstDisplayedCell = cell;
if (this.thresholdValue != null)
{
// Get the type of the log entry.
object val = e.Value;
Type paramType = val.GetType();
// Compare the log entry value to the threshold value.
// Use reflection to call the CompareTo method on the
// template parameter's type.
int compareVal = (int)paramType.InvokeMember(
"CompareTo",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
e.Value,
new object[] { this.thresholdValue },
System.Globalization.CultureInfo.InvariantCulture);
// If the log entry value exceeds the threshold value,
// set the cell's fore color and back color properties
// and raise the ThresholdExceeded event.
if (compareVal > 0)
{
e.CellStyle.BackColor = this.alertBackColorValue;
e.CellStyle.ForeColor = this.alertForeColorValue;
ThresholdExceededEventArgs teea =
new ThresholdExceededEventArgs(
this.thresholdValue,
e.Value);
this.ThresholdExceeded(teea);
}
}
}
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
// </snippet31>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.label1 = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.AutoSize = true;
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(10, 10);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10);
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(425, 424);
this.tableLayoutPanel1.TabIndex = 0;
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToOrderColumns = true;
this.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridView1.ColumnHeadersHeight = 4;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(13, 57);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.Size = new System.Drawing.Size(399, 354);
this.dataGridView1.TabIndex = 1;
this.dataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dataGridView1_CellFormatting);
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.SystemColors.Control;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Location = new System.Drawing.Point(13, 13);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(399, 38);
this.label1.TabIndex = 2;
this.label1.Text = "label1";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// AttributesDemoControl
//
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "AttributesDemoControl";
this.Padding = new System.Windows.Forms.Padding(10);
this.Size = new System.Drawing.Size(445, 444);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
// </snippet3>
// <snippet4>
// This is the EventArgs class for the ThresholdExceeded event.
public class ThresholdExceededEventArgs : EventArgs
{
private object thresholdValue = null;
private object exceedingValue = null;
public ThresholdExceededEventArgs(
object thresholdValue,
object exceedingValue)
{
this.thresholdValue = thresholdValue;
this.exceedingValue = exceedingValue;
}
public object ThresholdValue
{
get
{
return this.thresholdValue;
}
}
public object ExceedingValue
{
get
{
return this.exceedingValue;
}
}
}
// </snippet4>
// <snippet5>
// This class encapsulates a log entry. It is a parameterized
// type (also known as a template class). The parameter type T
// defines the type of data being logged. For threshold detection
// to work, this type must implement the IComparable interface.
[TypeConverter("LogEntryTypeConverter")]
public class LogEntry<T> where T : IComparable
{
private T entryValue;
private DateTime entryTimeValue;
public LogEntry(
T value,
DateTime time)
{
this.entryValue = value;
this.entryTimeValue = time;
}
public T Entry
{
get
{
return this.entryValue;
}
}
public DateTime EntryTime
{
get
{
return this.entryTimeValue;
}
}
// <snippet6>
// This is the TypeConverter for the LogEntry class.
public class LogEntryTypeConverter : TypeConverter
{
// <snippet7>
public override bool CanConvertFrom(
ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
// </snippet7>
// <snippet8>
public override object ConvertFrom(
ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value)
{
if (value is string)
{
string[] v = ((string)value).Split(new char[] { '|' });
Type paramType = typeof(T);
T entryValue = (T)paramType.InvokeMember(
"Parse",
BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod,
null,
null,
new string[] { v[0] },
culture);
return new LogEntry<T>(
entryValue,
DateTime.Parse(v[2]));
}
return base.ConvertFrom(context, culture, value);
}
// </snippet8>
// <snippet9>
public override object ConvertTo(
ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value,
Type destinationType)
{
if (destinationType == typeof(string))
{
LogEntry<T> le = value as LogEntry<T>;
string stringRepresentation =
String.Format("{0} | {1}",
le.Entry,
le.EntryTime);
return stringRepresentation;
}
return base.ConvertTo(context, culture, value, destinationType);
}
// </snippet9>
}
// </snippet6>
}
// </snippet5>
}
// </snippet1>
@@ -0,0 +1,284 @@
// <snippet100>
// <snippet101>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using AttributesDemoControlLibrary;
// </snippet101>
// This sample demonstrates using the AttributesDemoControl to log
// data from a data source.
namespace AttributesDemoControlTest
{
public class Form1 : Form
{
private BindingSource bindingSource1;
private System.Diagnostics.PerformanceCounter performanceCounter1;
private Button startButton;
private Button stopButton;
private System.Timers.Timer timer1;
private ToolStripStatusLabel statusStripPanel1;
private NumericUpDown numericUpDown1;
private GroupBox groupBox1;
private GroupBox groupBox2;
private TableLayoutPanel tableLayoutPanel1;
private AttributesDemoControl attributesDemoControl1;
private System.ComponentModel.IContainer components = null;
// This form uses an AttributesDemoControl to display a stream
// of LogEntry objects. The data stream is generated by polling
// a performance counter and communicating the counter values
// to the control with data binding.
public Form1()
{
InitializeComponent();
// Set the initial value of the threshold up/down control
// to the control's threshold value.
this.numericUpDown1.Value =
(decimal)(float)this.attributesDemoControl1.Threshold;
// Assign the performance counter's name to the control's
// title text.
this.attributesDemoControl1.TitleText =
this.performanceCounter1.CounterName;
}
// This method handles the ThresholdExceeded event. It posts
// the value that exceeded the threshold to the status strip.
private void attributesDemoControl1_ThresholdExceeded(
ThresholdExceededEventArgs e)
{
string msg = String.Format(
"{0}: Value {1} exceeded threshold {2}",
this.attributesDemoControl1.CurrentLogTime,
e.ExceedingValue,
e.ThresholdValue);
this.ReportStatus( msg );
}
// <snippet110>
// This method handles the timer's Elapsed event. It queries
// the performance counter for the next value, packs the
// value in a LogEntry object, and adds the new LogEntry to
// the list managed by the BindingSource.
private void timer1_Elapsed(
object sender,
System.Timers.ElapsedEventArgs e)
{
// Get the latest value from the performance counter.
float val = this.performanceCounter1.NextValue();
// The performance counter returns values of type float,
// but any type that implements the IComparable interface
// will work.
LogEntry<float> entry = new LogEntry<float>(val, DateTime.Now);
// Add the new LogEntry to the BindingSource list.
this.bindingSource1.Add(entry);
}
// </snippet110>
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
this.attributesDemoControl1.Threshold =
(float)this.numericUpDown1.Value;
string msg = String.Format(
"Threshold changed to {0}",
this.attributesDemoControl1.Threshold);
this.ReportStatus(msg);
}
private void startButton_Click(object sender, EventArgs e)
{
this.ReportStatus(DateTime.Now + ": Starting");
this.timer1.Start();
}
private void stopButton_Click(object sender, EventArgs e)
{
this.ReportStatus(DateTime.Now + ": Stopping");
this.timer1.Stop();
}
private void ReportStatus(string msg)
{
if (msg != null)
{
this.statusStripPanel1.Text = msg;
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
this.startButton = new System.Windows.Forms.Button();
this.stopButton = new System.Windows.Forms.Button();
this.timer1 = new System.Timers.Timer();
this.statusStripPanel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.attributesDemoControl1 = new AttributesDemoControlLibrary.AttributesDemoControl();
((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// performanceCounter1
//
this.performanceCounter1.CategoryName = ".NET CLR Memory";
this.performanceCounter1.CounterName = "Gen 0 heap size";
this.performanceCounter1.InstanceName = "_Global_";
//
// startButton
//
this.startButton.Location = new System.Drawing.Point(31, 25);
this.startButton.Name = "startButton";
this.startButton.TabIndex = 1;
this.startButton.Text = "Start";
this.startButton.Click += new System.EventHandler(this.startButton_Click);
//
// stopButton
//
this.stopButton.Location = new System.Drawing.Point(112, 25);
this.stopButton.Name = "stopButton";
this.stopButton.TabIndex = 2;
this.stopButton.Text = "Stop";
this.stopButton.Click += new System.EventHandler(this.stopButton_Click);
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.SynchronizingObject = this;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// statusStripPanel1
//
this.statusStripPanel1.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter;
this.statusStripPanel1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.statusStripPanel1.Name = "statusStripPanel1";
this.statusStripPanel1.Text = "Ready";
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(37, 29);
this.numericUpDown1.Maximum = new decimal(new int[] {
1410065408,
2,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.TabIndex = 7;
this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged);
//
// groupBox1
//
this.groupBox1.Anchor = System.Windows.Forms.AnchorStyles.None;
this.groupBox1.Controls.Add(this.numericUpDown1);
this.groupBox1.Location = new System.Drawing.Point(280, 326);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 70);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Threshold Value";
//
// groupBox2
//
this.groupBox2.Anchor = System.Windows.Forms.AnchorStyles.None;
this.groupBox2.Controls.Add(this.startButton);
this.groupBox2.Controls.Add(this.stopButton);
this.groupBox2.Location = new System.Drawing.Point(26, 327);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(214, 68);
this.groupBox2.TabIndex = 14;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Logging";
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Controls.Add(this.groupBox2, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.groupBox1, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.attributesDemoControl1, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10);
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(514, 411);
this.tableLayoutPanel1.TabIndex = 15;
//
// attributesDemoControl1
//
this.tableLayoutPanel1.SetColumnSpan(this.attributesDemoControl1, 2);
this.attributesDemoControl1.DataMember = "";
this.attributesDemoControl1.DataSource = this.bindingSource1;
this.attributesDemoControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.attributesDemoControl1.Location = new System.Drawing.Point(13, 13);
this.attributesDemoControl1.Name = "attributesDemoControl1";
this.attributesDemoControl1.Padding = new System.Windows.Forms.Padding(10);
this.attributesDemoControl1.Size = new System.Drawing.Size(488, 306);
this.attributesDemoControl1.TabIndex = 0;
this.attributesDemoControl1.Threshold = 200000F;
this.attributesDemoControl1.TitleText = "TITLE";
this.attributesDemoControl1.ThresholdExceeded += new AttributesDemoControlLibrary.ThresholdExceededEventHandler(this.attributesDemoControl1_ThresholdExceeded);
//
// Form1
//
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(514, 430);
this.Controls.Add(this.tableLayoutPanel1);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
// </snippet100>
@@ -0,0 +1,10 @@
all: AttributesDemoControl.dll form1.exe
AttributesDemoControl.dll: AttributesDemoControl.cs
csc /target:library AttributesDemoControl.cs
Form1.exe: AttributesDemoControl.dll
csc form1.cs /r:AttributesDemoControl.dll
clean:
del *.exe *.dll *.bin *.obj
@@ -0,0 +1,232 @@
// <snippet1>
// <snippet7>
using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
// </snippet7>
namespace BackgroundWorkerExample
{
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// <snippet2>
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
int arg = (int)e.Argument;
// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}
// </snippet2>
// <snippet3>
// This event handler demonstrates how to interpret
// the outcome of the asynchronous operation implemented
// in the DoWork event handler.
private void backgroundWorker1_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("Operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else
{
// The operation completed normally.
string msg = String.Format("Result = {0}", e.Result);
MessageBox.Show(msg);
}
}
// </snippet3>
// <snippet4>
// This method models an operation that may take a long time
// to run. It can be cancelled, it can raise an exception,
// or it can exit normally and return a result. These outcomes
// are chosen randomly.
private int TimeConsumingOperation(
BackgroundWorker bw,
int sleepPeriod )
{
int result = 0;
Random rand = new Random();
while (!bw.CancellationPending)
{
bool exit = false;
switch (rand.Next(3))
{
// Raise an exception.
case 0:
{
throw new Exception("An error condition occurred.");
break;
}
// Sleep for the number of milliseconds
// specified by the sleepPeriod parameter.
case 1:
{
Thread.Sleep(sleepPeriod);
break;
}
// Exit and return normally.
case 2:
{
result = 23;
exit = true;
break;
}
default:
{
break;
}
}
if( exit )
{
break;
}
}
return result;
}
// </snippet4>
// <snippet5>
private void startBtn_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync(2000);
}
// </snippet5>
// <snippet6>
private void cancelBtn_Click(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
}
// </snippet6>
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.startBtn = new System.Windows.Forms.Button();
this.cancelBtn = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
//
// startBtn
//
this.startBtn.Location = new System.Drawing.Point(12, 12);
this.startBtn.Name = "startBtn";
this.startBtn.Size = new System.Drawing.Size(75, 23);
this.startBtn.TabIndex = 0;
this.startBtn.Text = "Start";
this.startBtn.Click += new System.EventHandler(this.startBtn_Click);
//
// cancelBtn
//
this.cancelBtn.Location = new System.Drawing.Point(94, 11);
this.cancelBtn.Name = "cancelBtn";
this.cancelBtn.Size = new System.Drawing.Size(75, 23);
this.cancelBtn.TabIndex = 1;
this.cancelBtn.Text = "Cancel";
this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(183, 49);
this.Controls.Add(this.cancelBtn);
this.Controls.Add(this.startBtn);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.ComponentModel.BackgroundWorker backgroundWorker1;
private System.Windows.Forms.Button startBtn;
private System.Windows.Forms.Button cancelBtn;
}
public class Program
{
private Program()
{
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
// </snippet1>
@@ -0,0 +1,172 @@
// <snippet1>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
public class Form1 : Form
{
private BackgroundWorker backgroundWorker1;
private Button downloadButton;
private ProgressBar progressBar1;
private XmlDocument document = null;
public Form1()
{
InitializeComponent();
// Instantiate BackgroundWorker and attach handlers to its
// DoWork and RunWorkerCompleted events.
backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
}
// <snippet2>
private void downloadButton_Click(object sender, EventArgs e)
{
// Start the download operation in the background.
this.backgroundWorker1.RunWorkerAsync();
// Disable the button for the duration of the download.
this.downloadButton.Enabled = false;
// Once you have started the background thread you
// can exit the handler and the application will
// wait until the RunWorkerCompleted event is raised.
// Or if you want to do something else in the main thread,
// such as update a progress bar, you can do so in a loop
// while checking IsBusy to see if the background task is
// still running.
while (this.backgroundWorker1.IsBusy)
{
progressBar1.Increment(1);
// Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
}
}
// </snippet2>
// <snippet3>
private void backgroundWorker1_DoWork(
object sender,
DoWorkEventArgs e)
{
document = new XmlDocument();
// Uncomment the following line to
// simulate a noticeable latency.
//Thread.Sleep(5000);
// Replace this file name with a valid file name.
document.Load(@"http://www.tailspintoys.com/sample.xml");
}
// </snippet3>
// <snippet4>
private void backgroundWorker1_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e)
{
// Set progress bar to 100% in case it's not already there.
progressBar1.Value = 100;
if (e.Error == null)
{
MessageBox.Show(document.InnerXml, "Download Complete");
}
else
{
MessageBox.Show(
"Failed to download file",
"Download failed",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
// Enable the download button and reset the progress bar.
this.downloadButton.Enabled = true;
progressBar1.Value = 0;
}
// </snippet4>
#region Windows Form Designer generated code
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support
/// </summary>
private void InitializeComponent()
{
this.downloadButton = new System.Windows.Forms.Button();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.SuspendLayout();
//
// downloadButton
//
this.downloadButton.Location = new System.Drawing.Point(12, 12);
this.downloadButton.Name = "downloadButton";
this.downloadButton.Size = new System.Drawing.Size(100, 23);
this.downloadButton.TabIndex = 0;
this.downloadButton.Text = "Download file";
this.downloadButton.UseVisualStyleBackColor = true;
this.downloadButton.Click += new System.EventHandler(this.downloadButton_Click);
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(12, 50);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(100, 26);
this.progressBar1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(133, 104);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.downloadButton);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
// </snippet1>
@@ -0,0 +1,318 @@
// <snippet1>
// <snippet2>
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
// </snippet2>
namespace BackgroundWorkerExample
{
public class FibonacciForm : System.Windows.Forms.Form
{
// <snippet14>
private int numberToCompute = 0;
private int highestPercentageReached = 0;
// </snippet14>
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.Button startAsyncButton;
private System.Windows.Forms.Button cancelAsyncButton;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label resultLabel;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
public FibonacciForm()
{
InitializeComponent();
InitializeBackgroundWorker();
}
// Set up the BackgroundWorker object by
// attaching event handlers.
private void InitializeBackgroundWorker()
{
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorker1_ProgressChanged);
}
// <snippet13>
private void startAsyncButton_Click(System.Object sender,
System.EventArgs e)
{
// Reset the text in the result label.
resultLabel.Text = String.Empty;
// Disable the UpDown control until
// the asynchronous operation is done.
this.numericUpDown1.Enabled = false;
// Disable the Start button until
// the asynchronous operation is done.
this.startAsyncButton.Enabled = false;
// Enable the Cancel button while
// the asynchronous operation runs.
this.cancelAsyncButton.Enabled = true;
// Get the value from the UpDown control.
numberToCompute = (int)numericUpDown1.Value;
// Reset the variable for percentage tracking.
highestPercentageReached = 0;
// <snippet3>
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync(numberToCompute);
// </snippet3>
}
// </snippet13>
// <snippet4>
private void cancelAsyncButton_Click(System.Object sender,
System.EventArgs e)
{
// Cancel the asynchronous operation.
this.backgroundWorker1.CancelAsync();
// Disable the Cancel button.
cancelAsyncButton.Enabled = false;
}
// </snippet4>
// <snippet5>
// This event handler is where the actual,
// potentially time-consuming work is done.
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
// </snippet5>
// <snippet6>
// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
// Next, handle the case where the user canceled
// the operation.
// Note that due to a race condition in
// the DoWork event handler, the Cancelled
// flag may not have been set, even though
// CancelAsync was called.
resultLabel.Text = "Canceled";
}
else
{
// Finally, handle the case where the operation
// succeeded.
resultLabel.Text = e.Result.ToString();
}
// Enable the UpDown control.
this.numericUpDown1.Enabled = true;
// Enable the Start button.
startAsyncButton.Enabled = true;
// Disable the Cancel button.
cancelAsyncButton.Enabled = false;
}
// </snippet6>
// <snippet7>
// This event handler updates the progress bar.
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
// </snippet7>
// <snippet10>
// This is the method that does the actual work. For this
// example, it computes a Fibonacci number and
// reports progress as it does its work.
long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)
{
// The parameter n must be >= 0 and <= 91.
// Fib(n), with n > 91, overflows a long.
if ((n < 0) || (n > 91))
{
throw new ArgumentException(
"value must be >= 0 and <= 91", "n");
}
long result = 0;
// <snippet8>
// Abort the operation if the user has canceled.
// Note that a call to CancelAsync may have set
// CancellationPending to true just after the
// last invocation of this method exits, so this
// code will not have the opportunity to set the
// DoWorkEventArgs.Cancel flag to true. This means
// that RunWorkerCompletedEventArgs.Cancelled will
// not be set to true in your RunWorkerCompleted
// event handler. This is a race condition.
// <snippet11>
if (worker.CancellationPending)
{
e.Cancel = true;
}
// </snippet11>
else
{
if (n < 2)
{
result = 1;
}
else
{
result = ComputeFibonacci(n - 1, worker, e) +
ComputeFibonacci(n - 2, worker, e);
}
// <snippet12>
// Report progress as a percentage of the total task.
int percentComplete =
(int)((float)n / (float)numberToCompute * 100);
if (percentComplete > highestPercentageReached)
{
highestPercentageReached = percentComplete;
worker.ReportProgress(percentComplete);
}
// </snippet12>
}
// </snippet8>
return result;
}
// </snippet10>
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.startAsyncButton = new System.Windows.Forms.Button();
this.cancelAsyncButton = new System.Windows.Forms.Button();
this.resultLabel = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.SuspendLayout();
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(16, 16);
this.numericUpDown1.Maximum = new System.Decimal(new int[] {
91,
0,
0,
0});
this.numericUpDown1.Minimum = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(80, 20);
this.numericUpDown1.TabIndex = 0;
this.numericUpDown1.Value = new System.Decimal(new int[] {
1,
0,
0,
0});
//
// startAsyncButton
//
this.startAsyncButton.Location = new System.Drawing.Point(16, 72);
this.startAsyncButton.Name = "startAsyncButton";
this.startAsyncButton.Size = new System.Drawing.Size(120, 23);
this.startAsyncButton.TabIndex = 1;
this.startAsyncButton.Text = "Start Async";
this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click);
//
// cancelAsyncButton
//
this.cancelAsyncButton.Enabled = false;
this.cancelAsyncButton.Location = new System.Drawing.Point(153, 72);
this.cancelAsyncButton.Name = "cancelAsyncButton";
this.cancelAsyncButton.Size = new System.Drawing.Size(119, 23);
this.cancelAsyncButton.TabIndex = 2;
this.cancelAsyncButton.Text = "Cancel Async";
this.cancelAsyncButton.Click += new System.EventHandler(this.cancelAsyncButton_Click);
//
// resultLabel
//
this.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.resultLabel.Location = new System.Drawing.Point(112, 16);
this.resultLabel.Name = "resultLabel";
this.resultLabel.Size = new System.Drawing.Size(160, 23);
this.resultLabel.TabIndex = 3;
this.resultLabel.Text = "(no result)";
this.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(18, 48);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(256, 8);
this.progressBar1.Step = 2;
this.progressBar1.TabIndex = 4;
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
//
// FibonacciForm
//
this.ClientSize = new System.Drawing.Size(292, 118);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.resultLabel);
this.Controls.Add(this.cancelAsyncButton);
this.Controls.Add(this.startAsyncButton);
this.Controls.Add(this.numericUpDown1);
this.Name = "FibonacciForm";
this.Text = "Fibonacci Calculator";
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new FibonacciForm());
}
}
}
// </snippet1>
@@ -0,0 +1,134 @@
// <snippet1>
// <snippet2>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// </snippet2>
// This sample demonstrates the use of the
// DesignerSerializationVisibility attribute
// to serialize a collection of strings
// at design time.
namespace SerializationDemo
{
class Form1 : Form
{
private SerializationDemoControl serializationDemoControl1;
public Form1()
{
InitializeComponent();
}
// The Windows Forms Designer emits code to this method.
// If an instance of SerializationDemoControl is added
// to the form, the Strings will be serialized here.
private void InitializeComponent()
{
this.serializationDemoControl1 = new SerializationDemo.SerializationDemoControl();
this.SuspendLayout();
//
// serializationDemoControl1
//
this.serializationDemoControl1.Location = new System.Drawing.Point(0, 0);
this.serializationDemoControl1.Name = "serializationDemoControl1";
this.serializationDemoControl1.Padding = new System.Windows.Forms.Padding(5);
this.serializationDemoControl1.TabIndex = 0;
//
// Form1
//
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.serializationDemoControl1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
// <snippet3>
public class SerializationDemoControl : UserControl
{
// This is the TextBox contained by
// the SerializationDemoControl.
private System.Windows.Forms.TextBox textBox1;
// <snippet4>
// This field backs the Strings property.
private String[] stringsValue = new String[1];
// </snippet4>
public SerializationDemoControl()
{
InitializeComponent();
}
// <snippet5>
// When the DesignerSerializationVisibility attribute has
// a value of "Content" or "Visible" the designer will
// serialize the property. This property can also be edited
// at design time with a CollectionEditor.
[DesignerSerializationVisibility(
DesignerSerializationVisibility.Content )]
public String[] Strings
{
get
{
return this.stringsValue;
}
set
{
this.stringsValue = value;
// Populate the contained TextBox with the values
// in the stringsValue array.
StringBuilder sb =
new StringBuilder(this.stringsValue.Length);
for (int i = 0; i < this.stringsValue.Length; i++)
{
sb.Append(this.stringsValue[i]);
sb.Append("\r\n");
}
this.textBox1.Text = sb.ToString();
}
}
// </snippet5>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
// Settings for the contained TextBox control.
this.textBox1.AutoSize = false;
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(5, 5);
this.textBox1.Margin = new System.Windows.Forms.Padding(0);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.ScrollBars = ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(140, 140);
this.textBox1.TabIndex = 0;
// Settings for SerializationDemoControl.
this.Controls.Add(this.textBox1);
this.Name = "SerializationDemoControl";
this.Padding = new System.Windows.Forms.Padding(5);
this.ResumeLayout(false);
}
}
// </snippet3>
}
// </snippet1>
@@ -0,0 +1,32 @@
// <snippet100>
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Diagnostics;
namespace IListSourceCS
{
public class BusinessObjectBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
}
}
// </snippet100>
@@ -0,0 +1,65 @@
// <snippet10>
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace IListSourceCS
{
public class Employee : BusinessObjectBase
{
private string _id;
private string _name;
private Decimal parkingId;
public Employee() : this(string.Empty, 0) {}
public Employee(string name) : this(name, 0) {}
public Employee(string name, Decimal parkingId) : base()
{
this._id = System.Guid.NewGuid().ToString();
// Set values
this.Name = name;
this.ParkingID = parkingId;
}
public string ID
{
get { return _id; }
}
const string NAME = "Name";
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
// Raise the PropertyChanged event.
OnPropertyChanged(NAME);
}
}
}
const string PARKING_ID = "Salary";
public Decimal ParkingID
{
get { return parkingId; }
set
{
if (parkingId != value)
{
parkingId = value;
// Raise the PropertyChanged event.
OnPropertyChanged(PARKING_ID);
}
}
}
}
}
// </snippet10>
@@ -0,0 +1,51 @@
// <snippet1>
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace IListSourceCS
{
public class EmployeeListSource : Component, IListSource
{
public EmployeeListSource() {}
public EmployeeListSource(IContainer container)
{
container.Add(this);
}
// <snippet2>
#region IListSource Members
// <snippet3>
bool IListSource.ContainsListCollection
{
get { return false; }
}
// </snippet3>
// <snippet4>
System.Collections.IList IListSource.GetList()
{
BindingList<Employee> ble = new BindingList<Employee>();
if (!this.DesignMode)
{
ble.Add(new Employee("Aaberg, Jesper", 26000000));
ble.Add(new Employee("Cajhen, Janko", 19600000));
ble.Add(new Employee("Furse, Kari", 19000000));
ble.Add(new Employee("Langhorn, Carl", 16000000));
ble.Add(new Employee("Todorov, Teodor", 15700000));
ble.Add(new Employee("Verebélyi, Ágnes", 15700000));
}
return ble;
}
// </snippet4>
#endregion
// </snippet2>
}
}
// </snippet1>
@@ -0,0 +1,152 @@
// <snippet1000>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace IListSourceCS
{
public class Form1 : Form
{
private System.ComponentModel.IContainer components = null;
private FlowLayoutPanel flowLayoutPanel1;
private Label label2;
private DataGridView dataGridView1;
private DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn;
private DataGridViewTextBoxColumn salaryDataGridViewTextBoxColumn;
private DataGridViewTextBoxColumn iDDataGridViewTextBoxColumn;
private EmployeeListSource employeeListSource1;
public Form1()
{
InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.label2 = new System.Windows.Forms.Label();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.nameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.salaryDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.iDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.employeeListSource1 = new EmployeeListSource(this.components);
this.flowLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.Controls.Add(this.label2);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(416, 51);
this.flowLayoutPanel1.TabIndex = 11;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 6);
this.label2.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(408, 39);
this.label2.TabIndex = 0;
this.label2.Text = "This sample demonstrates how to implement the IListSource interface. In this sam" +
"ple, a DataGridView is bound at design time to a Component (employeeListSource1)" +
" that implements IListSource.";
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridView1.AutoGenerateColumns = false;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.nameDataGridViewTextBoxColumn,
this.salaryDataGridViewTextBoxColumn,
this.iDDataGridViewTextBoxColumn});
this.dataGridView1.DataSource = this.employeeListSource1;
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 51);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(416, 215);
this.dataGridView1.TabIndex = 12;
//
// nameDataGridViewTextBoxColumn
//
this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name";
this.nameDataGridViewTextBoxColumn.FillWeight = 131.7987F;
this.nameDataGridViewTextBoxColumn.HeaderText = "Name";
this.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn";
//
// salaryDataGridViewTextBoxColumn
//
this.salaryDataGridViewTextBoxColumn.DataPropertyName = "ParkingID";
this.salaryDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2;
this.salaryDataGridViewTextBoxColumn.FillWeight = 121.8274F;
this.salaryDataGridViewTextBoxColumn.HeaderText = "Parking ID";
this.salaryDataGridViewTextBoxColumn.Name = "salaryDataGridViewTextBoxColumn";
//
// iDDataGridViewTextBoxColumn
//
this.iDDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.iDDataGridViewTextBoxColumn.DataPropertyName = "ID";
this.iDDataGridViewTextBoxColumn.FillWeight = 46.37391F;
this.iDDataGridViewTextBoxColumn.HeaderText = "ID";
this.iDDataGridViewTextBoxColumn.Name = "iDDataGridViewTextBoxColumn";
this.iDDataGridViewTextBoxColumn.ReadOnly = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(416, 266);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.flowLayoutPanel1);
this.Name = "Form1";
this.Text = "IListSource Sample";
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
// </snippet1000>
@@ -0,0 +1,5 @@
IListSource.exe: BusinessObjectBase.cs Employee.cs EmployeeListSource.cs Form1.cs
csc /t:exe /out:IListSource.exe BusinessObjectBase.cs Employee.cs EmployeeListSource.cs Form1.cs
clean:
del *.dll *.bin *.exe
@@ -0,0 +1,159 @@
// <snippet1>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
// Change the namespace to the project name.
namespace TestNotifyPropertyChangedCS
{
// This form demonstrates using a BindingSource to bind
// a list to a DataGridView control. The list does not
// raise change notifications. However the DemoCustomer type
// in the list does.
public partial class Form1 : Form
{
// This button causes the value of a list element to be changed.
private Button changeItemBtn = new Button();
// This DataGridView control displays the contents of the list.
private DataGridView customersDataGridView = new DataGridView();
// This BindingSource binds the list to the DataGridView control.
private BindingSource customersBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
// Set up the "Change Item" button.
this.changeItemBtn.Text = "Change Item";
this.changeItemBtn.Dock = DockStyle.Bottom;
this.changeItemBtn.Click +=
new EventHandler(changeItemBtn_Click);
this.Controls.Add(this.changeItemBtn);
// Set up the DataGridView.
customersDataGridView.Dock = DockStyle.Top;
this.Controls.Add(customersDataGridView);
this.Size = new Size(400, 200);
}
private void Form1_Load(object sender, EventArgs e)
{
// Create and populate the list of DemoCustomer objects
// which will supply data to the DataGridView.
BindingList<DemoCustomer> customerList = new BindingList<DemoCustomer>();
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
// Bind the list to the BindingSource.
this.customersBindingSource.DataSource = customerList;
// Attach the BindingSource to the DataGridView.
this.customersDataGridView.DataSource =
this.customersBindingSource;
}
// Change the value of the CompanyName property for the first
// item in the list when the "Change Item" button is clicked.
void changeItemBtn_Click(object sender, EventArgs e)
{
// Get a reference to the list from the BindingSource.
BindingList<DemoCustomer> customerList =
this.customersBindingSource.DataSource as BindingList<DemoCustomer>;
// Change the value of the CompanyName property for the
// first item in the list.
customerList[0].CustomerName = "Tailspin Toys";
customerList[0].PhoneNumber = "(708)555-0150";
}
}
// <snippet9>
// This is a simple customer class that
// implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// The constructor is private to enforce the factory pattern.
private DemoCustomer()
{
customerNameValue = "Customer";
phoneNumberValue = "(312)555-0100";
}
// This is the public factory method.
public static DemoCustomer CreateNewCustomer()
{
return new DemoCustomer();
}
// This property represents an ID, suitable
// for use as a primary key in a database.
public Guid ID
{
get
{
return this.idValue;
}
}
public string CustomerName
{
get
{
return this.customerNameValue;
}
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged();
}
}
}
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged();
}
}
}
}
// </snippet9>
}
// </snippet1>
@@ -0,0 +1,148 @@
// <snippet10>
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace ITypedListCS
{
class Customer : INotifyPropertyChanged
{
public Customer() {}
public Customer(int id, string name, string company, string address, string city, string state, string zip)
{
this._id = id;
this._name = name;
this._company = company;
this._address = address;
this._city = city;
this._state = state;
this._zip = zip;
}
#region Public Properties
private int _id;
public int ID
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
OnPropertyChanged(new PropertyChangedEventArgs("ID"));
}
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
}
private string _company;
public string Company
{
get { return _company; }
set
{
if (_company != value)
{
_company = value;
OnPropertyChanged(new PropertyChangedEventArgs("Company"));
}
}
}
private string _address;
public string Address
{
get { return _address; }
set
{
if (_address != value)
{
_address = value;
OnPropertyChanged(new PropertyChangedEventArgs("Address"));
}
}
}
private string _city;
public string City
{
get { return _city; }
set
{
if (_city != value)
{
_city = value;
OnPropertyChanged(new PropertyChangedEventArgs("City"));
}
}
}
private string _state;
public string State
{
get { return _state; }
set
{
if (_state != value)
{
_state = value;
OnPropertyChanged(new PropertyChangedEventArgs("State"));
}
}
}
private string _zip;
public string ZipCode
{
get { return _zip; }
set
{
if (_zip != value)
{
_zip = value;
OnPropertyChanged(new PropertyChangedEventArgs("ZipCode"));
}
}
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
}
}
// </snippet10>
@@ -0,0 +1,166 @@
// <snippet100>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ITypedListCS
{
public partial class Form1 : Form
{
private SortableBindingList<Customer> sortableBindingListOfCustomers;
private BindingList<Customer> bindingListOfCustomers;
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Label label2;
private DataGridView dataGridView1;
private Button button1;
private Button button2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.sortableBindingListOfCustomers = new SortableBindingList<Customer>();
this.bindingListOfCustomers = new BindingList<Customer>();
this.dataGridView1.DataSource = this.bindingListOfCustomers;
}
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.DataSource = null;
this.dataGridView1.DataSource = this.sortableBindingListOfCustomers;
}
private void button2_Click(object sender, EventArgs e)
{
this.dataGridView1.DataSource = null;
this.dataGridView1.DataSource = this.bindingListOfCustomers;
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.label2 = new System.Windows.Forms.Label();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.flowLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.Controls.Add(this.label2);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(566, 51);
this.flowLayoutPanel1.TabIndex = 13;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 6);
this.label2.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(558, 39);
this.label2.TabIndex = 0;
this.label2.Text = "This sample demonstrates how to implement the ITypedList interface. Clicking on the 'Sort Columns' button will bind the DataGridView to a sub-classed BindingList<T> that implements ITypedList to provide a sorted list of columns. Clicking on the 'Reset' button will bind the DataGridView to a normal BindingList<T>.";
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(6, 57);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.Size = new System.Drawing.Size(465, 51);
this.dataGridView1.TabIndex = 14;
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(477, 57);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(82, 23);
this.button1.TabIndex = 15;
this.button1.Text = "Sort Columns";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.Location = new System.Drawing.Point(477, 86);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(82, 23);
this.button2.TabIndex = 16;
this.button2.Text = "Reset";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(566, 120);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.flowLayoutPanel1);
this.Name = "Form1";
this.Text = "ITypedList Sample";
this.Load += new System.EventHandler(this.Form1_Load);
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
// </snippet100>
@@ -0,0 +1,66 @@
// <snippet1>
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
namespace ITypedListCS
{
[Serializable()]
public class SortableBindingList<T> : BindingList<T>, ITypedList
{
[NonSerialized()]
private PropertyDescriptorCollection properties;
public SortableBindingList() : base()
{
// Get the 'shape' of the list.
// Only get the public properties marked with Browsable = true.
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(
typeof(T),
new Attribute[] { new BrowsableAttribute(true) });
// Sort the properties.
properties = pdc.Sort();
}
// <snippet2>
#region ITypedList Implementation
// <snippet3>
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
PropertyDescriptorCollection pdc;
if (listAccessors!=null && listAccessors.Length>0)
{
// Return child list shape.
pdc = ListBindingHelper.GetListItemProperties(listAccessors[0].PropertyType);
}
else
{
// Return properties in sort order.
pdc = properties;
}
return pdc;
}
// </snippet3>
// <snippet4>
// This method is only used in the design-time framework
// and by the obsolete DataGrid control.
public string GetListName(PropertyDescriptor[] listAccessors)
{
return typeof(T).Name;
}
// </snippet4>
#endregion
// </snippet2>
}
}
// </snippet1>
@@ -0,0 +1,5 @@
ITypedList.exe: SortableBindingList.cs Customer.cs Form1.cs
csc /t:exe /out:ITypedList.exe SortableBindingList.cs Customer.cs Form1.cs
clean:
del *.dll *.bin *.exe
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace AlignText
{
public class Form1 : Form
{
public Form1()
{
this.Paint +=new PaintEventHandler(Form1_Paint);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
private void AlignTextWithTextRenderer(PaintEventArgs e)
{
//<snippet20>
string text2 = "Use TextFormatFlags and Rectangle objects to"
+ " center text in a rectangle.";
using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
Rectangle rect2 = new Rectangle(150, 10, 130, 140);
// Create a TextFormatFlags with word wrapping, horizontal center and
// vertical center specified.
TextFormatFlags flags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
// Draw the text and the surrounding rectangle.
TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags);
e.Graphics.DrawRectangle(Pens.Black, rect2);
}
//</snippet20>
}
private void AlignTextWithDrawString(PaintEventArgs e)
{
//<snippet10>
string text1 = "Use StringFormat and Rectangle objects to"
+ " center text in a rectangle.";
using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
Rectangle rect1 = new Rectangle(10, 10, 130, 140);
// Create a StringFormat object with the each line of text, and the block
// of text centered on the page.
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
// Draw the text and the surrounding rectangle.
e.Graphics.DrawString(text1, font1, Brushes.Blue, rect1, stringFormat);
e.Graphics.DrawRectangle(Pens.Black, rect1);
}
//</snippet10>
}
private void DrawTextAtLocation1(PaintEventArgs e)
{
//<snippet30>
using (Font font1 = new Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel)){
PointF pointF1 = new PointF(30, 10);
e.Graphics.DrawString("Hello", font1, Brushes.Blue, pointF1);
}
//</snippet30>
}
private void DrawTextAtLocation2(PaintEventArgs e)
{
//<snippet40>
using (Font font = new Font("Times New Roman", 24, FontStyle.Bold, GraphicsUnit.Pixel))
{
Point point1 = new Point(30, 10);
TextRenderer.DrawText(e.Graphics, "Hello", font, point1, Color.Blue);
}
//</snippet40>
}
private void DrawTextInARectangle1(PaintEventArgs e)
{
//<snippet50>
string text1 = "Draw text in a rectangle by passing a RectF to the DrawString method.";
using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
RectangleF rectF1 = new RectangleF(30, 10, 100, 122);
e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1);
e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1));
}
//</snippet50>
}
private void DrawTextInARectangle2(PaintEventArgs e)
{
//<snippet60>
string text2 = "Draw text in a rectangle by passing a RectF to the DrawString method.";
using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
Rectangle rect2 = new Rectangle(30, 10, 100, 122);
// Specify the text is wrapped.
TextFormatFlags flags = TextFormatFlags.WordBreak;
TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags);
e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2));
}
//</snippet60>
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
//AlignTextWithDrawString(e);
//AlignTextWithTextRenderer(e);
//DrawTextAtLocation1(e);
//DrawTextAtLocation2(e);
DrawTextInARectangle1(e);
}
}
}
@@ -0,0 +1,164 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public class SystemDrawingAlphaBlending
{
// 8f2508af-f495-4223-b5cc-646cbbb520eb
// How to: Draw Opaque and Semitransparent Lines
public void Method11(PaintEventArgs e)
{
// <snippet11>
Bitmap bitmap = new Bitmap("Texture1.jpg");
e.Graphics.DrawImage(bitmap, 10, 5, bitmap.Width, bitmap.Height);
Pen opaquePen = new Pen(Color.FromArgb(255, 0, 0, 255), 15);
Pen semiTransPen = new Pen(Color.FromArgb(128, 0, 0, 255), 15);
e.Graphics.DrawLine(opaquePen, 0, 20, 100, 20);
e.Graphics.DrawLine(semiTransPen, 0, 40, 100, 40);
e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected;
e.Graphics.DrawLine(semiTransPen, 0, 60, 100, 60);
// </snippet11>
}
// a27121e6-f7e9-4c09-84e2-f05aa9d2a1bb
// How to: Use a Color Matrix to Set Alpha Values in Images
public void Method21(PaintEventArgs e)
{
// <snippet21>
// Create the Bitmap object and load it with the texture image.
Bitmap bitmap = new Bitmap("Texture.jpg");
// Initialize the color matrix.
// Note the value 0.8 in row 4, column 4.
float[][] matrixItems ={
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, 0.8f, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
// Create an ImageAttributes object and set its color matrix.
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
// First draw a wide black line.
e.Graphics.DrawLine(
new Pen(Color.Black, 25),
new Point(10, 35),
new Point(200, 35));
// Now draw the semitransparent bitmap image.
int iWidth = bitmap.Width;
int iHeight = bitmap.Height;
e.Graphics.DrawImage(
bitmap,
new Rectangle(30, 0, iWidth, iHeight), // destination rectangle
0.0f, // source rectangle x
0.0f, // source rectangle y
iWidth, // source rectangle width
iHeight, // source rectangle height
GraphicsUnit.Pixel,
imageAtt);
// </snippet21>
}
// a4f6f6b8-3bc8-440a-84af-d62ef0f8ff40
// How to: Draw with Opaque and Semitransparent Brushes
public void Method31(PaintEventArgs e)
{
// <snippet31>
Bitmap bitmap = new Bitmap("Texture1.jpg");
e.Graphics.DrawImage(bitmap, 50, 50, bitmap.Width, bitmap.Height);
SolidBrush opaqueBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
e.Graphics.FillEllipse(opaqueBrush, 35, 45, 45, 30);
e.Graphics.FillEllipse(semiTransBrush, 86, 45, 45, 30);
e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected;
e.Graphics.FillEllipse(semiTransBrush, 40, 90, 86, 30);
// </snippet31>
}
// f331df2d-b395-4b0a-95be-24fec8c9bbb5
// How to: Use Compositing Mode to Control Alpha Blending
public void Method41()
{
Bitmap myBitmap = new Bitmap(180, 100);
// Create a Graphics object that we can use to draw on the bitmap.
Graphics bitmapGraphics = Graphics.FromImage(myBitmap);
// <snippet41>
bitmapGraphics.CompositingMode = CompositingMode.SourceCopy;
// </snippet41>
}
public void Method42()
{
Bitmap myBitmap = new Bitmap(180, 100);
// Create a Graphics object that we can use to draw on the bitmap.
Graphics bitmapGraphics = Graphics.FromImage(myBitmap);
// <snippet42>
bitmapGraphics.CompositingMode = CompositingMode.SourceOver;
// </snippet42>
}
public void Method43(PaintEventArgs e)
{
// <snippet43>
// Create a blank bitmap.
Bitmap myBitmap = new Bitmap(180, 100);
// Create a Graphics object that we can use to draw on the bitmap.
Graphics bitmapGraphics = Graphics.FromImage(myBitmap);
// Create a red brush and a green brush, each with an alpha value of 160.
SolidBrush redBrush = new SolidBrush(Color.FromArgb(160, 255, 0, 0));
SolidBrush greenBrush = new SolidBrush(Color.FromArgb(160, 0, 255, 0));
// Set the compositing mode so that when we draw overlapping ellipses,
// the colors of the ellipses are not blended.
bitmapGraphics.CompositingMode = CompositingMode.SourceCopy;
// Fill an ellipse using a red brush that has an alpha value of 160.
bitmapGraphics.FillEllipse(redBrush, 0, 0, 150, 70);
// Fill a second ellipse using a green brush that has an alpha value of 160.
// The green ellipse overlaps the red ellipse, but the green is not
// blended with the red.
bitmapGraphics.FillEllipse(greenBrush, 30, 30, 150, 70);
// Set the compositing quality of the form's Graphics object.
e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected;
// Draw a multicolored background.
SolidBrush colorBrush = new SolidBrush(Color.Aqua);
e.Graphics.FillRectangle(colorBrush, 200, 0, 60, 100);
colorBrush.Color = Color.Yellow;
e.Graphics.FillRectangle(colorBrush, 260, 0, 60, 100);
colorBrush.Color = Color.Fuchsia;
e.Graphics.FillRectangle(colorBrush, 320, 0, 60, 100);
// Display the bitmap on a white background.
e.Graphics.DrawImage(myBitmap, 0, 0);
// Display the bitmap on a multicolored background.
e.Graphics.DrawImage(myBitmap, 200, 0);
// </snippet43>
}
}
@@ -0,0 +1,149 @@
using System;
using System.Windows.Forms;
using System.Drawing;
public class Form1:
System.Windows.Forms.Form
{
private void DoSomething1()
{
// Snippet for: \vbtskcodeexampledrawingfilledellipseonform.xml
// <snippet1>
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillEllipse(myBrush, new Rectangle(0, 0, 200, 300));
myBrush.Dispose();
formGraphics.Dispose();
// </snippet1>
}
private void DoSomething2()
{
// Snippet for: \vbtskcodeexampledrawingfilledrectangleonform.xml
// <snippet2>
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush, new Rectangle(0, 0, 200, 300));
myBrush.Dispose();
formGraphics.Dispose();
// </snippet2>
}
private void DoSomething3()
{
// Snippet for: \vbtskcodeexamplecreatingpen.xml
// <snippet3>
System.Drawing.Pen myPen;
myPen = new System.Drawing.Pen(System.Drawing.Color.Tomato);
// </snippet3>
}
private void DoSomething4()
{
// Snippet for: \vbtskcodeexamplecreatingsolidbrush.xml
// <snippet4>
System.Drawing.SolidBrush myBrush;
myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.PeachPuff);
// </snippet4>
}
private void DoSomething5()
{
// Snippet for: \vbtskcodeexampledrawinglineonform.xml
// <snippet5>
System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 200, 200);
myPen.Dispose();
formGraphics.Dispose();
// </snippet5>
}
// Snippet for: \vbtskcodeexampledrawingoutlinedshapes.xml
// <snippet6>
private void DrawEllipse()
{
System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.DrawEllipse(myPen, new Rectangle(0, 0, 200, 300));
myPen.Dispose();
formGraphics.Dispose();
}
private void DrawRectangle()
{
System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.DrawRectangle(myPen, new Rectangle(0, 0, 200, 300));
myPen.Dispose();
formGraphics.Dispose();
}
// </snippet6>
// Snippet for: \vbtskcodeexampledrawingtextonform2.xml
// <snippet7>
public void DrawString()
{
System.Drawing.Graphics formGraphics = this.CreateGraphics();
string drawString = "Sample Text";
System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16);
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
float x = 150.0F;
float y = 50.0F;
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
drawFont.Dispose();
drawBrush.Dispose();
formGraphics.Dispose();
}
// </snippet7>
// Snippet for: \vbtskcodeexampledrawingtextonform.xml
// <snippet8>
public void DrawVerticalString()
{
System.Drawing.Graphics formGraphics = this.CreateGraphics();
string drawString = "Sample Text";
System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 16);
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
float x = 150.0F;
float y = 50.0F;
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
drawFormat.FormatFlags = StringFormatFlags.DirectionVertical;
formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
drawFont.Dispose();
drawBrush.Dispose();
formGraphics.Dispose();
}
// </snippet8>
private void DoSomething9()
{
Pen myPen = new Pen(Color.Red);
// Snippet for: \vbtskcodeexamplesetcolorofpen.xml
// <snippet9>
myPen.Color = System.Drawing.Color.PeachPuff;
// </snippet9>
}
// Snippet for: \vbtskcreateashapedwindowsform.xml
// <snippet10>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
shape.AddEllipse(0, 0, this.Width, this.Height);
this.Region = new System.Drawing.Region(shape);
}
// </snippet10>
[STAThread]
public static void Main()
{
Application.Run(new Form1());
}
}
@@ -0,0 +1,97 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Drawing2D;
public class SystemDrawingConstructingDrawingCurves
{
// 37a0bedb-20c2-4cf0-91fa-a5509e826b30
// How to: Draw a Sequence of Bézier Splines
private void Method11(PaintEventArgs e)
{
// <snippet11>
Point[] p = {
new Point(10, 100), // start point of first spline
new Point(75, 10), // first control point of first spline
new Point(80, 50), // second control point of first spline
new Point(100, 150), // endpoint of first spline and
// start point of second spline
new Point(125, 80), // first control point of second spline
new Point(175, 200), // second control point of second spline
new Point(200, 80)}; // endpoint of second spline
Pen pen = new Pen(Color.Blue);
e.Graphics.DrawBeziers(pen, p);
// </snippet11>
}
// a4a41e80-4461-4b47-b6bd-2c5e68881994
// How to: Draw Cardinal Splines
private void Method21(PaintEventArgs e)
{
// <snippet21>
Point[] points = {
new Point(0, 100),
new Point(50, 80),
new Point(100, 20),
new Point(150, 80),
new Point(200, 100)};
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255));
e.Graphics.DrawCurve(pen, points);
// </snippet21>
}
private void Method22(PaintEventArgs e)
{
// <snippet22>
Point[] points = {
new Point(60, 60),
new Point(150, 80),
new Point(200, 40),
new Point(180, 120),
new Point(120, 100),
new Point(80, 160)};
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255));
e.Graphics.DrawClosedCurve(pen, points);
// </snippet22>
}
private void Method23(PaintEventArgs e)
{
// <snippet23>
Point[] points = {
new Point(20, 50),
new Point(100, 10),
new Point(200, 100),
new Point(300, 50),
new Point(400, 80)};
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255));
e.Graphics.DrawCurve(pen, points, 0.0f);
e.Graphics.DrawCurve(pen, points, 0.6f);
e.Graphics.DrawCurve(pen, points, 1.0f);
// </snippet23>
}
// f4f3fe30-f0a6-4743-ac91-11310cebea9f
// How to: Draw a Single Bézier Spline
private void Method31(PaintEventArgs e)
{
// <snippet31>
Point p1 = new Point(10, 100); // Start point
Point c1 = new Point(100, 10); // First control point
Point c2 = new Point(150, 150); // Second control point
Point p2 = new Point(200, 100); // Endpoint
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255));
e.Graphics.DrawBezier(pen, p1, c1, c2, p2);
// </snippet31>
}
}
@@ -0,0 +1,69 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Drawing2D;
public class SystemDrawingConstructingDrawingPaths
{
// 5a36b0e4-f1f4-46c0-a85a-22ae98491950
// How to: Fill Open Figures
private void Method11(PaintEventArgs e)
{
// <snippet11>
GraphicsPath path = new GraphicsPath();
// Add an open figure.
path.AddArc(0, 0, 150, 120, 30, 120);
// Add an intrinsically closed figure.
path.AddEllipse(50, 50, 50, 100);
Pen pen = new Pen(Color.FromArgb(128, 0, 0, 255), 5);
SolidBrush brush = new SolidBrush(Color.Red);
// The fill mode is FillMode.Alternate by default.
e.Graphics.FillPath(brush, path);
e.Graphics.DrawPath(pen, path);
// </snippet11>
}
// 82fd56c7-b443-4765-9b7c-62ce030656ec
// How to: Create Figures from Lines, Curves, and Shapes
private void Method21(PaintEventArgs e)
{
// <snippet21>
GraphicsPath path = new GraphicsPath();
path.AddArc(175, 50, 50, 50, 0, -180);
e.Graphics.DrawPath(new Pen(Color.FromArgb(128, 255, 0, 0), 4), path);
// </snippet21>
}
private void Method22(PaintEventArgs e)
{
// <snippet22>
// Create an array of points for the curve in the second figure.
Point[] points = {
new Point(40, 60),
new Point(50, 70),
new Point(30, 90)};
GraphicsPath path = new GraphicsPath();
path.StartFigure(); // Start the first figure.
path.AddArc(175, 50, 50, 50, 0, -180);
path.AddLine(100, 0, 250, 20);
// First figure is not closed.
path.StartFigure(); // Start the second figure.
path.AddLine(50, 20, 5, 90);
path.AddCurve(points, 3);
path.AddLine(50, 150, 150, 180);
path.CloseFigure(); // Second figure is closed.
e.Graphics.DrawPath(new Pen(Color.FromArgb(255, 255, 0, 0), 2), path);
// </snippet22>
}
}
@@ -0,0 +1,128 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public class Form1 : Form
{
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
Pen myPen = Pens.Red;
// 0659fe00-9e0c-41c4-9118-016f2404c905
// Matrix Representation of Transformations
public void Method11()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet11>
Matrix myMatrix = new Matrix();
myMatrix.Rotate(30);
myMatrix.Scale(1, 2, MatrixOrder.Append);
myMatrix.Translate(5, 0, MatrixOrder.Append);
// </snippet11>
}
// b601d66d-d572-4f11-9d2e-92f0dc8893f3
// Global and Local Transformations
public void Method21()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet21>
myGraphics.DrawEllipse(myPen, 0, 0, 100, 50);
myGraphics.ScaleTransform(1, 0.5f);
myGraphics.TranslateTransform(50, 0, MatrixOrder.Append);
myGraphics.RotateTransform(30, MatrixOrder.Append);
myGraphics.DrawEllipse(myPen, 0, 0, 100, 50);
// </snippet21>
}
public void Method22()
{
Graphics myGraphics = this.CreateGraphics();
GraphicsPath myGraphicsPath = new GraphicsPath();
// <snippet22>
Matrix myMatrix = new Matrix();
myMatrix.Rotate(45);
myGraphicsPath.Transform(myMatrix);
myGraphics.DrawRectangle(myPen, 10, 10, 100, 50);
myGraphics.DrawPath(myPen, myGraphicsPath);
// </snippet22>
}
public void Method23()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet23>
Matrix myMatrix = new Matrix(1, 0, 0, -1, 0, 0);
myGraphics.Transform = myMatrix;
myGraphics.TranslateTransform(200, 150, MatrixOrder.Append);
// </snippet23>
}
public void Method24()
{
Graphics myGraphics = this.CreateGraphics();
SolidBrush mySolidBrush1 = new SolidBrush(Color.Red);
SolidBrush mySolidBrush2 = new SolidBrush(Color.Black);
// <snippet24>
// Create the path.
GraphicsPath myGraphicsPath = new GraphicsPath();
Rectangle myRectangle = new Rectangle(0, 0, 60, 60);
myGraphicsPath.AddRectangle(myRectangle);
// Fill the path on the new coordinate system.
// No local transformation
myGraphics.FillPath(mySolidBrush1, myGraphicsPath);
// Set the local transformation of the GraphicsPath object.
Matrix myPathMatrix = new Matrix();
myPathMatrix.Scale(2, 1);
myPathMatrix.Rotate(30, MatrixOrder.Append);
myGraphicsPath.Transform(myPathMatrix);
// Fill the transformed path on the new coordinate system.
myGraphics.FillPath(mySolidBrush2, myGraphicsPath);
// </snippet24>
}
// c61ff50a-eb1d-4e6c-83cd-f7e9764cfa9f
// Types of Coordinate Systems
public void Method31()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet31>
myGraphics.TranslateTransform(100, 50);
myGraphics.DrawLine(myPen, 0, 0, 160, 80);
// </snippet31>
}
public void Method32()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet32>
myGraphics.PageUnit = GraphicsUnit.Inch;
myGraphics.DrawLine(myPen, 0, 0, 2, 1);
// </snippet32>
}
public void Method33()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet33>
Pen myPen = new Pen(Color.Black, 1 / myGraphics.DpiX);
// </snippet33>
}
public void Method34()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet34>
myGraphics.TranslateTransform(2, 0.5f);
myGraphics.PageUnit = GraphicsUnit.Inch;
myGraphics.DrawLine(myPen, 0, 0, 2, 1);
// </snippet34>
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BitmapAtRuntime
{
public class Form1 : Form
{
public Form1()
{
this.Paint += new PaintEventHandler(Form1_Paint);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
void Form1_Paint(object sender, PaintEventArgs e)
{
CreateBitmapAtRuntime();
}
//<snippet1>
PictureBox pictureBox1 = new PictureBox();
public void CreateBitmapAtRuntime()
{
pictureBox1.Size = new Size(210, 110);
this.Controls.Add(pictureBox1);
Bitmap flag = new Bitmap(200, 100);
Graphics flagGraphics = Graphics.FromImage(flag);
int red = 0;
int white = 11;
while (white <= 100) {
flagGraphics.FillRectangle(Brushes.Red, 0, red, 200,10);
flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);
red += 20;
white += 20;
}
pictureBox1.Image = flag;
}
//</snippet1>
}
}
@@ -0,0 +1,381 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Text;
public class SystemDrawingFontsAndText
{
// 26d74ef5-0f39-4eeb-8d20-00e66e014abe
// How to: Enumerate Installed Fonts
public void Method11(PaintEventArgs e)
{
// <snippet11>
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
fontFamily,
8,
FontStyle.Regular,
GraphicsUnit.Point);
RectangleF rectF = new RectangleF(10, 10, 500, 500);
SolidBrush solidBrush = new SolidBrush(Color.Black);
string familyName;
string familyList = "";
FontFamily[] fontFamilies;
InstalledFontCollection installedFontCollection = new InstalledFontCollection();
// Get the array of FontFamily objects.
fontFamilies = installedFontCollection.Families;
// The loop below creates a large string that is a comma-separated
// list of all font family names.
int count = fontFamilies.Length;
for (int j = 0; j < count; ++j)
{
familyName = fontFamilies[j].Name;
familyList = familyList + familyName;
familyList = familyList + ", ";
}
// Draw the large string (list of all families) in a rectangle.
e.Graphics.DrawString(familyList, font, solidBrush, rectF);
// </snippet11>
}
// 48fc34f3-f236-4b01-a0cb-f0752e6d22ae
// How to: Use Antialiasing with Text
public void Method21(PaintEventArgs e)
{
// <snippet21>
FontFamily fontFamily = new FontFamily("Times New Roman");
Font font = new Font(
fontFamily,
32,
FontStyle.Regular,
GraphicsUnit.Pixel);
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
string string1 = "SingleBitPerPixel";
string string2 = "AntiAlias";
e.Graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
e.Graphics.DrawString(string1, font, solidBrush, new PointF(10, 10));
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
e.Graphics.DrawString(string2, font, solidBrush, new PointF(10, 60));
// </snippet21>
}
// 50c69046-4188-47d9-b949-cc2610ffd337
// How to: Create Vertical Text
public void Method31(PaintEventArgs e)
{
// <snippet31>
string myText = "Vertical text";
FontFamily fontFamily = new FontFamily("Lucida Console");
Font font = new Font(
fontFamily,
14,
FontStyle.Regular,
GraphicsUnit.Point);
PointF pointF = new PointF(40, 10);
StringFormat stringFormat = new StringFormat();
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
e.Graphics.DrawString(myText, font, solidBrush, pointF, stringFormat);
// </snippet31>
}
// 64878f98-39ba-4303-b63f-0859ab682eeb
// How to: Set Tab Stops in Drawn Text
public void Method41(PaintEventArgs e)
{
// <snippet41>
string text = "Name\tTest 1\tTest 2\tTest 3\n";
text = text + "Joe\t95\t88\t91\n";
text = text + "Mary\t98\t84\t90\n";
text = text + "Sam\t42\t76\t98\n";
text = text + "Jane\t65\t73\t92\n";
FontFamily fontFamily = new FontFamily("Courier New");
Font font = new Font(
fontFamily,
12,
FontStyle.Regular,
GraphicsUnit.Point);
Rectangle rect = new Rectangle(10, 10, 450, 100);
StringFormat stringFormat = new StringFormat();
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
float[] tabs = { 150, 100, 100, 100 };
stringFormat.SetTabStops(0, tabs);
e.Graphics.DrawString(text, font, solidBrush, rect, stringFormat);
Pen pen = Pens.Black;
e.Graphics.DrawRectangle(pen, rect);
// </snippet41>
}
// 6533d5e5-a8dc-4b76-9fc4-3bf75c8b9212
// How to: Create a Private Font Collection
public void Method51(PaintEventArgs e)
{
// <snippet51>
PointF pointF = new PointF(10, 0);
SolidBrush solidBrush = new SolidBrush(Color.Black);
int count = 0;
string familyName = "";
string familyNameAndStyle;
FontFamily[] fontFamilies;
PrivateFontCollection privateFontCollection = new PrivateFontCollection();
// Add three font files to the private collection.
privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\Arial.ttf");
privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\CourBI.ttf");
privateFontCollection.AddFontFile("D:\\systemroot\\Fonts\\TimesBD.ttf");
// Get the array of FontFamily objects.
fontFamilies = privateFontCollection.Families;
// How many objects in the fontFamilies array?
count = fontFamilies.Length;
// Display the name of each font family in the private collection
// along with the available styles for that font family.
for (int j = 0; j < count; ++j)
{
// Get the font family name.
familyName = fontFamilies[j].Name;
// Is the regular style available?
if (fontFamilies[j].IsStyleAvailable(FontStyle.Regular))
{
familyNameAndStyle = "";
familyNameAndStyle = familyNameAndStyle + familyName;
familyNameAndStyle = familyNameAndStyle + " Regular";
Font regFont = new Font(
familyName,
16,
FontStyle.Regular,
GraphicsUnit.Pixel);
e.Graphics.DrawString(
familyNameAndStyle,
regFont,
solidBrush,
pointF);
pointF.Y += regFont.Height;
}
// Is the bold style available?
if (fontFamilies[j].IsStyleAvailable(FontStyle.Bold))
{
familyNameAndStyle = "";
familyNameAndStyle = familyNameAndStyle + familyName;
familyNameAndStyle = familyNameAndStyle + " Bold";
Font boldFont = new Font(
familyName,
16,
FontStyle.Bold,
GraphicsUnit.Pixel);
e.Graphics.DrawString(familyNameAndStyle, boldFont, solidBrush, pointF);
pointF.Y += boldFont.Height;
}
// Is the italic style available?
if (fontFamilies[j].IsStyleAvailable(FontStyle.Italic))
{
familyNameAndStyle = "";
familyNameAndStyle = familyNameAndStyle + familyName;
familyNameAndStyle = familyNameAndStyle + " Italic";
Font italicFont = new Font(
familyName,
16,
FontStyle.Italic,
GraphicsUnit.Pixel);
e.Graphics.DrawString(
familyNameAndStyle,
italicFont,
solidBrush,
pointF);
pointF.Y += italicFont.Height;
}
// Is the bold italic style available?
if (fontFamilies[j].IsStyleAvailable(FontStyle.Italic) &&
fontFamilies[j].IsStyleAvailable(FontStyle.Bold))
{
familyNameAndStyle = "";
familyNameAndStyle = familyNameAndStyle + familyName;
familyNameAndStyle = familyNameAndStyle + "BoldItalic";
Font italicFont = new Font(
familyName,
16,
FontStyle.Italic | FontStyle.Bold,
GraphicsUnit.Pixel);
e.Graphics.DrawString(
familyNameAndStyle,
italicFont,
solidBrush,
pointF);
pointF.Y += italicFont.Height;
}
// Is the underline style available?
if (fontFamilies[j].IsStyleAvailable(FontStyle.Underline))
{
familyNameAndStyle = "";
familyNameAndStyle = familyNameAndStyle + familyName;
familyNameAndStyle = familyNameAndStyle + " Underline";
Font underlineFont = new Font(
familyName,
16,
FontStyle.Underline,
GraphicsUnit.Pixel);
e.Graphics.DrawString(
familyNameAndStyle,
underlineFont,
solidBrush,
pointF);
pointF.Y += underlineFont.Height;
}
// Is the strikeout style available?
if (fontFamilies[j].IsStyleAvailable(FontStyle.Strikeout))
{
familyNameAndStyle = "";
familyNameAndStyle = familyNameAndStyle + familyName;
familyNameAndStyle = familyNameAndStyle + " Strikeout";
Font strikeFont = new Font(
familyName,
16,
FontStyle.Strikeout,
GraphicsUnit.Pixel);
e.Graphics.DrawString(
familyNameAndStyle,
strikeFont,
solidBrush,
pointF);
pointF.Y += strikeFont.Height;
}
// Separate the families with white space.
pointF.Y += 10;
} // for
// </snippet51>
}
// d3a4a223-9492-4b54-9afd-db1c31c3cefd
// How to: Construct Font Families and Fonts
public void Method61(PaintEventArgs e)
{
// <snippet61>
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
fontFamily,
16,
FontStyle.Regular,
GraphicsUnit.Pixel);
// </snippet61>
}
// ff7c0616-67f7-4fa2-84ee-b8d642f2b09b
// How to: Obtain Font Metrics
public void Method71(PaintEventArgs e)
{
// <snippet71>
string infoString = ""; // enough space for one line of output
int ascent; // font family ascent in design units
float ascentPixel; // ascent converted to pixels
int descent; // font family descent in design units
float descentPixel; // descent converted to pixels
int lineSpacing; // font family line spacing in design units
float lineSpacingPixel; // line spacing converted to pixels
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
fontFamily,
16, FontStyle.Regular,
GraphicsUnit.Pixel);
PointF pointF = new PointF(10, 10);
SolidBrush solidBrush = new SolidBrush(Color.Black);
// Display the font size in pixels.
infoString = "font.Size returns " + font.Size + ".";
e.Graphics.DrawString(infoString, font, solidBrush, pointF);
// Move down one line.
pointF.Y += font.Height;
// Display the font family em height in design units.
infoString = "fontFamily.GetEmHeight() returns " +
fontFamily.GetEmHeight(FontStyle.Regular) + ".";
e.Graphics.DrawString(infoString, font, solidBrush, pointF);
// Move down two lines.
pointF.Y += 2 * font.Height;
// Display the ascent in design units and pixels.
ascent = fontFamily.GetCellAscent(FontStyle.Regular);
// 14.484375 = 16.0 * 1854 / 2048
ascentPixel =
font.Size * ascent / fontFamily.GetEmHeight(FontStyle.Regular);
infoString = "The ascent is " + ascent + " design units, " + ascentPixel +
" pixels.";
e.Graphics.DrawString(infoString, font, solidBrush, pointF);
// Move down one line.
pointF.Y += font.Height;
// Display the descent in design units and pixels.
descent = fontFamily.GetCellDescent(FontStyle.Regular);
// 3.390625 = 16.0 * 434 / 2048
descentPixel =
font.Size * descent / fontFamily.GetEmHeight(FontStyle.Regular);
infoString = "The descent is " + descent + " design units, " +
descentPixel + " pixels.";
e.Graphics.DrawString(infoString, font, solidBrush, pointF);
// Move down one line.
pointF.Y += font.Height;
// Display the line spacing in design units and pixels.
lineSpacing = fontFamily.GetLineSpacing(FontStyle.Regular);
// 18.398438 = 16.0 * 2355 / 2048
lineSpacingPixel =
font.Size * lineSpacing / fontFamily.GetEmHeight(FontStyle.Regular);
infoString = "The line spacing is " + lineSpacing + " design units, " +
lineSpacingPixel + " pixels.";
e.Graphics.DrawString(infoString, font, solidBrush, pointF);
// </snippet71>
}
}
@@ -0,0 +1,50 @@
//<snippet1>
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
public class Form1 :
Form
{
private Button printButton = new Button();
private PrintDocument printDocument1 = new PrintDocument();
public Form1()
{
printButton.Text = "Print Form";
printButton.Click += new EventHandler(printButton_Click);
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
this.Controls.Add(printButton);
}
void printButton_Click(object sender, EventArgs e)
{
CaptureScreen();
printDocument1.Print();
}
Bitmap memoryImage;
private void CaptureScreen()
{
Graphics myGraphics = this.CreateGraphics();
Size s = this.Size;
memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
}
private void printDocument1_PrintPage(System.Object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
}
public static void Main()
{
Application.Run(new Form1());
}
}
//</snippet1>
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ExtractAssociatedIcon
{
public class Form1 : Form
{
public Form1()
{
ExtractAssociatedIconEx();
}
// <snippet1>
ListView listView1;
ImageList imageList1;
public void ExtractAssociatedIconEx()
{
// Initialize the ListView, ImageList and Form.
listView1 = new ListView();
imageList1 = new ImageList();
listView1.Location = new Point(37, 12);
listView1.Size = new Size(151, 262);
listView1.SmallImageList = imageList1;
listView1.View = View.SmallIcon;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.listView1);
this.Text = "Form1";
// Get the c:\ directory.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"c:\");
ListViewItem item;
listView1.BeginUpdate();
// For each file in the c:\ directory, create a ListViewItem
// and set the icon to the icon extracted from the file.
foreach (System.IO.FileInfo file in dir.GetFiles())
{
// Set a default icon for the file.
Icon iconForFile = SystemIcons.WinLogo;
item = new ListViewItem(file.Name, 1);
// Check to see if the image collection contains an image
// for this extension, using the extension as a key.
if (!imageList1.Images.ContainsKey(file.Extension))
{
// If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName);
imageList1.Images.Add(file.Extension, iconForFile);
}
item.ImageKey = file.Extension;
listView1.Items.Add(item);
}
listView1.EndUpdate();
}
// </snippet1>
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
@@ -0,0 +1,118 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Imaging;
public class Form1 : Form
{
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
// 09f0c07a-19c0-43b4-90a2-862a10545ce8
// Drawing, Positioning, and Cloning Images in GDI+
public void Method11()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet11>
Bitmap myBitmap = new Bitmap("Climber.jpg");
myGraphics.DrawImage(myBitmap, 10, 10);
// </snippet11>
}
public void Method12()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet12>
Bitmap myBMP = new Bitmap("SpaceCadet.bmp");
Bitmap myGIF = new Bitmap("Soda.gif");
Bitmap myJPEG = new Bitmap("Mango.jpg");
Bitmap myPNG = new Bitmap("Flowers.png");
Bitmap myTIFF = new Bitmap("MS.tif");
myGraphics.DrawImage(myBMP, 10, 10);
myGraphics.DrawImage(myGIF, 220, 10);
myGraphics.DrawImage(myJPEG, 280, 10);
myGraphics.DrawImage(myPNG, 150, 200);
myGraphics.DrawImage(myTIFF, 300, 200);
// </snippet12>
}
public void Method13()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet13>
Bitmap originalBitmap = new Bitmap("Spiral.png");
Rectangle sourceRectangle = new Rectangle(0, 0, originalBitmap.Width,
originalBitmap.Height / 2);
Bitmap secondBitmap = originalBitmap.Clone(sourceRectangle,
PixelFormat.DontCare);
myGraphics.DrawImage(originalBitmap, 10, 10);
myGraphics.DrawImage(secondBitmap, 150, 10);
// </snippet13>
}
// 51da872c-c783-440f-8bf6-1e580a966c31
// Metafiles in GDI+
// <snippet21>
public void Example_DisplayMetafile(PaintEventArgs e)
{
Graphics myGraphics = e.Graphics;
Metafile myMetafile = new Metafile("SampleMetafile.emf");
myGraphics.DrawImage(myMetafile, 100, 100);
}
// </snippet21>
// ad5daf26-005f-45bc-a2af-e0e97777a21a
// Cropping and Scaling Images in GDI+
public void Method31()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet31>
Bitmap myBitmap = new Bitmap("Spiral.png");
Rectangle expansionRectangle = new Rectangle(135, 10,
myBitmap.Width, myBitmap.Height);
Rectangle compressionRectangle = new Rectangle(300, 10,
myBitmap.Width / 2, myBitmap.Height / 2);
myGraphics.DrawImage(myBitmap, 10, 10);
myGraphics.DrawImage(myBitmap, expansionRectangle);
myGraphics.DrawImage(myBitmap, compressionRectangle);
// </snippet31>
}
public void Method32()
{
Graphics myGraphics = this.CreateGraphics();
// <snippet32>
Bitmap myBitmap = new Bitmap("Runner.jpg");
// One hand of the runner
Rectangle sourceRectangle = new Rectangle(80, 70, 80, 45);
// Compressed hand
Rectangle destRectangle1 = new Rectangle(200, 10, 20, 16);
// Expanded hand
Rectangle destRectangle2 = new Rectangle(200, 40, 200, 160);
// Draw the original image at (0, 0).
myGraphics.DrawImage(myBitmap, 0, 0);
// Draw the compressed hand.
myGraphics.DrawImage(
myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel);
// Draw the expanded hand.
myGraphics.DrawImage(
myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel);
// </snippet32>
}
}
@@ -0,0 +1,306 @@
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Drawing.Text;
using System;
public class Form1 :
System.Windows.Forms.Form
{
#region " Windows Form Designer generated code "
public Form1() : base()
{
//This call is required by the Windows Form Designer.
InitializeComponent();
ExtractAssociatedIconEx();
}
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough]
private void InitializeComponent()
{
// Form1
//
this.ClientSize = new System.Drawing.Size(292, 266);
this.Name = "Form1";
this.Text = "Form1";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
this.ResumeLayout(false);
}
#endregion
[System.STAThread]
public static void Main()
{
Application.Run(new Form1());
}
//<snippet1>
protected void DrawCaps(PaintEventArgs e)
{
GraphicsPath hPath = new GraphicsPath();
// Create the outline for our custom end cap.
hPath.AddLine(new Point(0, 0), new Point(0, 5));
hPath.AddLine(new Point(0, 5), new Point(5, 1));
hPath.AddLine(new Point(5, 1), new Point(3, 1));
// Construct the hook-shaped end cap.
CustomLineCap HookCap = new CustomLineCap(null, hPath);
// Set the start cap and end cap of the HookCap to be rounded.
HookCap.SetStrokeCaps(LineCap.Round, LineCap.Round);
// Create a pen and set end custom start and end
// caps to the hook cap.
Pen customCapPen = new Pen(Color.Black, 5);
customCapPen.CustomStartCap = HookCap;
customCapPen.CustomEndCap = HookCap;
// Create a second pen using the start and end caps from
// the hook cap.
Pen capPen = new Pen(Color.Red, 10);
LineCap startCap;
LineCap endCap;
HookCap.GetStrokeCaps(out startCap, out endCap);
capPen.StartCap = startCap;
capPen.EndCap = endCap;
// Create a line to draw.
Point[] points = { new Point(100, 100), new Point(200, 50),
new Point(250, 300) };
// Draw the lines.
e.Graphics.DrawLines(capPen, points);
e.Graphics.DrawLines(customCapPen, points);
}
//</snippet1>
//<snippet2>
private void ExtractAssociatedIconEx()
{
Icon ico =
Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe");
this.Icon = ico;
}
//</snippet2>
//<snippet3>
private void ConstructAnIconFromAType(PaintEventArgs e)
{
Icon icon1 = new Icon(typeof(Control), "Error.ico");
e.Graphics.DrawIcon(icon1, new Rectangle(10, 10, 50, 50));
}
//</snippet3>
// <snippet4>
private void ShowOutputChannels(PaintEventArgs e)
{
//Create a bitmap from a file.
Bitmap bmp1 = new Bitmap("c:\\fakePhoto.jpg");
// Create a new bitmap from the original, resizing it for this example.
Bitmap bmp2 = new Bitmap(bmp1, new Size(80, 80));
bmp1.Dispose();
// Create an ImageAttributes object.
ImageAttributes imgAttributes = new ImageAttributes();
// Draw the image unaltered.
e.Graphics.DrawImage(bmp2, 10, 10);
// Draw the image, showing the intensity of the cyan channel.
imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelC,
System.Drawing.Imaging.ColorAdjustType.Bitmap);
e.Graphics.DrawImage(bmp2, new Rectangle(100, 10, bmp2.Width, bmp2.Height),
0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes);
// Draw the image, showing the intensity of the magenta channel.
imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelM,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(bmp2, new Rectangle(10, 100, bmp2.Width, bmp2.Height),
0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes);
// Draw the image, showing the intensity of the yellow channel.
imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelY,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(bmp2, new Rectangle(100, 100, bmp2.Width, bmp2.Height), 0, 0,
bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes);
// Draw the image, showing the intensity of the black channel.
imgAttributes.SetOutputChannel(ColorChannelFlag.ColorChannelK,
System.Drawing.Imaging.ColorAdjustType.Bitmap);
e.Graphics.DrawImage(bmp2, new Rectangle(10, 190, bmp2.Width, bmp2.Height),
0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel, imgAttributes);
//Dispose of the bitmap.
bmp2.Dispose();
}
// </snippet4>
//<snippet5>
private void OpAdditionExample(PaintEventArgs e)
{
PointF point1 = new PointF(120.5F, 120F);
SizeF size1 = new SizeF(120.5F, 30.5F);
RectangleF rect1 = new RectangleF(point1, size1);
if (new PointF(rect1.Right, rect1.Bottom) == point1 + size1)
e.Graphics.DrawString("They are equal", this.Font, Brushes.Black, rect1);
else
e.Graphics.DrawString("They are not equal", this.Font, Brushes.Red, rect1);
}
//</snippet5>
//<snippet6>
private void AddExample(PaintEventArgs e)
{
PointF point1 = new PointF(120.5F, 120F);
SizeF size1 = new SizeF(20.5F, 20.5F);
RectangleF rect1 = new RectangleF(point1, size1);
PointF point2 = new PointF(rect1.Right, rect1.Bottom);
if (point2 != PointF.Add(point1, size1))
e.Graphics.DrawString("They are not equal", this.Font, Brushes.Red, rect1);
else
e.Graphics.DrawString("They are equal", this.Font, Brushes.Black, rect1);
}
//</snippet6>
//<snippet7>
private void SubtractExample(PaintEventArgs e)
{
PointF point1 = new PointF(120.5F, 120F);
SizeF size1 = new SizeF(120.5F, 30.5F);
PointF point2 = PointF.Subtract(point1, size1);
e.Graphics.DrawLine(Pens.Blue, point1, point2);
}
//</snippet7>
//<snippet8>
private void OpSubtractionExample(PaintEventArgs e)
{
PointF point1 = new PointF(120.5F, 120F);
SizeF size1 = new SizeF(20.5F, 20.5F);
PointF point2 = point1 - size1;
e.Graphics.DrawLine(Pens.Blue, point1, point2);
}
//</snippet8>
private void ShearColors(PaintEventArgs e)
{
//<snippet9>
Image image = new Bitmap("ColorBars.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
float[][] colorMatrixElements = {
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0.5f, 0, 1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10, width, height);
e.Graphics.DrawImage(
image,
new Rectangle(150, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
//</snippet9>
}
//<snippetInstalledFonts>
InstalledFontCollection ifc = new InstalledFontCollection();
private void EnumerateInstalledFonts(PaintEventArgs e)
{
FontFamily[] families = ifc.Families;
float x = 0.0F;
float y = 0.0F;
for (int i = 0; i < ifc.Families.Length; i++)
{
if (ifc.Families[i].IsStyleAvailable(FontStyle.Regular))
{
e.Graphics.DrawString(ifc.Families[i].Name, new Font(ifc.Families[i], 12),
Brushes.Black, x, y);
y += 20;
if (y % 700 == 0)
{
x += 140;
y = 0;
}
}
}
}
//</snippetInstalledFonts>
//<snippetConstructFontWithString>
private void ConstructFontWithString(PaintEventArgs e)
{
Font font1 = new Font("Arial", 20);
e.Graphics.DrawString("Arial Font", font1, Brushes.Red, new PointF(10, 10));
}
//</snippetConstructFontWithString>
public static Bitmap ResizeImage(System.Drawing.Image image)
{
//<snippetSetResolution>
Bitmap bitmap = new Bitmap(100, 100);
bitmap.SetResolution(96.0F, 96.0F);
//</snippetSetResolution>
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.DrawImage(image,
new Rectangle(0, 0, 100, 100),
new Rectangle(0, 0, image.Width, image.Height),
GraphicsUnit.Pixel);
}
return bitmap;
}
//<snippetGetThumbnail>
public bool ThumbnailCallback()
{
return false;
}
public void Example_GetThumb(PaintEventArgs e)
{
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap = new Bitmap("Climber.jpg");
Image myThumbnail = myBitmap.GetThumbnailImage(
40, 40, myCallback, IntPtr.Zero);
e.Graphics.DrawImage(myThumbnail, 150, 75);
}
//</snippetGetThumbnail>
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawCaps(e);
//ConstructAnIconFromAType(e);
ShowOutputChannels(e);
}
}
@@ -0,0 +1,263 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public class SystemDrawingMiscLegacyTopics
{
// 1e717711-1361-448e-aa49-0f3ec43110c9
// Using the World Transformation
private void Method11(PaintEventArgs e)
{
// <snippet11>
Rectangle rect = new Rectangle(0, 0, 50, 50);
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
e.Graphics.DrawRectangle(pen, rect);
// </snippet11>
}
private void Method12(PaintEventArgs e)
{
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
Rectangle rect = new Rectangle(0, 0, 50, 50);
// <snippet12>
e.Graphics.ScaleTransform(1.75f, 0.5f);
e.Graphics.DrawRectangle(pen, rect);
// </snippet12>
}
private void Method13(PaintEventArgs e)
{
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
Rectangle rect = new Rectangle(0, 0, 50, 50);
// <snippet13>
e.Graphics.ResetTransform();
e.Graphics.RotateTransform(28); // 28 degrees
e.Graphics.DrawRectangle(pen, rect);
// </snippet13>
}
private void Method14(PaintEventArgs e)
{
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
Rectangle rect = new Rectangle(0, 0, 50, 50);
// <snippet14>
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(150, 150);
e.Graphics.DrawRectangle(pen, rect);
// </snippet14>
}
// 37d5f9dc-a5cf-4475-aa5d-34d714e808a9
// Why Transformation Order Is Significant
private void Method21(PaintEventArgs e)
{
// <snippet21>
Rectangle rect = new Rectangle(0, 0, 50, 50);
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
e.Graphics.ResetTransform();
e.Graphics.ScaleTransform(1.75f, 0.5f);
e.Graphics.RotateTransform(28, MatrixOrder.Append);
e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append);
e.Graphics.DrawRectangle(pen, rect);
// </snippet21>
}
private void Method22(PaintEventArgs e)
{
// <snippet22>
Rectangle rect = new Rectangle(0, 0, 50, 50);
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append);
e.Graphics.RotateTransform(28, MatrixOrder.Append);
e.Graphics.ScaleTransform(1.75f, 0.5f);
e.Graphics.DrawRectangle(pen, rect);
// </snippet22>
}
private void Method23(PaintEventArgs e)
{
// <snippet23>
Rectangle rect = new Rectangle(0, 0, 50, 50);
Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(150, 150, MatrixOrder.Prepend);
e.Graphics.RotateTransform(28, MatrixOrder.Prepend);
e.Graphics.ScaleTransform(1.75f, 0.5f);
e.Graphics.DrawRectangle(pen, rect);
// </snippet23>
}
// 3a4c07cb-a40a-4d14-ad35-008f531910a8
// How to: Use Hit Testing with a Region
private void Method31(PaintEventArgs e)
{
// <snippet31>
Point point = new Point(60, 10);
// Assume that the variable "point" contains the location of the
// most recent mouse click.
// To simulate a hit, assign (60, 10) to point.
// To simulate a miss, assign (0, 0) to point.
SolidBrush solidBrush = new SolidBrush(Color.Black);
Region region1 = new Region(new Rectangle(50, 0, 50, 150));
Region region2 = new Region(new Rectangle(0, 50, 150, 50));
// Create a plus-shaped region by forming the union of region1 and
// region2.
// The union replaces region1.
region1.Union(region2);
if (region1.IsVisible(point, e.Graphics))
{
// The point is in the region. Use an opaque brush.
solidBrush.Color = Color.FromArgb(255, 255, 0, 0);
}
else
{
// The point is not in the region. Use a semitransparent brush.
solidBrush.Color = Color.FromArgb(64, 255, 0, 0);
}
e.Graphics.FillRegion(solidBrush, region1);
// </snippet31>
}
// 43d121b4-e14c-4901-b25c-2d6c25ba4e29
// How to: Use Clipping with a Region
private void Method41(PaintEventArgs e)
{
// <snippet41>
// Create a path that consists of a single polygon.
Point[] polyPoints = {
new Point(10, 10),
new Point(150, 10),
new Point(100, 75),
new Point(100, 150)};
GraphicsPath path = new GraphicsPath();
path.AddPolygon(polyPoints);
// Construct a region based on the path.
Region region = new Region(path);
// Draw the outline of the region.
Pen pen = Pens.Black;
e.Graphics.DrawPath(pen, path);
// Set the clipping region of the Graphics object.
e.Graphics.SetClip(region, CombineMode.Replace);
// Draw some clipped strings.
FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
fontFamily,
36, FontStyle.Bold,
GraphicsUnit.Pixel);
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 255, 0, 0));
e.Graphics.DrawString(
"A Clipping Region",
font, solidBrush,
new PointF(15, 25));
e.Graphics.DrawString(
"A Clipping Region",
font,
solidBrush,
new PointF(15, 68));
// </snippet41>
}
// a0d9f178-43a4-4323-bb5a-d3e3f77ae6c1
// Using Nested Graphics Containers
private void Method61(PaintEventArgs e)
{
// <snippet61>
Graphics graphics = e.Graphics;
Pen pen = new Pen(Color.Red);
GraphicsContainer graphicsContainer;
graphics.FillRectangle(Brushes.Black, 100, 80, 3, 3);
graphics.TranslateTransform(100, 80);
graphicsContainer = graphics.BeginContainer();
graphics.RotateTransform(30);
graphics.DrawRectangle(pen, -60, -30, 120, 60);
graphics.EndContainer(graphicsContainer);
graphics.DrawRectangle(pen, -60, -30, 120, 60);
// </snippet61>
}
private void Method62(PaintEventArgs e)
{
// <snippet62>
Graphics graphics = e.Graphics;
GraphicsContainer graphicsContainer;
Pen redPen = new Pen(Color.Red, 2);
Pen bluePen = new Pen(Color.Blue, 2);
SolidBrush aquaBrush = new SolidBrush(Color.FromArgb(255, 180, 255, 255));
SolidBrush greenBrush = new SolidBrush(Color.FromArgb(255, 150, 250, 130));
graphics.SetClip(new Rectangle(50, 65, 150, 120));
graphics.FillRectangle(aquaBrush, 50, 65, 150, 120);
graphicsContainer = graphics.BeginContainer();
// Create a path that consists of a single ellipse.
GraphicsPath path = new GraphicsPath();
path.AddEllipse(75, 50, 100, 150);
// Construct a region based on the path.
Region region = new Region(path);
graphics.FillRegion(greenBrush, region);
graphics.SetClip(region, CombineMode.Replace);
graphics.DrawLine(redPen, 50, 0, 350, 300);
graphics.EndContainer(graphicsContainer);
graphics.DrawLine(bluePen, 70, 0, 370, 300);
// </snippet62>
}
private void Method63(PaintEventArgs e)
{
// <snippet63>
Graphics graphics = e.Graphics;
GraphicsContainer innerContainer;
GraphicsContainer outerContainer;
SolidBrush brush = new SolidBrush(Color.Blue);
FontFamily fontFamily = new FontFamily("Times New Roman");
Font font = new Font(fontFamily, 36, FontStyle.Regular, GraphicsUnit.Pixel);
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
outerContainer = graphics.BeginContainer();
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
innerContainer = graphics.BeginContainer();
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
graphics.DrawString(
"Inner Container",
font,
brush,
new PointF(20, 10));
graphics.EndContainer(innerContainer);
graphics.DrawString(
"Outer Container",
font,
brush,
new PointF(20, 50));
graphics.EndContainer(outerContainer);
graphics.DrawString(
"Graphics Object",
font,
brush,
new PointF(20, 90));
// </snippet63>
}
}
@@ -0,0 +1,87 @@
//<snippet0>
using System;
using System.Drawing;
using System.IO;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace PrintApp
{
public class Form1 : Form
{
private Button printButton;
//<snippet8>
private PrintDocument printDocument1 = new PrintDocument();
private string stringToPrint;
//</snippet8>
public Form1()
{
this.printButton = new System.Windows.Forms.Button();
this.printButton.Location = new System.Drawing.Point(12, 51);
this.printButton.Size = new System.Drawing.Size(75, 23);
this.printButton.Text = "Print";
this.printButton.Click += new System.EventHandler(this.printButton_Click);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.printButton);
// Associate the PrintPage event handler with the PrintPage event.
printDocument1.PrintPage +=
new PrintPageEventHandler(printDocument1_PrintPage);
}
private void ReadFile()
{
//<snippet1>
string docName = "testPage.txt";
string docPath = @"c:\";
printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
{
stringToPrint = reader.ReadToEnd();
}
//</snippet1>
}
//<snippet2>
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
}
//</snippet2>
private void printButton_Click(object sender, EventArgs e)
{
ReadFile();
//<snippet5>
printDocument1.Print();
//</snippet5>
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
//</snippet0>
@@ -0,0 +1,100 @@
//<snippet0>
using System;
using System.Drawing;
using System.IO;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace PrintPreviewApp
{
public partial class Form1 : Form
{
private Button printPreviewButton;
//<snippet1>
private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
private PrintDocument printDocument1 = new PrintDocument();
// Declare a string to hold the entire document contents.
private string documentContents;
// Declare a variable to hold the portion of the document that
// is not printed.
private string stringToPrint;
//</snippet1>
public Form1()
{
this.printPreviewButton = new System.Windows.Forms.Button();
this.printPreviewButton.Location = new System.Drawing.Point(12, 12);
this.printPreviewButton.Size = new System.Drawing.Size(125, 23);
this.printPreviewButton.Text = "Print Preview";
this.printPreviewButton.Click += new System.EventHandler(this.printPreviewButton_Click);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.printPreviewButton);
printDocument1.PrintPage +=
new PrintPageEventHandler(printDocument1_PrintPage);
}
//<snippet2>
private void ReadDocument()
{
string docName = "testPage.txt";
string docPath = @"c:\";
printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
{
documentContents = reader.ReadToEnd();
}
stringToPrint = documentContents;
}
//</snippet2>
//<snippet3>
void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page.
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
// If there are no more pages, reset the string to be printed.
if (!e.HasMorePages)
stringToPrint = documentContents;
}
//</snippet3>
//<snippet4>
private void printPreviewButton_Click(object sender, EventArgs e)
{
ReadDocument();
//<snippet5>
printPreviewDialog1.Document = printDocument1;
//</snippet5>
printPreviewDialog1.ShowDialog();
}
//</snippet4>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
//</snippet0>
@@ -0,0 +1,187 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Imaging;
public class SystemDrawingRecoloringImages
{
// 2106fb9a-4d60-4dcf-9220-9f189a6c4d19
// How to: Translate Image Colors
private void Method11(PaintEventArgs e)
{
// <snippet11>
Image image = new Bitmap("ColorBars.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
float[][] colorMatrixElements = {
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {.75f, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10, width, height);
e.Graphics.DrawImage(
image,
new Rectangle(150, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
// </snippet11>
}
// 44df4556-a433-49c0-ac0f-9a12063a5860
// How to: Use a Color Matrix to Transform a Single Color
private void Method21(PaintEventArgs e)
{
// <snippet21>
Image image = new Bitmap("InputColor.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
float[][] colorMatrixElements = {
new float[] {2, 0, 0, 0, 0}, // red scaling factor of 2
new float[] {0, 1, 0, 0, 0}, // green scaling factor of 1
new float[] {0, 0, 1, 0, 0}, // blue scaling factor of 1
new float[] {0, 0, 0, 1, 0}, // alpha scaling factor of 1
new float[] {.2f, .2f, .2f, 0, 1}}; // three translations of 0.2
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10);
e.Graphics.DrawImage(
image,
new Rectangle(120, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
// </snippet21>
}
// 977df1ce-8665-42d4-9fb1-ef7f0ff63419
// How to: Use a Color Remap Table
private void Method31(PaintEventArgs e)
{
// <snippet31>
Image image = new Bitmap("RemapInput.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
ColorMap colorMap = new ColorMap();
colorMap.OldColor = Color.FromArgb(255, 255, 0, 0); // opaque red
colorMap.NewColor = Color.FromArgb(255, 0, 0, 255); // opaque blue
ColorMap[] remapTable = { colorMap };
imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10, width, height);
e.Graphics.DrawImage(
image,
new Rectangle(150, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
// </snippet31>
}
// df23c887-7fd6-4b15-ad94-e30b5bd4b849
// Using Transformations to Scale Colors
private void Method41(PaintEventArgs e)
{
// <snippet41>
Image image = new Bitmap("ColorBars2.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
float[][] colorMatrixElements = {
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 2, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10, width, height);
e.Graphics.DrawImage(
image,
new Rectangle(150, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
// </snippet41>
}
private void Method42(PaintEventArgs e)
{
// <snippet42>
Image image = new Bitmap("ColorBars.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
float[][] colorMatrixElements = {
new float[] {.75F, 0, 0, 0, 0},
new float[] {0, .65F, 0, 0, 0},
new float[] {0, 0, .5F, 0, 0},
new float[] {0, 0, 0, 1F, 0},
new float[] {0, 0, 0, 0, 1F}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10, width, height);
e.Graphics.DrawImage(
image,
new Rectangle(150, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
// </snippet42>
}
}
@@ -0,0 +1,70 @@
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
#endregion
namespace RotateColors
{
public class Form1 : Form
{
public Form1()
{
this.Paint +=new PaintEventHandler(Form1_Paint);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
void Form1_Paint(object sender, PaintEventArgs e)
{
RotateColors(e);
}
//<snippet1>
private void RotateColors(PaintEventArgs e)
{
Bitmap image = new Bitmap("RotationInput.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
float degrees = 60f;
double r = degrees * System.Math.PI / 180; // degrees to radians
float[][] colorMatrixElements = {
new float[] {(float)System.Math.Cos(r), (float)System.Math.Sin(r), 0, 0, 0},
new float[] {(float)-System.Math.Sin(r), (float)-System.Math.Cos(r), 0, 0, 0},
new float[] {0, 0, 2, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(
colorMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
e.Graphics.DrawImage(image, 10, 10, width, height);
e.Graphics.DrawImage(
image,
new Rectangle(150, 10, width, height), // destination rectangle
0, 0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
imageAttributes);
}
//</snippet1>
}
}
@@ -0,0 +1,100 @@
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
public class class1
{
// 06088b31-bac9-4ef3-9ebe-06c2c764d6df
// How to: Fill a Shape with a Solid Color
public void Method11(PaintEventArgs e)
{
// <snippet11>
SolidBrush solidBrush = new SolidBrush(
Color.FromArgb(255, 255, 0, 0));
e.Graphics.FillEllipse(solidBrush, 0, 0, 100, 60);
// </snippet11>
}
// 508da5a6-2433-4d2b-9680-eaeae4e96e3b
// How to: Fill a Shape with an Image Texture
public void Method21(PaintEventArgs e)
{
// <snippet21>
Image image = new Bitmap("ImageFile.jpg");
TextureBrush tBrush = new TextureBrush(image);
tBrush.Transform = new Matrix(
75.0f / 640.0f,
0.0f,
0.0f,
75.0f / 480.0f,
0.0f,
0.0f);
e.Graphics.FillEllipse(tBrush, new Rectangle(0, 150, 150, 250));
// </snippet21>
}
// 6d407891-6e5c-4495-a546-3da5604e9fb8
// How to: Tile a Shape with an Image
public void Method31(PaintEventArgs e)
{
// <snippet31>
Image image = new Bitmap("HouseAndTree.gif");
TextureBrush tBrush = new TextureBrush(image);
Pen blackPen = new Pen(Color.Black);
e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200));
e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200));
// </snippet31>
}
public void Method32(PaintEventArgs e)
{
// <snippet32>
Image image = new Bitmap("HouseAndTree.gif");
TextureBrush tBrush = new TextureBrush(image);
Pen blackPen = new Pen(Color.Black);
tBrush.WrapMode = WrapMode.TileFlipX;
e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200));
e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200));
// </snippet32>
}
public void Method33(PaintEventArgs e)
{
// <snippet33>
Image image = new Bitmap("HouseAndTree.gif");
TextureBrush tBrush = new TextureBrush(image);
Pen blackPen = new Pen(Color.Black);
tBrush.WrapMode = WrapMode.TileFlipY;
e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200));
e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200));
// </snippet33>
}
public void Method34(PaintEventArgs e)
{
// <snippet34>
Image image = new Bitmap("HouseAndTree.gif");
TextureBrush tBrush = new TextureBrush(image);
Pen blackPen = new Pen(Color.Black);
tBrush.WrapMode = WrapMode.TileFlipXY;
e.Graphics.FillRectangle(tBrush, new Rectangle(0, 0, 200, 200));
e.Graphics.DrawRectangle(blackPen, new Rectangle(0, 0, 200, 200));
// </snippet34>
}
// 9c8300ff-187b-404f-af1f-ebd499f5b16f
// How to: Fill a Shape with a Hatch Pattern
public void Method41(PaintEventArgs e)
{
// <snippet41>
HatchBrush hBrush = new HatchBrush(
HatchStyle.Horizontal,
Color.Red,
Color.FromArgb(255, 128, 255, 255));
e.Graphics.FillEllipse(hBrush, 0, 0, 100, 60);
// </snippet41>
}
}
@@ -0,0 +1,133 @@
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
public class Form1 : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
// 0828c331-a438-4bdd-a4d6-3ef1e59e8795
// How to: Use a Pen to Draw Lines
public void Method11(PaintEventArgs e)
{
// <snippet11>
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0));
e.Graphics.DrawLine(pen, 20, 10, 300, 100);
// </snippet11>
}
// 54a7fa14-3ad8-4d64-b424-2a12005b250c
// How to: Use a Pen to Draw Rectangles
public void Method21(PaintEventArgs e)
{
// <snippet21>
Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 5);
e.Graphics.DrawRectangle(blackPen, 10, 10, 100, 50);
// </snippet21>
}
// 9fc480c2-3c75-4fd1-8ab5-296a99e820e2
// How to: Join Lines
public void Method31(PaintEventArgs e)
{
// <snippet31>
GraphicsPath path = new GraphicsPath();
Pen penJoin = new Pen(Color.FromArgb(255, 0, 0, 255), 8);
path.StartFigure();
path.AddLine(new Point(50, 200), new Point(100, 200));
path.AddLine(new Point(100, 200), new Point(100, 250));
penJoin.LineJoin = LineJoin.Bevel;
e.Graphics.DrawPath(penJoin, path);
// </snippet31>
}
// a202af36-4d31-4401-a126-b232f51db581
// How to: Set Pen Width and Alignment
public void Method41(PaintEventArgs e)
{
// <snippet41>
Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
greenPen.Alignment = PenAlignment.Center;
// Draw the line with the wide green pen.
e.Graphics.DrawLine(greenPen, 10, 100, 100, 50);
// Draw the line with the thin black pen.
e.Graphics.DrawLine(blackPen, 10, 100, 100, 50);
// </snippet41>
}
public void Method42(PaintEventArgs e)
{
// <snippet42>
Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
greenPen.Alignment = PenAlignment.Center;
// Draw the rectangle with the wide green pen.
e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50);
// Draw the rectangle with the thin black pen.
e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50);
// </snippet42>
}
public void Method43(PaintEventArgs e)
{
Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
// <snippet43>
greenPen.Alignment = PenAlignment.Inset;
// </snippet43>
}
// cd0ed96a-cce4-47b9-b58a-3bae2e3d1bee
// How to: Draw a Custom Dashed Line
public void Method51(PaintEventArgs e)
{
// <snippet51>
float[] dashValues = { 5, 2, 15, 4 };
Pen blackPen = new Pen(Color.Black, 5);
blackPen.DashPattern = dashValues;
e.Graphics.DrawLine(blackPen, new Point(5, 5), new Point(405, 5));
// </snippet51>
}
// dc9118cc-f3c2-42e5-8173-f46d41d18fd5
// How to: Draw a Line Filled with a Texture
public void Method61(PaintEventArgs e)
{
// <snippet61>
Bitmap bitmap = new Bitmap("Texture1.jpg");
TextureBrush tBrush = new TextureBrush(bitmap);
Pen texturedPen = new Pen(tBrush, 30);
e.Graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
e.Graphics.DrawEllipse(texturedPen, 100, 20, 200, 100);
// </snippet61>
}
// eb68c3e1-c400-4886-8a04-76978a429cb6
// How to: Draw a Line with Line Caps
public void Method71(PaintEventArgs e)
{
// <snippet71>
Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255), 8);
pen.StartCap = LineCap.ArrowAnchor;
pen.EndCap = LineCap.RoundAnchor;
e.Graphics.DrawLine(pen, 20, 175, 300, 175);
// </snippet71>
}
}
@@ -0,0 +1,308 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Drawing2D;
public class class1
{
// 1948e834-e104-481c-b71d-d8aa9e4d106e
// How to: Create a Path Gradient
// <snippet11>
public void FillEllipseWithPathGradient(PaintEventArgs e)
{
// Create a path that consists of a single ellipse.
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, 140, 70);
// Use the path to construct a brush.
PathGradientBrush pthGrBrush = new PathGradientBrush(path);
// Set the color at the center of the path to blue.
pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
// Set the color along the entire boundary
// of the path to aqua.
Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
pthGrBrush.SurroundColors = colors;
e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70);
}
// </snippet11>
// <snippet12>
public void ConstructBrushFromStarShapedPath(PaintEventArgs e)
{
// Put the points of a polygon in an array.
Point[] points = {
new Point(75, 0),
new Point(100, 50),
new Point(150, 50),
new Point(112, 75),
new Point(150, 150),
new Point(75, 100),
new Point(0, 150),
new Point(37, 75),
new Point(0, 50),
new Point(50, 50)};
// Use the array of points to construct a path.
GraphicsPath path = new GraphicsPath();
path.AddLines(points);
// Use the path to construct a path gradient brush.
PathGradientBrush pthGrBrush = new PathGradientBrush(path);
// Set the color at the center of the path to red.
pthGrBrush.CenterColor = Color.FromArgb(255, 255, 0, 0);
// Set the colors of the points in the array.
Color[] colors = {
Color.FromArgb(255, 0, 0, 0),
Color.FromArgb(255, 0, 255, 0),
Color.FromArgb(255, 0, 0, 255),
Color.FromArgb(255, 255, 255, 255),
Color.FromArgb(255, 0, 0, 0),
Color.FromArgb(255, 0, 255, 0),
Color.FromArgb(255, 0, 0, 255),
Color.FromArgb(255, 255, 255, 255),
Color.FromArgb(255, 0, 0, 0),
Color.FromArgb(255, 0, 255, 0)};
pthGrBrush.SurroundColors = colors;
// Fill the path with the path gradient brush.
e.Graphics.FillPath(pthGrBrush, path);
}
// </snippet12>
// <snippet13>
public void DrawPathGradentWthoutGraphicsPath(PaintEventArgs e)
{
// Construct a path gradient brush based on an array of points.
PointF[] ptsF = {
new PointF(0, 0),
new PointF(160, 0),
new PointF(160, 200),
new PointF(80, 150),
new PointF(0, 200)};
PathGradientBrush pBrush = new PathGradientBrush(ptsF);
// An array of five points was used to construct the path gradient
// brush. Set the color of each point in that array.
Color[] colors = {
Color.FromArgb(255, 255, 0, 0), // (0, 0) red
Color.FromArgb(255, 0, 255, 0), // (160, 0) green
Color.FromArgb(255, 0, 255, 0), // (160, 200) green
Color.FromArgb(255, 0, 0, 255), // (80, 150) blue
Color.FromArgb(255, 255, 0, 0)}; // (0, 200) red
pBrush.SurroundColors = colors;
// Set the center color to white.
pBrush.CenterColor = Color.White;
// Use the path gradient brush to fill a rectangle.
e.Graphics.FillRectangle(pBrush, new Rectangle(0, 0, 160, 200));
}
// </snippet13>
// <snippet14>
public void CustomizePathGradientBrush(PaintEventArgs e)
{
// Create a path that consists of a single ellipse.
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, 200, 100);
// Create a path gradient brush based on the elliptical path.
PathGradientBrush pthGrBrush = new PathGradientBrush(path);
// Set the color along the entire boundary to blue.
Color[] color = { Color.Blue };
pthGrBrush.SurroundColors = color;
// Set the center color to aqua.
pthGrBrush.CenterColor = Color.Aqua;
// Use the path gradient brush to fill the ellipse.
e.Graphics.FillPath(pthGrBrush, path);
// Set the focus scales for the path gradient brush.
pthGrBrush.FocusScales = new PointF(0.3f, 0.8f);
// Use the path gradient brush to fill the ellipse again.
// Show this filled ellipse to the right of the first filled ellipse.
e.Graphics.TranslateTransform(220.0f, 0.0f);
e.Graphics.FillPath(pthGrBrush, path);
}
// </snippet14>
// <snippet15>
public void CustomizeWithInterpolation(PaintEventArgs e)
{
// Vertices of the outer triangle
Point[] points = {
new Point(100, 0),
new Point(200, 200),
new Point(0, 200)};
// No GraphicsPath object is created. The PathGradientBrush
// object is constructed directly from the array of points.
PathGradientBrush pthGrBrush = new PathGradientBrush(points);
Color[] colors = {
Color.FromArgb(255, 0, 128, 0), // dark green
Color.FromArgb(255, 0, 255, 255), // aqua
Color.FromArgb(255, 0, 0, 255)}; // blue
float[] relativePositions = {
0f, // Dark green is at the boundary of the triangle.
0.4f, // Aqua is 40 percent of the way from the boundary
// to the center point.
1.0f}; // Blue is at the center point.
ColorBlend colorBlend = new ColorBlend();
colorBlend.Colors = colors;
colorBlend.Positions = relativePositions;
pthGrBrush.InterpolationColors = colorBlend;
// Fill a rectangle that is larger than the triangle
// specified in the Point array. The portion of the
// rectangle outside the triangle will not be painted.
e.Graphics.FillRectangle(pthGrBrush, 0, 0, 200, 200);
}
// </snippet15>
// <snippet16>
public void SetCenterPoint(PaintEventArgs e)
{
// Create a path that consists of a single ellipse.
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, 140, 70);
// Use the path to construct a brush.
PathGradientBrush pthGrBrush = new PathGradientBrush(path);
// Set the center point to a location that is not
// the centroid of the path.
pthGrBrush.CenterPoint = new PointF(120, 40);
// Set the color at the center of the path to blue.
pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
// Set the color along the entire boundary
// of the path to aqua.
Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
pthGrBrush.SurroundColors = colors;
e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70);
}
// </snippet16>
// <snippet17>
public void SetCenterPointOutsidePath(PaintEventArgs e)
{
// Create a path that consists of a single ellipse.
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, 140, 70);
// Use the path to construct a brush.
PathGradientBrush pthGrBrush = new PathGradientBrush(path);
// Set the center point to a location that is not
// the centroid of the path.
pthGrBrush.CenterPoint = new PointF(145, 35);
// Set the color at the center of the path to blue.
pthGrBrush.CenterColor = Color.FromArgb(255, 0, 0, 255);
// Set the color along the entire boundary
// of the path to aqua.
Color[] colors = { Color.FromArgb(255, 0, 255, 255) };
pthGrBrush.SurroundColors = colors;
e.Graphics.FillEllipse(pthGrBrush, 0, 0, 140, 70);
}
// </snippet17>
// 6c88e1cc-1217-4399-ac12-cb37592b9f01
// How to: Create a Linear Gradient
// <snippet21>
public void UseHorizontalLinearGradients(PaintEventArgs e)
{
LinearGradientBrush linGrBrush = new LinearGradientBrush(
new Point(0, 10),
new Point(200, 10),
Color.FromArgb(255, 255, 0, 0), // Opaque red
Color.FromArgb(255, 0, 0, 255)); // Opaque blue
Pen pen = new Pen(linGrBrush);
e.Graphics.DrawLine(pen, 0, 10, 200, 10);
e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100);
e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30);
}
// </snippet21>
// <snippet22>
public void CustomizeLinearGradients(PaintEventArgs e)
{
LinearGradientBrush linGrBrush = new LinearGradientBrush(
new Point(0, 10),
new Point(200, 10),
Color.FromArgb(255, 0, 0, 0), // Opaque black
Color.FromArgb(255, 255, 0, 0)); // Opaque red
float[] relativeIntensities = { 0.0f, 0.5f, 1.0f };
float[] relativePositions = { 0.0f, 0.2f, 1.0f };
//Create a Blend object and assign it to linGrBrush.
Blend blend = new Blend();
blend.Factors = relativeIntensities;
blend.Positions = relativePositions;
linGrBrush.Blend = blend;
e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100);
e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30);
}
// </snippet22>
// <snippet23>
public void CreateDiagonalLinearGradients(PaintEventArgs e)
{
LinearGradientBrush linGrBrush = new LinearGradientBrush(
new Point(0, 0),
new Point(200, 100),
Color.FromArgb(255, 0, 0, 255), // opaque blue
Color.FromArgb(255, 0, 255, 0)); // opaque green
Pen pen = new Pen(linGrBrush, 10);
e.Graphics.DrawLine(pen, 0, 0, 600, 300);
e.Graphics.FillEllipse(linGrBrush, 10, 100, 200, 100);
}
// </snippet23>
// da4690e7-5fac-4fd2-b3f0-5cb35c165b92
// How to: Apply Gamma Correction to a Gradient
// <snippet31>
public void FillTwoRectangles(PaintEventArgs e)
{
LinearGradientBrush linGrBrush = new LinearGradientBrush(
new Point(0, 10),
new Point(200, 10),
Color.Red,
Color.Blue);
e.Graphics.FillRectangle(linGrBrush, 0, 0, 200, 50);
linGrBrush.GammaCorrection = true;
e.Graphics.FillRectangle(linGrBrush, 0, 60, 200, 50);
}
// </snippet31>
}
@@ -0,0 +1,267 @@
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
public class SystemDrawingWorkingWithImages : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SystemDrawingWorkingWithImages());
}
// 053e3360-bca0-4b25-9afa-0e77a6f17b03
// How to: Crop and Scale Images
private void Method11(PaintEventArgs e)
{
// <snippet11>
Image image = new Bitmap("Apple.gif");
// Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0);
// Make the destination rectangle 30 percent wider and
// 30 percent taller than the original image.
// Put the upper-left corner of the destination
// rectangle at (150, 20).
int width = image.Width;
int height = image.Height;
RectangleF destinationRect = new RectangleF(
150,
20,
1.3f * width,
1.3f * height);
// Draw a portion of the image. Scale that portion of the image
// so that it fills the destination rectangle.
RectangleF sourceRect = new RectangleF(0, 0, .75f * width, .75f * height);
e.Graphics.DrawImage(
image,
destinationRect,
sourceRect,
GraphicsUnit.Pixel);
// </snippet11>
}
// 5bc558d7-b326-4050-a834-b8600da0de95
// How to: Load and Display Bitmaps
private void Method21(PaintEventArgs e)
{
// <snippet21>
Bitmap bitmap = new Bitmap("Grapes.jpg");
e.Graphics.DrawImage(bitmap, 60, 10);
// </snippet21>
}
// 5fe2c95d-8653-4d55-bf0d-e5afa28f223b
// How to: Improve Performance by Avoiding Automatic Scaling
private void Method31(PaintEventArgs e)
{
Image image = new Bitmap("Texture.jpg");
// <snippet31>
e.Graphics.DrawImage(image, 50, 30); // upper-left corner at (50, 30)
// </snippet31>
}
private void Method32(PaintEventArgs e)
{
// <snippet32>
Image image = new Bitmap("Texture.jpg");
e.Graphics.DrawImage(image, 10, 10);
e.Graphics.DrawImage(image, 120, 10, image.Width, image.Height);
// </snippet32>
}
// 60af1714-f148-4d85-a739-0557965ffa73
// How to: Load and Display Metafiles
private void Method41(PaintEventArgs e)
{
// <snippet41>
Metafile metafile = new Metafile("SampleMetafile.emf");
e.Graphics.DrawImage(metafile, 60, 10);
// </snippet41>
}
// 72ec0b31-0be7-444a-9575-1dbcb864e0be
// How to: Read Image Metadata
private void Method51(PaintEventArgs e)
{
// <snippet51>
// Create an Image object.
Image image = new Bitmap(@"c:\FakePhoto.jpg");
// Get the PropertyItems property from image.
PropertyItem[] propItems = image.PropertyItems;
// Set up the display.
Font font = new Font("Arial", 12);
SolidBrush blackBrush = new SolidBrush(Color.Black);
int X = 0;
int Y = 0;
// For each PropertyItem in the array, display the ID, type, and
// length.
int count = 0;
foreach (PropertyItem propItem in propItems)
{
e.Graphics.DrawString(
"Property Item " + count.ToString(),
font,
blackBrush,
X, Y);
Y += font.Height;
e.Graphics.DrawString(
" id: 0x" + propItem.Id.ToString("x"),
font,
blackBrush,
X, Y);
Y += font.Height;
e.Graphics.DrawString(
" type: " + propItem.Type.ToString(),
font,
blackBrush,
X, Y);
Y += font.Height;
e.Graphics.DrawString(
" length: " + propItem.Len.ToString() + " bytes",
font,
blackBrush,
X, Y);
Y += font.Height;
count++;
}
// Convert the value of the second property to a string, and display
// it.
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string manufacturer = encoding.GetString(propItems[1].Value);
e.Graphics.DrawString(
"The equipment make is " + manufacturer + ".",
font,
blackBrush,
X, Y);
// </snippet51>
}
// a3bf97eb-63ed-425a-ba07-dcc65efb567c
// How to: Rotate, Reflect, and Skew Images
private void Method61(PaintEventArgs e)
{
// <snippet61>
Point[] destinationPoints = {
new Point(200, 20), // destination for upper-left point of
// original
new Point(110, 100), // destination for upper-right point of
// original
new Point(250, 30)}; // destination for lower-left point of
// original
Image image = new Bitmap("Stripes.bmp");
// Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0);
// Draw the image mapped to the parallelogram.
e.Graphics.DrawImage(image, destinationPoints);
// </snippet61>
}
// e956242a-1e5b-4217-a3cf-5f3fb45d00ba
// How to: Create Thumbnail Images
// <snippet71>
public bool ThumbnailCallback()
{
return true;
}
private void GetThumbnail(PaintEventArgs e)
{
Image.GetThumbnailImageAbort callback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Image image = new Bitmap(@"c:\FakePhoto.jpg");
Image pThumbnail = image.GetThumbnailImage(100, 100, callback, new
IntPtr());
e.Graphics.DrawImage(
pThumbnail,
10,
10,
pThumbnail.Width,
pThumbnail.Height);
}
// </snippet71>
// fde9bccf-8aa5-4b0d-ba4b-788740627b02
// How to: Use Interpolation Mode to Control Image Quality During Scaling
private void Method81(PaintEventArgs e)
{
// <snippet81>
Image image = new Bitmap("GrapeBunch.bmp");
int width = image.Width;
int height = image.Height;
// Draw the image with no shrinking or stretching.
e.Graphics.DrawImage(
image,
new Rectangle(10, 10, width, height), // destination rectangle
0,
0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel,
null);
// Shrink the image using low-quality interpolation.
e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
e.Graphics.DrawImage(
image,
new Rectangle(10, 250, (int)(0.6 * width), (int)(0.6 * height)),
// destination rectangle
0,
0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel);
// Shrink the image using medium-quality interpolation.
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
e.Graphics.DrawImage(
image,
new Rectangle(150, 250, (int)(0.6 * width), (int)(0.6 * height)),
// destination rectangle
0,
0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel);
// Shrink the image using high-quality interpolation.
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.DrawImage(
image,
new Rectangle(290, 250, (int)(0.6 * width), (int)(0.6 * height)),
// destination rectangle
0,
0, // upper-left corner of source rectangle
width, // width of source rectangle
height, // height of source rectangle
GraphicsUnit.Pixel);
// </snippet81>
}
}
@@ -0,0 +1,125 @@
// <snippet1>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
namespace SoundPlayerLoadAsyncExample
{
public class Form1 : Form
{
private SoundPlayer Player = new SoundPlayer();
public Form1()
{
InitializeComponent();
this.Player.LoadCompleted += new AsyncCompletedEventHandler(Player_LoadCompleted);
}
private void playSoundButton_Click(object sender, EventArgs e)
{
this.LoadAsyncSound();
}
public void LoadAsyncSound()
{
try
{
// Replace this file name with a valid file name.
this.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav";
this.Player.LoadAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error loading sound");
}
}
// This is the event handler for the LoadCompleted event.
void Player_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (Player.IsLoadCompleted)
{
try
{
this.Player.Play();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error playing sound");
}
}
}
private Button playSoundButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.playSoundButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// playSoundButton
//
this.playSoundButton.Location = new System.Drawing.Point(106, 112);
this.playSoundButton.Name = "playSoundButton";
this.playSoundButton.Size = new System.Drawing.Size(75, 23);
this.playSoundButton.TabIndex = 0;
this.playSoundButton.Text = "Play Sound";
this.playSoundButton.Click += new System.EventHandler(this.playSoundButton_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.playSoundButton);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
// </snippet1>
@@ -0,0 +1,121 @@
// <snippet1>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
namespace SoundPlayerPlayLoopingExample
{
public class Form1 : Form
{
private SoundPlayer Player = new SoundPlayer();
public Form1()
{
InitializeComponent();
}
private void playLoopingButton_Click(object sender, EventArgs e)
{
try
{
// Note: You may need to change the location specified based on
// the sounds loaded on your computer.
this.Player.SoundLocation = @"C:\Windows\Media\chimes.wav";
this.Player.PlayLooping();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error playing sound");
}
}
private void stopPlayingButton_Click(object sender, EventArgs e)
{
this.Player.Stop();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (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.playLoopingButton = new System.Windows.Forms.Button();
this.stopPlayingButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// playLoopingButton
//
this.playLoopingButton.Location = new System.Drawing.Point(12, 12);
this.playLoopingButton.Name = "playLoopingButton";
this.playLoopingButton.Size = new System.Drawing.Size(87, 23);
this.playLoopingButton.TabIndex = 0;
this.playLoopingButton.Text = "Play Looping";
this.playLoopingButton.UseVisualStyleBackColor = true;
this.playLoopingButton.Click += new System.EventHandler(this.playLoopingButton_Click);
//
// stopPlayingButton
//
this.stopPlayingButton.Location = new System.Drawing.Point(105, 12);
this.stopPlayingButton.Name = "stopPlayingButton";
this.stopPlayingButton.Size = new System.Drawing.Size(75, 23);
this.stopPlayingButton.TabIndex = 1;
this.stopPlayingButton.Text = "Stop";
this.stopPlayingButton.UseVisualStyleBackColor = true;
this.stopPlayingButton.Click += new System.EventHandler(this.stopPlayingButton_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(195, 51);
this.Controls.Add(this.stopPlayingButton);
this.Controls.Add(this.playLoopingButton);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button playLoopingButton;
private System.Windows.Forms.Button stopPlayingButton;
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
// </snippet1>

Some files were not shown because too many files have changed in this diff Show More